5

I've been building unit tests in ink and have come across a strange issue. If I instantiate a contract multiple times, the account id is always the same. I thought the account id is the address of the contract, hence should be different between two contract instantiations.

Code:

let c1 = MyContract::new();
println!("{:?}", c1.env().account_id()); // prints AccountId([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

let c2 = MyContract::new();
println!("{:?}", c2.env().account_id()); // prints AccountId([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

let c3 = MyContract::new();
println!("{:?}", c3.env().account_id()); // prints AccountId([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

Shouldn't the account id be different?

1 Answer 1

5

Off-chain environment used in the unit testing is just a mock environment so there aren't any dedicated mapping created b/w addresses & contracts. Latter is just an object with some associated values (in context of ink! off-chain engine). So multiple contracts can have the same address.

You need to manually set the callee before initialising a contract otherwise your contract address will be same as the last set callee (which is by default [1;32]). Below is a sample implementation on how to do it.

let contract_addr: AccountId = AccountId::from([0xFF as u8; 32]);  
set_callee::<DefaultEnvironment>(contract_addr);
let mut contract = MyContract::default();

assert_eq!(contract.env().account_id(), contract_addr); // true
1
  • That works wonderfully, thanks for your help again! :)
    – goastler
    Commented May 5, 2023 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.