Skip to content

Commit d20aca7

Browse files
authored
Merge pull request #2217 from CosmWasm/match-MockApi-mock_env
Let mock_env return a contract address that is compatible with MockApi
2 parents 9a1c80c + b74215c commit d20aca7

File tree

4 files changed

+135
-12
lines changed

4 files changed

+135
-12
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,15 @@ and this project adheres to
2929
[`is_human_readable`](https://docs.rs/serde/latest/serde/trait.Serializer.html#method.is_human_readable).
3030
This is to make these types more efficient when used together with the new
3131
[MessagePack](https://msgpack.org) encoding. ([#2118])
32+
- cosmwasm-std: Let `mock_env` return a contract address that is valid bech32
33+
and uses the same bech32 prefix as `MockApi`; Change `MOCK_CONTRACT_ADDR`
34+
value to match the contract address from `mock_env`. ([#2211])
35+
- cosmwasm-vm: Let `mock_env` return a contract address that is valid bech32 and
36+
uses the same bech32 prefix as `MockApi`; Change `MOCK_CONTRACT_ADDR` value to
37+
match the contract address from `mock_env`. ([#2211])
3238

3339
[#2118]: https://github.com/CosmWasm/cosmwasm/pull/2118
40+
[#2211]: https://github.com/CosmWasm/cosmwasm/issues/2211
3441

3542
## [2.1.3] - 2024-08-08
3643

packages/std/src/testing/mock.rs

Lines changed: 63 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ use crate::{ChannelResponse, IbcQuery, ListChannelsResponse, PortIdResponse};
5252
use crate::{Decimal256, DelegationRewardsResponse, DelegatorValidatorsResponse};
5353
use crate::{RecoverPubkeyError, StdError, StdResult, SystemError, VerificationError};
5454

55-
pub const MOCK_CONTRACT_ADDR: &str = "cosmos2contract";
55+
pub const MOCK_CONTRACT_ADDR: &str =
56+
"cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs";
5657

5758
/// Creates all external requirements that can be injected for unit tests.
5859
///
@@ -337,12 +338,62 @@ fn validate_length(bytes: &[u8]) -> StdResult<()> {
337338
}
338339
}
339340

340-
/// Returns a default environment with height, time, chain_id, and contract address
341+
/// Returns a default environment with height, time, chain_id, and contract address.
341342
/// You can submit as is to most contracts, or modify height/time if you want to
342343
/// test for expiration.
343344
///
344345
/// This is intended for use in test code only.
346+
///
347+
/// The contract address uses the same bech32 prefix as [`MockApi`](crate::testing::MockApi). While
348+
/// this is good for the majority of users, you might need to create your `Env`s
349+
/// differently if you need a valid address using a different prefix.
350+
///
351+
/// ## Examples
352+
///
353+
/// Create an env:
354+
///
355+
/// ```
356+
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
357+
/// use cosmwasm_std::testing::mock_env;
358+
///
359+
/// let env = mock_env();
360+
/// assert_eq!(env, Env {
361+
/// block: BlockInfo {
362+
/// height: 12_345,
363+
/// time: Timestamp::from_nanos(1_571_797_419_879_305_533),
364+
/// chain_id: "cosmos-testnet-14002".to_string(),
365+
/// },
366+
/// transaction: Some(TransactionInfo { index: 3 }),
367+
/// contract: ContractInfo {
368+
/// address: Addr::unchecked("cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs"),
369+
/// },
370+
/// });
371+
/// ```
372+
///
373+
/// Mutate and reuse environment:
374+
///
375+
/// ```
376+
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
377+
/// use cosmwasm_std::testing::mock_env;
378+
///
379+
/// let env1 = mock_env();
380+
///
381+
/// // First test with `env1`
382+
///
383+
/// let mut env2 = env1.clone();
384+
/// env2.block.height += 1;
385+
/// env2.block.time = env1.block.time.plus_seconds(6);
386+
///
387+
/// // `env2` is one block and 6 seconds later
388+
///
389+
/// let mut env3 = env2.clone();
390+
/// env3.block.height += 1;
391+
/// env3.block.time = env2.block.time.plus_nanos(5_500_000_000);
392+
///
393+
/// // `env3` is one block and 5.5 seconds later
394+
/// ```
345395
pub fn mock_env() -> Env {
396+
let contract_addr = MockApi::default().addr_make("cosmos2contract");
346397
Env {
347398
block: BlockInfo {
348399
height: 12_345,
@@ -351,7 +402,7 @@ pub fn mock_env() -> Env {
351402
},
352403
transaction: Some(TransactionInfo { index: 3 }),
353404
contract: ContractInfo {
354-
address: Addr::unchecked(MOCK_CONTRACT_ADDR),
405+
address: contract_addr,
355406
},
356407
}
357408
}
@@ -688,7 +739,8 @@ pub struct BankQuerier {
688739
#[allow(dead_code)]
689740
/// BTreeMap<denom, amount>
690741
supplies: BTreeMap<String, Uint128>,
691-
/// BTreeMap<address, coins>
742+
/// A map from address to balance. The address is the String conversion of `Addr`,
743+
/// i.e. the bech32 encoded address.
692744
balances: BTreeMap<String, Vec<Coin>>,
693745
/// Vec<Metadata>
694746
denom_metadata: BTreeMap<Vec<u8>, DenomMetadata>,
@@ -698,7 +750,7 @@ impl BankQuerier {
698750
pub fn new(balances: &[(&str, &[Coin])]) -> Self {
699751
let balances: BTreeMap<_, _> = balances
700752
.iter()
701-
.map(|(s, c)| (s.to_string(), c.to_vec()))
753+
.map(|(address, balance)| (address.to_string(), balance.to_vec()))
702754
.collect();
703755

704756
BankQuerier {
@@ -1204,6 +1256,12 @@ mod tests {
12041256
const ETH_BLOCK_HEADER: &[u8] =
12051257
include_bytes!("../../../crypto/testdata/eth-headers/1699693797.394876721s.json");
12061258

1259+
#[test]
1260+
fn mock_env_matches_mock_contract_addr() {
1261+
let contract_address = mock_env().contract.address;
1262+
assert_eq!(contract_address, Addr::unchecked(MOCK_CONTRACT_ADDR));
1263+
}
1264+
12071265
#[test]
12081266
fn mock_info_works() {
12091267
#[allow(deprecated)]

packages/vm/src/instance.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -914,7 +914,7 @@ mod tests {
914914

915915
let report2 = instance.create_gas_report();
916916
assert_eq!(report2.used_externally, 251);
917-
assert_eq!(report2.used_internally, 16995280);
917+
assert_eq!(report2.used_internally, 17457465);
918918
assert_eq!(report2.limit, LIMIT);
919919
assert_eq!(
920920
report2.remaining,
@@ -1105,7 +1105,7 @@ mod tests {
11051105
.unwrap();
11061106

11071107
let init_used = orig_gas - instance.get_gas_left();
1108-
assert_eq!(init_used, 16995531);
1108+
assert_eq!(init_used, 17457716);
11091109
}
11101110

11111111
#[test]
@@ -1130,7 +1130,7 @@ mod tests {
11301130
.unwrap();
11311131

11321132
let execute_used = gas_before_execute - instance.get_gas_left();
1133-
assert_eq!(execute_used, 19589666);
1133+
assert_eq!(execute_used, 21041196);
11341134
}
11351135

11361136
#[test]
@@ -1173,6 +1173,6 @@ mod tests {
11731173
);
11741174

11751175
let query_used = gas_before_query - instance.get_gas_left();
1176-
assert_eq!(query_used, 11942871);
1176+
assert_eq!(query_used, 12631261);
11771177
}
11781178
}

packages/vm/src/testing/mock.rs

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ use super::storage::MockStorage;
1010
use crate::backend::unwrap_or_return_with_gas;
1111
use crate::{Backend, BackendApi, BackendError, BackendResult, GasInfo};
1212

13-
pub const MOCK_CONTRACT_ADDR: &str = "cosmwasmcontract"; // TODO: use correct address
13+
pub const MOCK_CONTRACT_ADDR: &str =
14+
"cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs";
15+
1416
/// Default gas multiplier in wasmd.
1517
/// See https://github.com/CosmWasm/wasmd/blob/v0.51.0/x/wasm/types/gas_register.go#L34
1618
const WASMD_GAS_MULTIPLIER: u64 = 140_000;
@@ -216,12 +218,62 @@ fn validate_length(bytes: &[u8]) -> Result<(), BackendError> {
216218
}
217219
}
218220

219-
/// Returns a default environment with height, time, chain_id, and contract address
221+
/// Returns a default environment with height, time, chain_id, and contract address.
220222
/// You can submit as is to most contracts, or modify height/time if you want to
221223
/// test for expiration.
222224
///
223225
/// This is intended for use in test code only.
226+
///
227+
/// The contract address uses the same bech32 prefix as [`MockApi`](crate::testing::MockApi). While
228+
/// this is good for the majority of users, you might need to create your `Env`s
229+
/// differently if you need a valid address using a different prefix.
230+
///
231+
/// ## Examples
232+
///
233+
/// Create an env:
234+
///
235+
/// ```
236+
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
237+
/// use cosmwasm_vm::testing::mock_env;
238+
///
239+
/// let env = mock_env();
240+
/// assert_eq!(env, Env {
241+
/// block: BlockInfo {
242+
/// height: 12_345,
243+
/// time: Timestamp::from_nanos(1_571_797_419_879_305_533),
244+
/// chain_id: "cosmos-testnet-14002".to_string(),
245+
/// },
246+
/// transaction: Some(TransactionInfo { index: 3 }),
247+
/// contract: ContractInfo {
248+
/// address: Addr::unchecked("cosmwasm1jpev2csrppg792t22rn8z8uew8h3sjcpglcd0qv9g8gj8ky922tscp8avs"),
249+
/// },
250+
/// });
251+
/// ```
252+
///
253+
/// Mutate and reuse environment:
254+
///
255+
/// ```
256+
/// # use cosmwasm_std::{Addr, BlockInfo, ContractInfo, Env, Timestamp, TransactionInfo};
257+
/// use cosmwasm_vm::testing::mock_env;
258+
///
259+
/// let env1 = mock_env();
260+
///
261+
/// // First test with `env1`
262+
///
263+
/// let mut env2 = env1.clone();
264+
/// env2.block.height += 1;
265+
/// env2.block.time = env1.block.time.plus_seconds(6);
266+
///
267+
/// // `env2` is one block and 6 seconds later
268+
///
269+
/// let mut env3 = env2.clone();
270+
/// env3.block.height += 1;
271+
/// env3.block.time = env2.block.time.plus_nanos(5_500_000_000);
272+
///
273+
/// // `env3` is one block and 5.5 seconds later
274+
/// ```
224275
pub fn mock_env() -> Env {
276+
let contract_addr = MockApi::default().addr_make("cosmos2contract");
225277
Env {
226278
block: BlockInfo {
227279
height: 12_345,
@@ -230,7 +282,7 @@ pub fn mock_env() -> Env {
230282
},
231283
transaction: Some(TransactionInfo { index: 3 }),
232284
contract: ContractInfo {
233-
address: Addr::unchecked(MOCK_CONTRACT_ADDR),
285+
address: Addr::unchecked(contract_addr),
234286
},
235287
}
236288
}
@@ -249,6 +301,12 @@ mod tests {
249301
use super::*;
250302
use cosmwasm_std::coins;
251303

304+
#[test]
305+
fn mock_env_matches_mock_contract_addr() {
306+
let contract_address = mock_env().contract.address;
307+
assert_eq!(contract_address, Addr::unchecked(MOCK_CONTRACT_ADDR));
308+
}
309+
252310
#[test]
253311
fn mock_info_works() {
254312
let info = mock_info("my name", &coins(100, "atom"));

0 commit comments

Comments
 (0)