3. integrate with smart contracts
To integrate with other CosmWasm contracts, it's crucial to understand what entry points are and how to use them. Entry points in a smart contract are the methods that allow interaction with it.
Smart contracts in CosmWasm define three primary entry points: instantiate, execute, and query.
- instantiate: This is the method that's called when the contract is deployed to the network. It's typically used to initialize the contract's state.
- execute: This method is called when a transaction is sent to the contract. It's used to update the contract's state.
- query: This method is called to read data from the contract's state. It doesn't alter the state.
When you are creating a smart contract that needs to interact with another contract, you need to look into what these entry points do, and handle the interaction within these methods. For this reason, you would need to know what parameters each method accepts and what it returns.
For example, if the other contract has an execute method that accepts a Transfer message, you need to know what fields the Transfer message expects.
In CosmWasm, inter-contract calls are facilitated using the CosmosMsg::Wasm(WasmMsg::Execute{})
message type. This allows your contract to define a set of messages that it wishes to send to other contracts on execution. These messages will be returned to the runtime and executed after your contract's execution is successfully completed.
The WasmMsg::Execute
type takes the following arguments:
- contract_addr: The address of the contract you wish to call.
- msg: The message you wish to send to the contract. This must be a JSON object that matches the contract's message schema.
- send: The coins you wish to transfer to the contract as part of the call.
Making Calls to the Other Contract's Entry Points
You can use the CosmosMsg::Wasm(WasmMsg::Execute{}) message type to interact with the other contract's execute method. Here's an example of how to do this:
// Construct the Transfer message for the other contract
let transfer_msg = to_binary(&Transfer {
recipient: deps.api.addr_humanize(&recipient_raw)?,
amount,
})?;
// Construct the WasmMsg
let msg = WasmMsg::Execute {
contract_addr: other_contract_addr.to_string(),
msg: transfer_msg,
send: vec![],
};
// Return the WasmMsg to be executed by the runtime
Ok(Response::new()
.add_attribute("action", "call_other_contract")
.add_message(msg))
In this example, Transfer is one of the entry points in the other contract. Keep in mind that the above is just for explanatory purpose, and we recommend you to check our guides to learn more.
It's important to remember that the WasmMsg::Execute
message will be executed after your contract's execution is successfully completed. If your contract's execution fails, the WasmMsg::Execute
message will not be executed.