bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 45쪽
's time to deploy it to the XIOND testnet and begin interacting with your smart contract. You can use the XION CLI, XION Developer CLI, or the xiond.js, depending on your preference.
## Deploy contract
On the "Compile Contract" page, we've created a binary executable in the form of a WebAssembly (wasm) file. You have the option to upload this code to the blockchain. After the upload process is finished, you'll be able to retrieve the bytecode for verification purposes.
### Deploy using XIOND
ext, you'll store the WebAssembly (wasm) bytecode of the "cw\_namespace" contract on the blockchain and acquire the associated code ID. This code ID will be essential for creating an instance of the "cw\_namespace" contract later in the process.
Replace "mywallet" with the name of the wallet you established during the environment setup on the previous page.
Execute the following commands to store the contract on chain:
{% code fullWidth="true" %}
```sh
RES=$(xiond tx wasm store artifacts/cw_nameservice.wasm --from mywallet $TXFLAG -y --output json)
```
{% endcode %}
{% hint style="info" %}
The TXFLAG env var was set in the [Setting Up Environment](/en/others/archived/cosmwasm-resources/introductory-section/setting-up-environment) section. Please refer to it.
{% endhint %}
The response contains the Code Id of the uploaded wasm binary:
```sh
echo $RES
```
The following is a simpler method to obtain the Code ID from the response:
```bash
CODE_ID=$(echo $RES | jq -r '.logs[0].events[] | select(.type=="store_code") | .attributes[] | select(.key=="code_id") | .value')
```
```bash
echo $CODE_ID
```
To view the contracts instantiated with the CODE\_ID generated above, execute the following command:
```bash
xiond query wasm list-contract-by-code $CODE_ID $NODE --output json
```
The response should be an empty list as no contracts have been instantiated at this point.
```
{"contracts":[],"pagination":{"next_key":null,"total":"0"}}
```
Before proceeding to instantiate a contract using the Code ID and interact with it, let's first confirm that the code stored on the blockchain matches the cw\_namespace.wasm binary you uploaded.
To do this, download the wasm binary from the blockchain and perform a comparison with the original one:
```bash
xiond query wasm code $CODE_ID $NODE download.wasm
```
Both binaries should be identical:
```bash
diff artifacts/cw_nameservice.wasm download.wasm
```
{% hint style="info" %}
If the 'diff' command produces no output, it signifies that the two files being compared are identical.
{% endhint %}
## Instantiating the contract
You can now create an instance of the wasm contract. After instantiation, you can make queries and execute transactions.
### Instantiate using xiond
```bash
# Prepare the instantiation message
INIT='{"purchase_price":{"amount":"100","denom":"uxion"},"transfer_price":{"amount":"999","denom":"uxion"}}'
# Instantiate the contract
xiond tx wasm instantiate $CODE_ID "$INIT" --from mywallet --label "name service" $TXFLAG -y --no-admin
```
## Contract Interaction
Now that the contract is instantiated, you can register a name and transfer it to another address by paying the transfer fee.
### Interact using xiond
```bash
# Register a name for the wallet address
REGISTER='{"register":{"name":"fred"}}'
xiond tx wasm execute $CONTRACT "$REGISTER" --amount 100uxion --from wallet $TXFLAG -y
# Query the owner of the name record
NAME_QUERY='{"resolve_record": {"name": "fred"}}'
xiond query wasm contract-state smart $CONTRACT "$NAME_QUERY" $NODE --output json
# {"data":{"address":"xion1pze5wsf0dg0fa4ysnttugn0m22ssf3t4a9yz3h"}}
# Transfer the ownership of the name record to wallet2 (change the "to" address to wallet2 generated during environment setup)
wasmd keys list
TRANSFER='{"transfer":{"name":"fred","to":"xion1lwcrr9ktsmn2f7fej6gywxcm8uvxlzz5ch40hm"}}'
xiond tx wasm execute $CONTRACT "$TRANSFER" --amount 999uxion --from wallet $TXFLAG -y
# Query the record owner again to see the new owner address:
NAME_QUERY='{"resolve_record": {"name": "fred"}}'
xiond query wasm contract-state smart $CONTRACT "$NAME_QUERY" $NODE --output json
# {"data":{"address":"xion1lwcrr9ktsmn2f7fej6gywxcm8uvxlzz5ch40hm"}}
```
## <br>
<br>
# Integrate with Smart Contracts
For seamless integration with other CosmWasm contracts, it's essential to grasp the concept of entry points and their utilization. Entry points in a smart contract serve as the means through which interactions occur.
In CosmWasm smart contracts, three fundamental entry points are defined: instantiate, execute, and query.
* **instantiate**: This method is invoked during the contract's deployment on the network. Its primary purpose is to set up and initialize the contract's state.
* **execute**: This method gets called when a transaction is sent to the contract. Its role is to modify and update the contract's state based on the transaction's input.
* **query**: This method is used exclusively for reading data from the contract's state. It does not make any changes to the state itself.
When developing a smart contract that requires interaction with another contract, it's essential to thoroughly understand the functionality of these entry points and manage the interaction within these methods. Consequently, you'll need to acquaint yourself with the parameters accepted by each method and the values they return.
For instance, if the other contract features an execute method that takes a **Transfer** message as input, it's imperative to be well-versed in the specific fields and data that the **Transfer** message expects. This knowledge is crucial for seamless and error-free integration between the two contracts.
In CosmWasm, inter-contract calls are enabled through the use of the **CosmosMsg::Wasm(WasmMsg::Execute{})** message type. This feature allows your contract to specify a series of messages it intends to dispatch to other contracts during execution. These messages will be passed back to the runtime and executed once your contract's execution is successfully completed.
The **WasmMsg::Execute** type accepts the following parameters:
* **contract\_addr:** The address of the contract you intend to invoke.
* **msg:** The message you want to transmit to the contract. This message must adhere to the contract's message schema and be formatted as a JSON object.
* **send:** The coins you wish to transfer to the contract as part of the call.
## Making Calls to the Other Contract's Entry Points
To engage with the execute method of another contract, you can employ the **CosmosMsg::Wasm(WasmMsg::Execute{})** message type. Here's an illustrative example of how to achieve this:
```rust
// 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 instance, **Transfer** serves as one of the entry points in the other contract. Please note that the above illustration is solely for explanatory purposes.
It's crucial to bear in mind that the **WasmMsg::Execute message** will only execute after the successful completion of your contract's execution. In the event of a failure in your contract's execution, the **WasmMsg::Execute message** will not be executed.
##
# Next Steps
Here are some recommended next steps for delving deeper into the world of CosmWasm:
* [**cw-awesome**](https://github.com/CosmWasm/awesome-cosmwasm): A thoughtfully curated compilation of valuable CosmWasm resources.
* [**cw-template**](https://github.com/CosmWasm/cw-template): An introductory CosmWasm project template. Instead of directly cloning the repository, refer to the README for instructions on utilizing cargo-generate to create your project structure.
* [**cw-plus**](https://github.com/CosmWasm/cw-plus): A collection of enterprise-ready smart contracts meticulously crafted to safeguard substantial assets. These contracts are continually enhanced and maintained by Confio. You'll find top-tier smart contracts developed by the community hosted here as well.
* [**cw-contracts**](https://github.com/deus-labs/cw-contracts): A repository containing a selection of community-crafted smart contracts. We warmly welcome contributions from the community to enhance this repository further.
Exploring CosmWasm further is immensely beneficial as it equips users with the knowledge and skills needed to harness the full potential of blockchain smart contracts. This understanding enables users to build secure, customized solutions, stay updated with the latest advancements, and more within the thriving blockchain industry.
# Contract Semantics
The purpose of this document is to provide a clear understanding of how a CosmWasm contract engages with its surrounding context. There are primarily two categories of actions involved: mutating actions, which are equipped with DepsMut and have the capability to alter the blockchain's state, and query actions, which execute on a single node with restricted read-only access to the data.
## Execution
The upcoming section will delve into the workings of the execute call. It's crucial to emphasize that these same principles are applicable to other mutating actions like instantiate, migrate, sudo, and more.
## **Understanding the Cosmos SDK and Transaction Processing**
Before delving into the details of CosmWasm, it is essential to explore the semantics governed by the blockchain framework it integrates with – the Cosmos SDK. This framework is built upon the Tendermint BFT Consensus Engine. To gain a comprehensive understanding, let's break down the transaction processing both before they enter CosmWasm and after they exit.
**Pre-Execution Processing**
In the initial stage, the Tendermint engine strives to achieve a 2/3+ consensus on a list of transactions earmarked for inclusion in the next block. This is accomplished without actually executing the transactions. They undergo a minimal pre-filtering by the Cosmos SDK module, verifying their validity in terms of format, gas fees adequacy, and being signed by an account with sufficient funds to cover the fees. Consequently, some transactions that result in errors may still find their way into a block.
**Block Commitment**
Once a block is committed, typically occurring every 5 seconds or so, the transactions are processed sequentially by the Cosmos SDK. Each transaction yields either a result or an error, accompanied by event logs, all of which are recorded in the TxResults section of the ensuing block. The AppHash, Merkle proof, or blockchain state generated after executing the block is also included in the next block.
**Transaction Handling by Cosmos SDK's BaseApp**
Cosmos SDK's BaseApp handles each transaction within an isolated context. Initially, it verifies all signatures and deducts the applicable gas fees. It establishes a "Gas Meter" to restrict execution to the amount of gas covered by the fees. Subsequently, it creates an isolated context for transaction execution. This design allows the code to read the current chain state after the last transaction's completion, but any write operations are confined to a cache that can be either committed or rolled back in case of an error.
**Handling of Multiple Messages in a Transaction**
A transaction may consist of multiple messages, with each message being executed sequentially under the same context and gas limit. If all messages succeed, the context is committed to the underlying blockchain state, and the results of all messages are stored in the TxResult. However, if one message encounters an error, all subsequent messages are bypassed, and any state changes are reverted. This mechanism ensures the crucial property of atomicity.
This understanding of the Cosmos SDK and transaction processing provides a solid foundation for comprehending how CosmWasm contracts interact within this ecosystem.
Consider the following, suppose both Aria and Toby jointly authorize a transaction comprising two messages. In this transaction, Aria initiates a payment of 1,000 ATOM to Toby, while Toby initiates a payment of 50 ETH to Aria. However, if Toby lacks the necessary funds in his account to cover his payment, not only will Toby's payment be canceled, but Aria's payment will also be rolled back. This behavior is akin to how a conventional database transaction functions.
Within the Cosmos ecosystem, the x/wasm module stands as a custom component of the Cosmos SDK. It specializes in processing specific messages, leveraging them to upload, instantiate, and execute smart contracts. Specifically, it accepts a properly signed MsgExecuteContract and directs it to Keeper.Execute. Here, the module loads the pertinent smart contract and invokes the execute function on it.
It's worth noting that this method can yield one of two outcomes: either success, accompanied by relevant data and events, or an error. In the event of an error, the entire transaction within the block will be reversed. It is within this context that our contract handles the execute call.
### Basic execution
When implementing a contract, we provide the following entry point:
```
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> { }
```
When utilizing DepsMut, this function gains the capability to both read from and write to the underlying Storage. Additionally, it can utilize the Api for address validation and perform queries on the state of other contracts or native modules. Upon completion, it provides one of two outcomes: either Ok(Response) or Err(ContractError). Now, let's explore the subsequent steps:
In the event it returns Err, this error is converted into a string representation (err.to\_string()), and this string is subsequently returned to the SDK module. All alterations to the state are undone, and x/wasm forwards this error message, which generally results in the termination of the transaction and the transmission of the same error message to the external caller.
If it returns Ok, the Response object is then parsed and processed. Let's delve into the various components of this process:
```
pub struct Response<T = Empty>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
/// Optional list of "subcalls" to make. These will be executed in order
/// (and this contract's subcall_response entry point invoked)
/// *before* any of the "fire and forget" messages get executed.
pub submessages: Vec<SubMsg<T>>,
/// After any submessages are processed, these are all dispatched in the host blockchain.
/// If they all succeed, then the transaction is committed. If any fail, then the transaction
/// and any local contract state changes are reverted.
pub messages: Vec<CosmosMsg<T>>,
/// The attributes that will be emitted as part of a "wasm" event
pub attributes: Vec<Attribute>,
pub data: Option<Binary>,
}
```
Within the Cosmos SDK, a transaction provides users with a set of events, accompanied by an optional "data result." This result is hashed and incorporated into the hash of the next block, ensuring its verifiability and capacity to convey crucial state information. However, it's worth noting that client applications typically place greater emphasis on events. The result is also commonly utilized for transmitting data between contracts or modules within the SDK. It's important to mention that the ResultHash specifically encompasses the Code (non-zero values indicate an error) and the Result (data) stemming from the transaction. While events and logs can be accessed through queries, it's essential to note that no light-client proofs are available for these components.
If the contract sets data, this data will be returned in the Result field. Additionally, there is a list of {key, value} pairs known as attributes, which will be appended to a default event.
To the client, the final result takes the following format:
```
{
"type": "wasm",
"attributes": [
{ "key": "contract_addr", "value": "cosmos1234567890qwerty" },
{ "key": "custom-key-1", "value": "custom-value-1" },
{ "key": "custom-key-2", "value": "custom-value-2" }
]
}
```
## Dispatching Messages
Now, let's proceed to discuss the messages field. While some contracts operate exclusively within their own scope, like a CW20 contract that solely manages balance adjustments during transfers, many contracts have the need to transfer tokens (native or CW20) or invoke other contracts for more intricate operations. This is where messages play a pivotal role. We provide a CosmosMsg, which serves as a serializable representation of any external call that a contract can initiate.
For instance, when the stargate feature flag is enabled, it takes the following form:
```
pub enum CosmosMsg<T = Empty>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
Bank(BankMsg),
/// This can be defined by each blockchain as a custom extension
Custom(T),
Staking(StakingMsg),
Distribution(DistributionMsg),
Stargate {
type_url: String,
value: Binary,
},
Ibc(IbcMsg),
Wasm(WasmMsg),
}
```
# Message
Interacting with a CosmWasm smart contract involves the use of messages. These messages are typically documented in a msg.rs file within the contract's codebase.
One of the fundamental messages is the "instantiate" message. This message is responsible for creating a new instance of a CosmWasm smart contract on the blockchain. In the contract's codebase, you'll usually find this message defined as "InstantiateMsg" in the msg.rs file. Subsequently, this message is passed to an "instantiate" function located in the main contract.rs file for further processing.
While the examples provided here are fairly straightforward, it's understandable if you have questions about the specific arguments that can be included in these messages. To gain a deeper understanding, you can refer to the contract's schema folder, which typically contains at least two pertinent files:
* "instantiate\_msg.json" - This file outlines the expected structure and data types for the "instantiate" message.
* "execute\_msg.json" - Within this file, you can find details about the expected structure and data types for each of the messages that the contract can utilize to perform various actions.
\
Contracts with extensive APIs may contain numerous schema files. Delve into these files to locate the specific message or command you are in search of.
In the example contract for nameservice, after the contract has been instantiated, you will discover that there are only two valid messages available:
```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
Register { name: String },
Transfer { name: String, to: String },
}
```
You can find the context for this code[ here](https://github.com/deus-labs/cw-contracts/blob/main/contracts/nameservice/src/msg.rs#L13).
Following that, the ExecuteMsg message is processed within the contract.rs file. Each of the enum values can be managed in the execute function as shown below:
```
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
match msg {
ExecuteMsg::Register { name } => execute_register(deps, env, info, name),
ExecuteMsg::Transfer { name, to } => execute_transfer(deps, env, info, name, to),
}
}
```
You can access the source code for the execute function [here](https://github.com/deus-labs/cw-contracts/blob/main/contracts/nameservice/src/contract.rs#L31).
# Submessages
Messages serve as a means to interact with both SDK modules and CW smart 프로젝트로 돌아가기