bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 47쪽
);
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(deps: DepsMut, env: Env, info: MessageInfo, msg: InstantiateMsg) -> Response {
// Use CW2 to set the contract version, this is needed for migrations
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
}
```
In the case of a migrating contract, aside from employing the set\_contract\_version function, you can also make use of the get\_contract\_version function to ascertain the previous version of the contract. Ensuring, for instance, that the update occurs only if the version being upgraded is more recent than the original contract version is of paramount importance.
```
[codebox]
use semver::Version;
// Migrate contract if version is lower than current version
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, _msg: Empty) -> Result<Response, ContractError> {
let version: Version = CONTRACT_VERSION.parse()?;
let storage_version: Version = get_contract_version(deps.storage)?.version.parse()?;
if storage_version < version {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// If state structure changed in any contract version in the way migration is needed, it
// should occur here
}
Ok(Response::new())
}
```
Both the set\_contract\_version and get\_contract\_version methods function with an Item data structure provided by cw\_storage\_plus, which is responsible for managing this information.
```
[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct ContractVersion {
/// contract is a globally unique identifier for the contract.
/// it should build off standard namespacing for whichever language it is in,
/// and prefix it with the registry we use.
/// For rust we prefix with `crates.io:`, to give us eg. `crates.io:cw20-base`
pub contract: String,
/// version is any string that this implementation knows. It may be simple counter "1", "2".
/// or semantic version on release tags "v0.7.0", or some custom feature flag list.
/// the only code that needs to understand the version parsing is code that knows how to
/// migrate from the given contract (and is tied to it's implementation somehow)
pub version: String,
}
```
Therefore, an example in serialized form may look like this:
```
{
"contract": "crates.io:cw20-base",
"version": "v0.1.0"
}
```
## Setting up a contract for Migrations
Executing a contract migration involves three sequential steps. Firstly, create an updated version of the contract you intend to modify. Next, deploy the new code onto the blockchain, but refrain from instantiating it. Finally, employ a dedicated MsgMigrateContract transaction to direct the old contract toward the new code, thus completing the migration process.
It's essential to note that during the migration process, the migrate function defined in the new contract is the one that gets executed, not the migrate function from the old code. Therefore, it is imperative for the new contract code to feature a properly defined migrate function that is appropriately exported as an entry point.
```
use cosmwasm_std::{
Empty, Env, DepsMut, Response,
};
use crate::error::ContractError;
use cosmwasm_std::entry_point;
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, _msg: Empty) -> Result<Response, ContractError> {
}
```
The migrate function offers the capability to make specific and granular changes to the State, akin to a database migration.
In the event that the migrate function returns an error, the transaction will terminate, all State alterations will be rolled back, and the migration will not proceed.
Listed below are various migration scenarios to provide insight into common use cases.
### Basic Contract Migration
This type of migration is one of the most commonly encountered scenarios. It involves a straightforward replacement of a contract's code. It's important to note that there are no safety checks in place, as there is no verification of a cw2::set\_contract\_version.
```
use cosmwasm_std::{ Env, DepsMut, Response };
use crate::error::ContractError;
use crate::msg::{ MigrateMsg };
use cosmwasm_std::entry_point;
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
// No state migrations performed, just returned a Response
Ok(Response::default())
}
```
### Migration Based on Code Version and Contract Name
This is a more extensive migration example. The migrate function guarantees the following:
1. Migration from a contract of the same type by verifying its name.
2. Upgrading from an older version of the contract by checking its version.
```
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
let ver = cw2::get_contract_version(deps.storage)?;
// ensure we are migrating from a compatible contract
if ver.contract != CONTRACT_NAME {
return Err(StdError::generic_err("Can only upgrade from same contract type").into());
}
// note: it's better to do a proper semver comparison, but a string comparison *usually* works
#[allow(clippy::cmp_owned)]
if ver.version >= CONTRACT_VERSION {
return Err(StdError::generic_err("Cannot upgrade from a newer contract version").into());
}
// set the new version
cw2::set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// do any required state migrations...
Ok(Response::default())
```
### Migrating with Semver Comparison
In this type of migration, Semver (Semantic Versioning) is used for comparison instead of performing a simple string comparison.
```
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
let version: Version = CONTRACT_VERSION.parse()?;
let storage_version: Version = get_contract_version(deps.storage)?.version.parse()?;
if storage_version < version {
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// If state structure changed in any contract version in the way migration is needed, it
// should occur here
}
Ok(Response::default())
}
```
In this example, Semver is employed to facilitate version checks. To implement this, you will also need to include the Semver dependency in your cargo dependencies.
```
[dependencies]
semver = "1"
You can also implement Semver custom errors:
#[derive(Error, Debug, PartialEq)]
pub enum ContractError {
#[error("Semver parsing error: {0}")]
SemVer(String),
}
impl From<semver::Error> for ContractError {
fn from(err: semver::Error) -> Self {
Self::SemVer(err.to_string())
}
}
```
### Updating Otherwise Immutable State with Migrate
This example showcases how a migration can be utilized to modify a value that would ordinarily be considered immutable. This functionality enables the alteration of the value exclusively during a migration when required.
```
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, HackError> {
let data = deps
.storage
.get(CONFIG_KEY)
.ok_or_else(|| StdError::not_found("State"))?;
let mut config: State = from_slice(&data)?;
config.verifier = deps.api.addr_validate(&msg.verifier)?;
deps.storage.set(CONFIG_KEY, &to_vec(&config)?);
Ok(Response::default())
}
```
In the example above, our MigrateMsg includes a verifier field that holds the new value for our contract's verifier field within the State. Assuming your contract doesn't expose an UpdateState or similar ExecuteMsgs, this method serves as the sole means to modify the verifier value.
### Leveraging Migrations to 'Burn' a Contract
Migrations can serve the purpose of abandoning an old contract and erasing its state. This technique has multiple use cases, and if necessary, you can refer to an example here:
```
#[entry_point]
pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> StdResult<Response> {
// delete all state
let keys: Vec<_> = deps
.storage
.range(None, None, Order::Ascending)
.map(|(k, _)| k)
.collect();
let count = keys.len();
for k in keys {
deps.storage.remove(&k);
}
// get balance and send all to recipient
let balance = deps.querier.query_all_balances(env.contract.address)?;
let send = BankMsg::Send {
to_address: msg.payout.clone(),
amount: balance,
};
let data_msg = format!("burnt {} keys", count).into_bytes();
Ok(Response::new()
.add_message(send)
.add_attribute("action", "burn")
.add_attribute("payout", msg.payout)
.set_data(data_msg))
}
#[entry_point]
pub fn migrate(deps: DepsMut, env: Env, msg: MigrateMsg) -> StdResult<Response> {
// delete all state
let keys: Vec<_> = deps
.storage
.range(None, None, Order::Ascending)
.map(|(k, _)| k)
.collect();
let count = keys.len();
for k in keys {
deps.storage.remove(&k);
}
// get balance and send all to recipient
let balance = deps.querier.query_all_balances(env.contract.address)?;
let send = BankMsg::Send {
to_address: msg.payout.clone(),
amount: balance,
};
let data_msg = format!("burnt {} keys", count).into_bytes();
Ok(Response::new()
.add_message(send)
.add_attribute("action", "burn")
.add_attribute("payout", msg.payout)
.set_data(data_msg))
}
```
In the example above, the migration process involves the complete deletion of the contract's state. Additionally, the entire balance of the contract is transferred to a specified payout address outlined in the MigrationMsg. Consequently, this action results in the depletion of all funds and the eradication of all state, effectively "burning" the contract.
# Testing
Over time, testing emerges as an essential element within the Smart Contract development process. These tests play a vital role in facilitating the seamless integration of modifications into the contract's codebase, preventing any disturbances to other components. Typically, a robust collection of contracts includes a thorough suite of tests categorized into two main types: Unit Testing and Integration Testing.
For unit testing, click here.
## Conducting Integration Testing Using cw-multi-test
The cw-multi-test package, available in the cw-plus repository, offers an intriguing method for testing your smart contracts without the necessity of complete deployment onto a testnet. Prior to the introduction of the multi-test package, the usual process involved establishing a pipeline to deploy contracts on a designated chain (like a testnet or local network), conducting tests, and subsequently, when feasible, terminating or self-destructing those contracts.
## Fundamental Concepts of cw-multi-test
Before you can simulate a blockchain environment in Rust and conduct tests involving interactions between contracts and banks, there are several fundamental concepts you should grasp.
In this section, we will adopt a step-by-step methodology to compose a test utilizing cw-multi-test while elucidating significant concepts throughout the process.
To kick off, we require a sample contract, such as the [cw-template](https://github.com/CosmWasm/cw-template/blob/main/src/contract.rs). This contract serves as a basic template and features two functions: Increment and Reset.
Our initial step involves the creation of a new test file, incorporating the following imports:
```
use cosmwasm_std::testing::{mock_env, MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR};
use cw_multi_test::{App, BankKeeper, Contract, ContractWrapper};
```
The previously mentioned imports offer us a diverse array of tools for crafting a test. Among these imports, the initial one of significance is App, as it functions as the simulated blockchain environment within which our tests will be executed.
## **Main Entry Points: App and Querier**
### **App: The Heart of the System**
At the core of the system lies the App, which serves as the gateway to your blockchain application. This integral component keeps tabs on critical details such as the block height and time, allowing you to manipulate them to simulate multiple blocks. You can employ the app.update\_block(next\_block) method to advance the timestamp by 5 seconds and the block height by 1, effectively mimicking the creation of a new block. Additionally, you have the freedom to craft custom mutators to progress these values further.
The App provides the App.execute entry point, enabling the execution of any CosmosMsg message, wrapping it into an atomic transaction. A successful execution triggers state commitment and yields data along with a list of events. In case of an error, it returns an Err(String). For your convenience, a set of helper methods tied to the Executor trait generates CosmosMsg messages, simplifying the API. These methods include instantiate\_contract, execute\_contract, and send\_tokens, each executing a single CosmosMsg message atomically, as if initiated by a user. If you wish to run multiple messages together and revert all state changes if any of them fail, you can make use of the execute\_multi method.
### **Querier: Streamlining Blockchain Queries**
Another vital entry point within the App is the Querier interface it implements. By employing App.wrap(), you can obtain a QuerierWrapper, which grants access to a range of user-friendly APIs for querying the blockchain. These APIs encompass functions like all\_balances and query\_wasm\_smart, simplifying your ability to interact with the Storage, execute contracts, banks, and queries. Moreover, you can effortlessly update the current BlockInfo with a concise and straightforward API. Behind the scenes, the system handles all messages returned from contracts, manages token transfers within the "bank," and invokes other contracts seamlessly.
To craft an App for utilization in your test code, proceed with the following:
```
fn mock_app() -> App {
let env = mock_env();
let api = Box::new(MockApi::default());
let bank = BankKeeper::new();
App::new(api, env.block, bank, Box::new(MockStorage::new()))
}
```
### Mocking Contracts
In the realm of multi-testing, the practice of mocking your contracts stands as a foundational principle, albeit one that presents significant challenges in the testing process. Initially, it's imperative that any contract under evaluation must either be mocked or wrapped. With the assistance of cw-multi-test, a ContractWrapper facilitates the encapsulation of the essential elements of your contract, including instantiation, execution, and queries, enabling deployment to a mocked network.
Mocking all your contracts and subsequently conducting tests on each can be approached in a scripting style. However, to ensure maintainability and efficiency, it's advisable to define all your wrapped contracts as functions. This approach promotes reusability and enhances the overall testing process
```
use crate::contract::{execute, instantiate, query, reply};
pub fn contract_stablecoin_exchanger() -> Box<dyn Contract<Empty>>{
let contract = ContractWrapper::new_with_empty(
execute,
instantiate,
query,
).with_reply(reply);
Box::new(contract)
}
```
## **Working with Complex Examples**
### *Understanding the Components*
The example provided above may appear complex, but let's swiftly dissect it. In this breakdown, we commence by importing crucial functions, including execute, instantiate, Query, and Reply, all of which come into play during contract runtime. These functions set the stage for creating our wrapper, a pivotal element in our testing process.
**Information to Consider**
{% hint style="info" %}
**Information to Consider**
*"To Reply or Not to Reply: That Is the Question"*
The need for with\_reply in your ContractWrapper depends on your contract's structure. If your contract lacks an implemented Reply function, it may not be necessary.
{% endhint %}
**Following the Mocking Process**
After successfully mocking a contract, the subsequent steps include storing the code and then configuring a contract using the code object. Notably, this process mirrors the deployment procedure for a testnet or mainnet chain. In unit tests, you interact with a mocked\_env, leveraging mock\_dependencies and supplying mock\_info as part of the process.
## **Storing and Instantiating a Contract**
### Preparing for Instantiation
To successfully instantiate a contract within a cw-multi-test environment, it must initially undergo a storing process. After storage, the contract becomes ready for instantiation, utilizing its corresponding code\_id.
```
let contract_code_id = router.store_code(contract_stablecoin_exchanger());
```
### Instantiating from the new code object
```
let mocked_contract_addr = router
.instantiate_contract(contract_code_id, owner.clone(), &msg, &[], "super-contract", None)
.unwrap();
```
## **Handling Mocked Contracts and Potential Errors**
### Dealing with Common Errors
During your testing process, you might encounter error messages such as:
1. "No ContractData"
2. "Contract \<contract> does not exist"
These errors often indicate that a crucial element is missing in your mocking setup. In the cw-multi-test environment, any component that your contract interacts with, even simple utility contracts, should be properly mocked. This applies to services that your contract interacts with, even if your immediate intention is not to test them.
### **Addressing Common Causes**
Examine your contract closely to identify instances where you're passing dummy contract addresses, which is a common root cause of these errors. If you do find such cases, the following steps are necessary:
1. Mock it out using the method described earlier.
2. Instantiate it using the method mentioned previously.
3. Capture its address.
4. Replace the dummy address with the captured one.
{% hint style="info" %}
***Important Note***
*Remember that valid addresses must consist of lowercase alphanumeric characters. For instance, "owner" is valid, whereas "OWNER" is not.*
{% endhint %}
### **Bringing Everything Together**
```
use cosmwasm_std::testing::{mock_env, MockApi, MockQuerier, MockStorage, MOCK_CONTRACT_ADDR};
use cw_multi_test::{App, BankKeeper, Contract, ContractWrapper};
use crate::contract::{execute, instantiate, query, reply};
use crate::msg::{InstantiateMsg, QueryMsg}
fn mock_app() -> App {
let env = mock_env();
let api = Box::new(MockApi::default());
let bank = BankKeeper::new();
App::new(api, env.block, bank, Box::new(MockStorage::new()))
}
pub fn contract_counter() -> Box<dyn Contract<Empty>>{
let contract = ContractWrapper::new_with_empty(
execute,
instantiate,
query,
);
Box::new(contract)
}
pub fn counter_instantiate_msg(count: Uint128) -> InstantiateMsg {
InstantiateMsg {
count: count
}
}
#[test]
fn counter_contract_multi_test() {
// Create the owner account
let owner = Addr::unchecked("owner");
let mut router = mock_app();
let counter_contract_code_id = router.store_code(contract_counter());
// Setup the counter contract with an initial count of zero
let init_msg = InstantiateMsg {
count: Uint128::zero()
}
// Instantiate the counter contract using its newly stored code id
let mocked_contract_addr = router
.instantiate_contract(counter_contract_code_id, owner.clone(), &init_msg, &[], "counter", None)
.unwrap();
// We can now start executing actions on the contract and querying it as needed
let msg = ExecuteMsg::Increment {}
// Increment the counter by executing the prepared msg above on the previously setup contract
let _ = router.execute_contract(
owner.clone(),
mocked_contract_addr.clone(),
&msg,
&[],
)
.unwrap();
// Query the contract to verify the counter was incremented
let config_msg = QueryMsg::Count{};
let count_response: CountResponse = router
.wrap()
.que프로젝트로 돌아가기