use crate::{MockApiBech32, MockApiBech32m};
use cosmwasm_std::testing::MockApi;
use cosmwasm_std::{instantiate2_address, Addr, Api, CanonicalAddr, StdResult, Storage};
use sha2::digest::Update;
use sha2::{Digest, Sha256};
const DEFAULT_PREFIX: &str = "cosmwasm";
pub trait IntoAddr {
fn into_addr(self) -> Addr;
fn into_addr_with_prefix(self, prefix: &'static str) -> Addr;
}
impl IntoAddr for &str {
fn into_addr(self) -> Addr {
MockApi::default().addr_make(self)
}
fn into_addr_with_prefix(self, prefix: &'static str) -> Addr {
MockApi::default().with_prefix(prefix).addr_make(self)
}
}
pub trait IntoBech32 {
fn into_bech32(self) -> Addr;
fn into_bech32_with_prefix(self, prefix: &'static str) -> Addr;
}
impl IntoBech32 for &str {
fn into_bech32(self) -> Addr {
MockApiBech32::new(DEFAULT_PREFIX).addr_make(self)
}
fn into_bech32_with_prefix(self, prefix: &'static str) -> Addr {
MockApiBech32::new(prefix).addr_make(self)
}
}
pub trait IntoBech32m {
fn into_bech32m(self) -> Addr;
fn into_bech32m_with_prefix(self, prefix: &'static str) -> Addr;
}
impl IntoBech32m for &str {
fn into_bech32m(self) -> Addr {
MockApiBech32m::new(DEFAULT_PREFIX).addr_make(self)
}
fn into_bech32m_with_prefix(self, prefix: &'static str) -> Addr {
MockApiBech32m::new(prefix).addr_make(self)
}
}
pub trait AddressGenerator {
fn contract_address(
&self,
api: &dyn Api,
_storage: &mut dyn Storage,
code_id: u64,
instance_id: u64,
) -> StdResult<Addr> {
let canonical_addr = instantiate_address(code_id, instance_id);
api.addr_humanize(&canonical_addr)
}
fn predictable_contract_address(
&self,
api: &dyn Api,
_storage: &mut dyn Storage,
_code_id: u64,
_instance_id: u64,
checksum: &[u8],
creator: &CanonicalAddr,
salt: &[u8],
) -> StdResult<Addr> {
let canonical_addr = instantiate2_address(checksum, creator, salt)?;
api.addr_humanize(&canonical_addr)
}
}
fn instantiate_address(code_id: u64, instance_id: u64) -> CanonicalAddr {
let mut key = Vec::<u8>::new();
key.extend_from_slice(b"wasm\0");
key.extend_from_slice(&code_id.to_be_bytes());
key.extend_from_slice(&instance_id.to_be_bytes());
let module = Sha256::digest("module".as_bytes());
Sha256::new()
.chain(module)
.chain(key)
.finalize()
.to_vec()
.into()
}
pub struct SimpleAddressGenerator;
impl AddressGenerator for SimpleAddressGenerator {}