bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 46쪽
contracts. It's important to note that messages are executed in a 'set-and-forget' manner, meaning you won't receive immediate feedback about the success or failure of the call.
Nevertheless, obtaining the result of your call can be highly advantageous in the following scenarios:
* When you're instantiating a new contract and need to acquire the contract address.
* When you're executing an action and need to confirm that the result was successful. For instance, you might want to ensure that a specific token amount has been correctly transferred to your contract.
* When you wish to handle an error from your cross-contract call instead of rolling back the transaction.
To retrieve the result of the message sent from your smart contract, you will need to initiate a submessage. For further insights into the semantics of submessages and the order of submessage execution, you can refer to additional documentation located [here](https://github.com/CosmWasm/cosmwasm/blob/main/SEMANTICS.md#submessages).
## Creating a Submessage
A submessage encapsulates a CosmosMsg within a SubMsg structure:
```
pub struct SubMsg<T> {
pub id: u64, // reply_id that will be used to handle the reply
pub msg: CosmosMsg<T>, // message to be sent
pub gas_limit: Option<u64>, // gas limit for the submessage
pub reply_on: ReplyOn, // a flag to determine when the reply should be sent
}
```
The source code for the SubMsg struct can be located [here](https://github.com/CosmWasm/cosmwasm/blob/main/packages/std/src/results/submessages.rs).
Now, let's examine an illustration of instantiating a cw20 token using a submessage:
```
const INSTANTIATE_REPLY_ID = 1u64;
// Creating a message to create a new cw20 token
let instantiate_tx = WasmMsg::Instantiate {
admin: None,
code_id: msg.cw20_code_id,
msg: to_binary(&Cw20InstantiateMsg {
name: "new token".to_string(),
symbol: "nToken".to_string(),
decimals: 6,
initial_balances: vec![],
mint: Some(MinterResponse {
minter: env.contract.address.to_string(),
cap: None,
}),
})?,
funds: vec![],
label: "".to_string(),
};
// Creating a submessage that wraps the message above
let submessage = SubMsg::reply_on_success(instantiate_tx.into(), INSTANTIATE_REPLY_ID);
// Creating a response with the submessage
let response = Response::new().add_submessage(submessage);
```
## Reply Strategies
Submessages provide four distinct response options for the recipient contract to offer:
```
pub enum ReplyOn {
/// Always perform a callback after SubMsg is processed
Always,
/// Only callback if SubMsg returned an error, no callback on success case
Error,
/// Only callback if SubMsg was successful, no callback on error case
Success,
/// Never make a callback - this is like the original CosmosMsg semantics
Never,
}
```
Previously, we generated the submessage using the SubMsg::reply\_on\_success shortcut. Nevertheless, it's worth noting that we can also create a submessage while explicitly specifying the reply strategy.
```
let submessage = SubMsg {
gas_limit: None,
id: INSTANTIATE_REPLY_ID,
reply_on: ReplyOn::Success,
msg: instantiate_tx.into()
}
```
## Handling a Reply
To process the response from the other contract, the calling contract must incorporate a new entry point. Below, you'll find two examples illustrating how to manage these responses:
#### Instantiating a new contract:
```
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, _env: Env, msg: Reply) -> StdResult<Response> {
match msg.id {
INSTANTIATE_REPLY_ID => handle_instantiate_reply(deps, msg),
id => Err(StdError::generic_err(format!("Unknown reply id: {}", id))),
}
}
fn handle_instantiate_reply(deps: DepsMut, msg: Reply) -> StdResult<Response> {
// Handle the msg data and save the contract address
// See: https://github.com/CosmWasm/cw-plus/blob/main/packages/utils/src/parse_reply.rs
let res = parse_reply_instantiate_data(msg)?;
// Save res.contract_address
Ok(Response::new())
}
```
#### Handling a reply from a token transfer:
```
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(deps: DepsMut, msg: Reply) -> StdResult<Response> {
match msg.id {
CW20_TRANSFER_REPLY_ID => handle_transfer_reply(deps, msg),
id => Err(StdError::generic_err(format!("Unknown reply id: {}", id))),
}
}
fn handle_transfer_reply(deps: DepsMut, msg: Reply) -> StdResult<Response> {
// Handle the msg data and save the contract address
// See: https://github.com/CosmWasm/cw-plus/blob/main/packages/utils/src/parse_reply.rs
let data = msg.result.into_result().map_err(StdError::generic_err);
// Search for the transfer event
// If there are multiple transfers, you will need to find the right event to handle
let transfer_event = msg
.events
.iter()
.find(|e| {
e.attributes
.iter()
.any(|attr| attr.key == "action" && attr.value == "transfer")
})
.ok_or_else(|| StdError::generic_err(format!("unable to find transfer action"))?;
// Do whatever you want with the attributes in the transfer event
// Reference to the full event: https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw20-base/src/contract.rs#L239-L244
Ok(Response::new())
}
```
### Transmitting Context Between Contracts
In order to prevent reentrancy attacks, CosmWasm prohibits the storage of context within the contract memory. To propagate state between contracts, there are two available methods:
* All events produced by the submessage can be accessed from the Reply message.
* Temporary state can be stored using cw\_storage\_plus::Item and subsequently loaded into the reply handler.
# Simple and Complex States
### Simple State
The state serves as the repository for storing and accessing data within a smart contract. Conceptually, it operates in a manner akin to the database interaction layer found in conventional applications.
A basic approach to managing state entails the storage of a single entity. For instance, in the case of the cw20 contract, the TokenInfo is established and recorded during the contract's initialization phase.
Initially, a TokenInfo type is defined in state.rs:
```
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub struct TokenInfo {
pub name: String,
pub symbol: String,
pub decimals: u8,
pub total_supply: Uint128,
pub mint: Option<MinterData>,
}
```
Then the storage is initialized:
```
pub const TOKEN_INFO: Item<TokenInfo> = Item::new("token_info");
```
Within the contract, the instantiate function demonstrates the process of saving data to this:
```
let data = TokenInfo {
name: msg.name,
symbol: msg.symbol,
decimals: msg.decimals,
total_supply,
mint,
};
TOKEN_INFO.save(deps.storage, & data) ?;
```
### Complex State
In more intricate solutions, there might be a requirement to store supplementary information. One approach to accomplish this is by serializing comprehensive JSON data structures, which enables data retrieval using key-value pairs.
In the context of CW20, the association of addresses with their CW20 balances is accomplished using a Map data structure
```
pub const BALANCES: Map<&Addr, Uint128> = Map::new("balance");
```
You can locate the code for this right [here.](https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw20-base/src/state.rs#L35)
Here's an illustrative example of how to work with the value within the BALANCES map ([seen here](https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw20-base/src/contract.rs#L250-L258)), as demonstrated in the subsequent code snippet:
```
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
deps.storage,
&info.sender,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
```
There's a lot of complexity here, so let's dissect it step by step:
1. **deps.storage** is an input provided, originating from the contract context. Think of **deps** as similar to the **ctx** you might have encountered in the Cosmos SDK.
2. **\&rcpt\_addr** is a borrowed reference to the validated recipient address. It's been verified and confirmed as valid; otherwise, the "let" statement would have triggered an error. This reference corresponds to the key within the key/value pair.
3. The third statement consists of an anonymous function (lambda) that returns a **StdResult** and carries out a computation based on the current value of **balance**. In this context, **balance** signifies the value within the key/value pair, while **\&rcpt\_addr** serves as the key.
# Result and Option
In the Rust programming language, Result and Option are enum types that encompass values within their respective variants:
```
enum Option<T> {
Some(T),
// existence
None, // non-existence
}
enum Result<T, E> {
Ok(T),
// success
Err(E), // failure
}
```
## Result
Result is an enum type, Result\<T, E>, where both T and E are generics, symbolizing success and failure. Result types find common use in entry points and handlers:
**Ok(T)**: A Result container signifying success, containing the value T.
**Err(E)**: A Result container indicating failure, containing the value E.
Numerous contract entry points are of the type Result\<Response, ContractError. In this context, Response represents the Right or Success branch, while ContractError corresponds to the Left or failure case.
For instance, in the case of CW20-base, the execute function is typed as Result\<Response, ContractError. Specifically, for the function that corresponds to ExecuteMsg::Transfer, namely execute\_transfer, this demonstrates how the result is returned.
```
pub fn execute_transfer(
deps: DepsMut,
_env: Env,
info: MessageInfo,
recipient: String,
amount: Uint128,
) -> Result<Response, ContractError> {
if amount == Uint128::zero() {
return Err(ContractError::InvalidZeroAmount {});
}
let rcpt_addr = deps.api.addr_validate(&recipient)?;
BALANCES.update(
deps.storage,
&info.sender,
|balance: Option<Uint128>| -> StdResult<_> {
Ok(balance.unwrap_or_default().checked_sub(amount)?)
},
)?;
BALANCES.update(
deps.storage,
&rcpt_addr,
|balance: Option<Uint128>| -> StdResult<_> { Ok(balance.unwrap_or_default() + amount) },
)?;
let res = Response::new()
.add_attribute("action", "transfer")
.add_attribute("from", info.sender)
.add_attribute("to", recipient)
.add_attribute("amount", amount);
Ok(res)
}
```
## StdResult
### The Significance of StdResult
It is equally essential to remain vigilant about StdResult, given its common application in query handlers and the associated functions.
### Illustration from the Nameservice Contract
For instance, in the nameservice contract, you can readily identify the utilization of StdResult. This construct operates in a manner akin to Result but does not include a predefined error branch.
```
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::ResolveRecord { name } => query_resolver(deps, env, name),
QueryMsg::Config {} => to_binary(&config_read(deps.storage).load()?),
}
}
```
Let's examine the implementation of the query\_resolver:
```
fn query_resolver(deps: Deps, _env: Env, name: String) -> StdResult<Binary> {
let key = name.as_bytes();
let address = match resolver_read(deps.storage).may_load(key)? {
Some(record) => Some(String::from(&record.owner)),
None => None,
};
let resp = ResolveRecordResponse { address };
to_binary(&resp)
}
```
Precisely matching or unwrapping your container types is crucial to effectively access and manipulate the enclosed values.
## Option
### Handling Absence in Rust
In the Rust programming language, there is no concept of nil or null, a departure from many other widely used programming languages. Instead, Rust employs the Option type to capture the idea of presence or absence within a container type.
### The Option Enum Type
Option is an enum type that features two variants:
**Some()**: It wraps an inner value, which can be accessed using .unwrap().
**None**: This variant signifies the absence of a value and is frequently employed as a default or placeholder value when a value is either not yet known or cannot be determined.
#### Example Usage
The following code snippet provides an example of how Rust's Option is utilized to handle optional values of purchase\_price and transfer\_price
```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {
pub purchase_price: Option<Coin>,
pub transfer_price: Option<Coin>,
}
```
When dealing with instances of the InstantiateMsg mentioned earlier, there will be either an outcome or nothing. To address this situation, it is customary to utilize the match operator for pattern matching the two possible cases.
```
let address = match resolver_read(deps.storage).may_load(key)? {
Some(record) => Some(String::from( & record.owner)),
None => None,
};
```
If utilizing None to signify an error state, the conventional recommendation is to raise an error rather than dealing with the None value.
\ <br>
\ <br>
# Query
### **Understanding Querying**
Querying is a process employed to extract data from a database or access state information. The available query messages are typically located in either msg.rs or query.rs, depending on the structure chosen by the contract author.
### **Performing Queries**
Queries can be executed using an external client, such as an API or through the CLI, or within a contract. For further insights into this process, refer to the section on Querying contract state.
### **Querying in Read-Only Mode**
Queries interact with a contract's data store exclusively in a read-only mode. They can retrieve data and conduct additional processing as necessary. However, it's important to note that there is a gas limit associated with query operations.
### **Managing Queries**
Queries are represented as entries within the [QueryMsg](https://github.com/deus-labs/cw-contracts/blob/main/contracts/nameservice/src/msg.rs#L20) enum and are handled within the contract's Query function.
```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum QueryMsg {
// ResolveAddress returns the current address that the name resolves to
ResolveRecord { name: String },
Config {},
}
```
Subsequently, the contract proceeds to handle this within the query function.
```
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::ResolveRecord { name } => query_resolver(deps, env, name),
QueryMsg::Config {} => to_binary(&config_read(deps.storage).load()?),
}
}
```
In this context, query\_resolver serves as just another function, while config\_read acts as a helper function that encapsulates data store access.
# Events
## **Return Types in Entry Point Functions**
The typical return type for entry point functions is Result\<Response, ContractError, where Response acts as a container for Events in the Cosmos SDK.
### **Usage of Response Type**
In the context of a contract's entry point, like instantiate or execute, Response should be returned as the successful outcome. It can be declared as mutable and modified within the function's body. However, a more prevalent approach is to construct it at the end and return it if all computations have been successful. In the forthcoming examples, Response is wrapped by Ok since it is returned as part of a function yielding the Result type, with Response signifying the Right or success branch.
### **Query Entry Point Exception**
The Query entry point is an exception to this pattern, as it returns StdResult in accordance with the Cosmos SDK interface.
For a deeper understanding of the Response struct, you can explore the source code [here](https://github.com/CosmWasm/cosmwasm/blob/main/packages/std/src/results/response.rs#L65).
## **Basic Usage of Response**
The most straightforward use of Response involves:
```
Ok(Response::default ())
```
This is a common occurrence in instantiate functions when there is no message to be returned to the client. Nevertheless, in the majority of cases when dealing with the execute function, it is expected that a Response should be returned, like so.
```
let res = Response::new()
.add_attribute("action", "transfer")
.add_attribute("from", info.sender)
.add_attribute("to", recipient)
.add_attribute("amount", amount);
Ok(res)
```
**In-Depth Analysis of the Code Snippet**
This code snippet involves several additional steps, so let's delve deeper into its workings.
*To explore the source code for this example, you can access it by clicking* [*here.*](https://github.com/CosmWasm/cw-plus/blob/main/contracts/cw20-base/src/contract.rs#L239)
**Steps in the Code**
1. A new Response is generated.
2. Several key/value pairs are added to this Response.
3. The Response is returned, encapsulated within a Result type using Ok.
**Command-Line Interface Observations**
When you invoke your contract through the command-line interface (CLI), you'll notice these steps logged as part of the "raw\_log" response, alongside other SDK events.
**Utilizing add\_event**
Instead of solely appending attributes, the add\_event function can be utilized to include an unencapsulated event that can be interacted with by other clients or contracts.
# Math
## **Math Functions in CosmWasm**
The mathematical functions employed in CosmWasm are built upon standard Rust. However, there are helper functions provided for u128, u64, and decimal data types.
### **Uint128**
Uint128 is a lightweight wrapper for u128 that utilizes string-based JSON encoding and decoding. This enables the complete u128 range to be accessible for clients that process JSON numbers as floats, such as JavaScript and jq.
### **Uint64**
Uint64 is a minimal layer that wraps u64 and employs strings for JSON encoding and decoding. This approach allows the full u64 range to be leveraged by clients that convert JSON numbers to floats, like JavaScript and jq.
### **Decimal**
Decimal is a fixed-point decimal value characterized by 18 fractional digits. For example, Decimal(1\_000\_000\_000\_000\_000\_000) is equivalent to 1.0. The largest possible value that can be represented is 340282366920938463463.374607431768211455, which is calculated as (2^128 - 1) divided by 10^18.
# Migration
Migration involves the process of updating or replacing the code of an existing smart contract, and sometimes includes modifying state data.
CosmWasm simplifies the contract migration process. When a contract is instantiated, there is an optional admin field that can be configured. If left unspecified, the contract remains immutable. However, if an external account or governance contract is assigned as the admin, that entity gains the authority to initiate migration. The admin can also transfer ownership to another account or make the contract entirely immutable by setting the admin field to an empty value.
This is where the CW2 specification plays a vital role. It defines a special Singleton that holds the contract's name and version information, which must be stored by all CW2-compliant contracts during instantiation. When the migration function is triggered, the newly created contract can reference this information to determine if it's compatible with migrating from the previous contract.
The CW2 Specification introduces a set\_contract\_version function that should be used when instantiating a new contract through the instantiate function. For contracts undergoing migration, it's crucial to utilize the set\_contract\_version function as part of the migration logic within the migrate(...) function, rather than in the instantiate function, to update the contract's versioning during the migration process.
```
[codebox]
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"프로젝트로 돌아가기