-
Hi, I am exploring the For example, I have a contract that alters its behavior based on its current balance or the number of times it has been called. I'd like to set these parameters to specific values before running my tests. Here’s a snippet of a contract that I'm working on: pragma solidity ^0.8.0;
contract TestContract {
uint256 public contractBalance;
uint256 public callCount;
function changeBehavior() external payable {
contractBalance += msg.value;
callCount += 1;
}
function checkBehavior() external view returns (string memory) {
if (contractBalance > 10 ether && callCount > 100) {
return "Condition 1 met";
} else if (contractBalance > 5 ether && callCount > 50) {
return "Condition 2 met";
} else {
return "No conditions met";
}
}
} Is there a straightforward way to define the initial state of contractBalance and callCount before executing the contract through the emulator? Any advice or examples would be greatly appreciated. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hello @eNzueth, To initialize a custom contract state, you would first create an Here's how you could do it: fn main() {
// Create a custom AccountState
let mut storage = HashMap::new();
// Set the value of the contract slot 0x0 (uint256 public contractBalance)
storage.insert([0u8; 32], [5u8; 32]);
// Create the AccountState to represent the contract state
let account_state = AccountState {
nonce: 0,
balance: [10u8; 32], // Initial balance
storage,
code_hash: [0u8; 32]
};
// Create an EvmState with your custom AccountState
let mut accounts = HashMap::new();
// You have to compute the contract address before
let contract_address = [0u8; 20];
// Set the contract state
accounts.insert(contract_address, account_state);
let evm_state = EvmState {
accounts,
codes: HashMap::new(),
logs: Vec::new(),
static_mode: false,
provider: None,
};
// Now pass the EvmState to the Runner::new function, it will be used as default state
let runner = Runner::new(
[0u8; 20],
None,
None,
None,
None,
Some(evm_state),
);
} In this example:
This way, you can initialize the state of your contract before executing it through the emulator. Hope this helps! |
Beta Was this translation helpful? Give feedback.
Hello @eNzueth,
To initialize a custom contract state, you would first create an
AccountState
object to represent the state of your contract, and then encapsulate that within anEvmState
object which you would use to create a new runner usingRunner::new
function.Here's how you could do it: