Instantiating CosmWasm Contract
In this section, we elucidate the process of initializing a smart contract. This is achieved by presenting the structure of the "InstantiateMsg" passed during contract creation and the "Instantiate" function that is executed when the contract is initiated.
Explanation
The InstantiateMsg serves as the initialization message, responsible for handling the variables provided when the contract is instantiated.
This function can be located within the msg.rs file.
/// Variables for contract instantiation.
/// Exclude variables susceptible to replay attacks or secret data.
pub struct InstantiateMsg {
pub sent_message: String,
}Instantiate
Upon the creation of the contract, the instantiate function configures the initial state of the smart contract, performs essential validations, and can act in a manner similar to an execute message.
You can find this function in the contract.rs file:
pub fn instantiate(
deps: DepsMut,
_env: Env,
_info: MessageInfo,
msg: InstantiateMsg,
) -> Result<Response, ContractError> {
// Initialize contract's state.
let state = State {
global_var: msg.sent_message,
};
// Save state to the blockchain.
STATE.save(deps.storage, &state)?;
Ok(Response::new().add_attribute("instantiated", "true"))
}
Example
To instantiate contracts using CosmWasm, you should generate the following files: lib.rs, contract.rs, msg.rs, error.rs, state.rs, and helpers.rs.
lib.rs
contract.rs
msg.rs
error.rs
state.rs
helpers.rs
Last updated
Was this helpful?