bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 54쪽 중 44쪽
legram channel](https://t.me/+5KA8xBuU5wYzZjU0)
* Monitor the proposal's voting period
3. **Submit Pull Request**
* Once the governance proposal passes
* Follow the instructions to submit a pull request against the [XION contracts repository](https://github.com/burnt-labs/contracts)
* Complete all items in the pull request checklist
* Wait for review and approval from the team
# Create a Gas-less User Experience
**The recommended method to create a gas-less experience for your users is using the Treasury Contracts (**[**read here**](/en/build-on-verona/accounts/getting-started/treasury-contracts)**).**
Fee Granting ([read here](/en/others/archived/create-a-gas-less-user-experience/fee-granting)) is an alternative method, but is **not recommended** since it would require the app to handle the setup and allowance. This method allows for the same experience if you don't want to use Treasury Contract method for your application but note that the recommended method ([Treasury Contracts](/en/build-on-verona/accounts/getting-started/treasury-contracts)) executes the same steps under the hood
{% content-ref url="/pages/AYjtzenfA17M32SEYD1Y" %}
[Enabling Gasless Transactions with Treasury](/en/build-on-verona/accounts/getting-started/treasury-contracts)
{% endcontent-ref %}
{% content-ref url="/pages/HhGYGM7663IRZs5gwovd" %}
[Fee Granting](/en/others/archived/create-a-gas-less-user-experience/fee-granting)
{% endcontent-ref %}
# Fee Granting
#### Demonstrating Fee Allowance
This guide outlines how to grant a fee allowance, so that you can enable a gas-less experience for your end users. This guide also demonstrates how to validate its functionality by sending tokens back using AAClient. The process involves:
1. **Initial Setup:** Creating client instances for a funding account and a recipient account.
2. **Granting Fee Allowance:** Allowing the recipient account to use the funding account's resources for transaction fees.
3. **Validating Fee Allowance:** Sending a token from the recipient account to the funding account to demonstrate the successful fee grant.
**Initial Setup**
Begin by initializing client instances for both accounts using user-provided private keys:
```typescript
import { AAClient } from "@burnt-labs/signers";
// These are used in the following code examples.
import { MsgGrantAllowance } from "cosmjs-types/cosmos/feegrant/v1beta1/tx";
import { BasicAllowance } from "cosmjs-types/cosmos/feegrant/v1beta1/feegrant";
export async function buildClient(
key: string
): Promise<[AAClient, AccountData]> {
const signer: OfflineDirectSigner = await DirectSecp256k1Wallet.fromKey(
fromHex(key),
burntChainInfo.bech32Config.bech32PrefixAccAddr
);
const [accountData] = await signer.getAccounts();
const client = await AAClient.connectWithSigner(
// This can be any RPC endpoint.
"https://rpc.xion-testnet-2.burnt.com:443",
signer
);
return [client, accountData];
}
const [fundingAccountClient, fundingAccount] = await buildClient("<private_key_of_funding_account>");
const [recipientAccountClient, recipientAccount] = await buildClient("<private_key_of_recipient_account>");
```
**Granting Fee Allowance**
Grant a fee allowance from the funding account to the recipient account:
```typescript
// Construct the grant allowance message
const msgGrantAllowance = {
typeUrl: "/cosmos.feegrant.v1beta1.MsgGrantAllowance",
value: MsgGrantAllowance.fromPartial({
granter: fundingAccount.address,
grantee: recipientAccount.address,
allowance: {
typeUrl: "/cosmos.feegrant.v1beta1.BasicAllowance",
value: BasicAllowance.encode(
BasicAllowance.fromPartial({
spendLimit: [
{
denom: "uxion",
amount: "<amount of token to grant>",
},
],
expiration: {
seconds: Math.floor((Date.now() + <Number of seconds until grant expires>) / 1000),
},
})
).finish(),
},
}),
};
// Send the grant allowance transaction
const grantResponse = await fundingAccountClient.signAndBroadcast(
fundingAccount.address,
[msgGrantAllowance],
defaultFee,
"Granting fee allowance to recipient account"
);
```
**Validating Fee Allowance**
To confirm the fee allowance, send a token back from the recipient account to the funding account:
```typescript
// Construct the send token message
const msgSend = {
typeUrl: "/cosmos.bank.v1beta1.MsgSend",
value: {
fromAddress: recipientAccount.address,
toAddress: fundingAccount.address,
amount: [
{
denom: "uxion",
amount: "1",
},
],
},
};
// Send the token transaction
const sendResponse = await recipientAccountClient.signAndBroadcast(
recipientAccount.address,
[msgSend],
{
...defaultFee,
granter: fundingAccount.address,
},
"Returning token to funding account"
);
console.log("sendResponse", sendResponse);
```
This complete example shows how to set up a fee allowance and verify its success through a token transaction.
# Account Upgrade Guide (Testnet)
There have been recent upgrades to the chain and the Account contract. To ensure your account remains compatible with the latest version, please head over to the Dashboard application to upgrade your account. This upgrade is essential to maintain seamless functionality with the newest version of the testnet chain.
What you need to do:
1. Login to the Dashboard: <https://testnet.dashboard.burnt.com/>
2. Click on Upgrade account
<figure><img src="https://3630978198-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FB5Z5ijJgMx0GJO3l1Il9%2Fuploads%2FJ4CB2pUJogf0CM3fA1AN%2Fimage.png?alt=media&token=ef01fe52-16f1-405d-af1e-6c6be9e5f217" alt=""><figcaption></figcaption></figure>
{% hint style="info" %}
If you have any questions or run into any issues, feel free to ask in our Telegram Developer Group (Join [here](https://t.me/+SC47NRhVz9Q2MDg0) :speech\_balloon:)
{% endhint %}
# CosmWasm Resources
Learn more about the CosmWasm smart contract platform
### What is CosmWasm?
CosmWasm is a smart contract platform written as a module that can be integrated into any blockchain built on top of the Cosmos SDK.
Currently, Rust is the most used programming language for CosmWasm. In the future, other programming languages, such as Go Lang, may also be utilized in some instances.
### Sections <a href="#sections" id="sections"></a>
* Introduction
This section provides hands-on training, guiding you through modifying, deploying, and executing a smart contract on a blockchain. It is the ideal place to familiarize yourself with all aspects of the system without delving too deep into coding.
* Contract Semantics
This section explains much of the high-level design and architecture of CosmWasm. It is crucial to understand the mental model and capabilities of the system before designing products with it. However, if you prefer to learn through coding, you can skip this section and revisit it as needed.
* Architecture
This section explores the various components that make up smart contracts and how they interact with the wider CosmWasm environment.
* Tutorials
This section demonstrates the development of smart contracts from zero to production with step-by-step explanations, code snippets, scripts, and more.
\
There are many public CosmWasm resources, such as this helpful one: <https://book.cosmwasm.com/>
# Introductory Section
The introductory section provides an overview of the core principles behind CosmWasm Smart Contracts. While a basic familiarity with Rust could be beneficial, the material is designed to cater to individuals of all proficiency levels, irrespective of their prior experience. Our goal is to offer clear and accessible guidance, allowing newcomers to gain practical insights through a comprehensive, step-by-step tutorial that delves into the following subjects:
* Setting up environment
* Deploying a smart contract to the XION blockchain
* Executing smart contract functions via the CLI
* Modifying an existing contract
If you'd like to start your exploration by delving into the inner workings of CosmWasm, you're welcome to skip ahead to the Architecture section for a concise overview. Later, you can return to this section to continue your journey.
You might have observed that the development of smart contracts is not covered in this section. The Getting Started segment has been purposely crafted to be as straightforward as possible, sidestepping any potential complexities associated with smart contract development, which will be covered in subsequent sections.
### Descriptions of the Following Sections:
[Setting up Environment](/en/others/archived/cosmwasm-resources/introductory-section/setting-up-environment): This section guides you through the setup of your client environment, essential software tools, and how to interact with the faucet.
[Compiling a Contract](/en/others/archived/cosmwasm-resources/introductory-section/compiling-a-contract): This section provides a step-by-step walkthrough of downloading and compiling smart contract code into wasm bytecode.
[Unit Test](/en/others/archived/cosmwasm-resources/introductory-section/unit-test): In this section, you'll learn how to perform unit tests within a CosmWasm smart contract, ensuring its functionality.
[Deployment and Interaction](/en/others/archived/cosmwasm-resources/introductory-section/deployment-and-interaction): This section demonstrates the deployment of a contract to the testnet, instantiation, and the execution of smart contract functions.
[Next Steps](/en/others/archived/cosmwasm-resources/introductory-section/next-steps): The concluding part of this tutorial, Next Steps, summarizes the Getting Started section and directs you towards further learning resources.
\ <br>
# Setting Up Environment
A user can choose to either set up a local testnet or connect to an existing network. For easy testing, the XION testnet is available for deploying and running ones contracts.
To set up a local testnet, see Running a Local Testnet. For details on the available XION networks, see the [Networks](/en/build-on-verona/references/public-endpoints-and-resources) page.
To work with CosmWasm smart contract, a user will need rust installed on their machine. If the user does not have it installed, they can find installation instructions on the Rust website.
Additionally, the user will need the Wasm rust compiler backend installed to build Wasm binaries.
Also, to be able to upload Rust Wasm Contracts into the blockchain, a user will need to install docker.
To minimize their contract sizes, it will be required to run CosmWasm Rust Optimizer; without that, more complex contracts might exceed a size limit.
### cosmwasm-check utility
An additional helpful tool for building smart contracts is the `cosmwasm-checkutility`. It allows a user to check if the wasm binary is a proper smart contract ready to upload into the blockchain. A user can install it using cargo:
`$ cargo install cosmwasm-check`
If the installation succeeds, a user should be able to execute the utility from your command line.
`$ cosmwasm-check --version`
`Contract checking 1.2.3`
### Verifying the installation
To guarantee a user is ready to build their smart contracts, they will need to make sure they can build examples. Checkout the cw-plus repository and run the testing command in its folder:
`$ git clone git@github.com:CosmWasm/cw-plus.git`
`$ cd ./cw-plus`
`cw-plus $ cargo test`
A user should see that everything in the repository gets compiled, and all tests pass.
`cw-plus` is a great place to find example contracts - look for them in contracts directory. The repository is maintained by CosmWasm creators, so contracts in there should follow good practices.\\
To verify the `cosmwasm-check` utility, first, a user will need to build a smart contract. Go to some contract directory, for example, `contracts/cw1-whitelist`, and call `cargo wasm`:
`cw-plus $ cd contracts/cw1-whitelist`
`cw-plus/contracts/cw1-whitelist $ cargo wasm`
A user should be able to find their output binary in the t`arget/wasm32-unknown-unknown/release/` of the root repo directory - not in the contract directory itself! Now they can check if contract validation passes:
`cw-plus/contracts/cw1-whitelist $ cosmwasm-check ../../target/wasm32-unknown-unknown/release/cw1_whitelist.wasm`
`Available capabilities: {"iterator", "cosmwasm_1_1", "cosmwasm_1_2", "stargate", "staking"}`
`../../target/wasm32-unknown-unknown/release/cw1_whitelist.wasm: pass`
`All contracts (1) passed checks!`
If you intend to use xiond as your preferred client, we recommend you to set up these variables. Otherwise you will have to type in node, chain id and gas-price details with every command you execute.
```bash
# bash
export NODE="--node $RPC"
export TXFLAG="${NODE} --chain-id xion-testnet-2 --gas-prices 0.25uxion --gas auto --gas-adjustment 1.4"
# zsh
export NODE=(--node $RPC)
export TXFLAG=($NODE --chain-id xion-testnet-2 --gas-prices 0.25uxion --gas auto --gas-adjustment 1.4)
```
{% hint style="info" %}
Get the RPC endpoint from the [Public Endpoints & Resources](/en/build-on-verona/references/public-endpoints-and-resources) section
{% endhint %}
# Compiling a Contract
Within this section, our objective is to retrieve the code for a sample contract and transform it into a wasm binary executable.
## Prerequisites
Before you proceed, ensure that you have installed the necessary dependencies as detailed in the "[Setting Up Environment](/en/others/archived/cosmwasm-resources/introductory-section/setting-up-environment)" guide.
## Downloading the Contract
To get started, initiate the download of the [cw-contracts ](https://github.com/deus-labs/cw-contracts)repository. The contract we'll be compiling is the ***nameservice*** contract.
**Clone the following repository:**
```
git clone https://github.com/InterWasm/cw-contracts
cd cw-contracts
git checkout main
cd contracts/nameservice
```
## Compile Contract
In this section, we will go over how to compile using Cargo.
#### Compile using Cargo
Execute the following command to compile the contract:
```
cargo wasm
```
After the compilation process, you should find the file *target/wasm32-unknown-unknown/release/cw\_nameservice.wasm* generated. Its size is roughly 1.9 MB, indicating that it's a release build but hasn't undergone the removal of all redundant code yet. To deploy the contract on-chain, optimization is necessary. Refer to the Optimized Compilation"section below for guidance on optimizing a contract.
## Optimized Compilation
In order to minimize gas costs, it is essential to minimize the binary size, resulting in more cost-effective deployment and reduced fees for every interaction. Fortunately, there are available tools to aid in this process. These optimization tools generate reproducible builds of CosmWasm smart contracts, ensuring that third parties can verify the contract's contents as claimed.
#### Optimize using Cargo
Executing the following command should yield an optimized contract suitable for storage on the blockchain:
```
RUSTFLAGS='-C link-arg=-s' cargo wasm
```
#### Optimize using Rust-Optimizer
{% hint style="info" %}
*You will have needed to already install Docker in order to run the rust-optimizer*
{% endhint %}
Navigate to the project root and run the following command:
```bash
docker run --rm -v "$(pwd)":/code \
--mount type=volume,source="$(basename "$(pwd)")_cache",target=/code/target \
--mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \
cosmwasm/rust-optimizer:0.16.0
```
By running this command, the .wasm file will undergo optimization, resulting in an optimized .wasm file located in the artifacts directory. If you have multiple contracts in the workspace append the name of the specific project you want built.
####
# Unit Test
Unit testing plays a vital role in software development, serving to verify the accuracy of your code and enabling the early detection of any bugs or problems. Within this section, we will delve into the procedure for running unit tests within a CosmWasm smart contract.
## Writing Unit Tests
In Rust, when creating unit tests for CosmWasm smart contracts, it's necessary to utilize the #test attribute to designate test functions. These functions should be organized within a tests module within your smart contract's source code, commonly guarded with a #cfg(test) attribute to ensure compilation solely during testing. Macros such as assert!, assert\_eq!, and assert\_ne! can be employed to verify your code's functionality against anticipated results.
## Running Unit Tests
Execute the following command to perform the available unit tests:
```
RUST_BACKTRACE=1 cargo unit-test
```
Following several compilation steps, you should notice:
```
running 15 tests
test coin_helpers::test::assert_sent_sufficient_coin_works ... ok
test tests::test_module::fails_on_register_insufficient_fees ... ok
test tests::test_module::fails_on_register_wrong_fee_denom ... ok
test tests::test_module::proper_init_no_fees ... ok
test tests::test_module::fails_on_register_already_taken_name ... ok
test tests::test_module::fails_on_transfer_insufficient_fees ... ok
test tests::test_module::proper_init_with_fees ... ok
test tests::test_module::register_available_name_and_query_works ... ok
test tests::test_module::fails_on_transfer_non_existent ... ok
test tests::test_module::fails_on_transfer_from_nonowner ... ok
test tests::test_module::register_available_name_fails_with_invalid_name ... ok
test tests::test_module::register_available_name_and_query_works_with_fees ... ok
test tests::test_module::returns_empty_on_query_unregistered_name ... ok
test tests::test_module::transfer_works ... ok
test tests::test_module::transfer_works_with_fees ... ok
test result: ok. 15 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
```
Enabling **RUST\_BACKTRACE=1** will furnish comprehensive stack traces for error tracking, a valuable tool. Please note that this feature exclusively functions with unit tests, which assess native Rust code rather than compiled wasm code. Furthermore, if you're interested in the sources of cargo wasm and cargo unit-test, they are merely aliases specified in the .cargo/config file situated within the project directory. A closer examination of the file's contents will provide you with insights into the cargo flags.
## Mocking
Mocking and dependency injection are strategies that enable you to segregate particular segments of your smart contract for testing. In the context of mocking, you generate imaginary objects or functions that substitute the real dependencies of your smart contract, granting you control over their conduct during testing. On the other hand, dependency injection entails supplying these mocked dependencies as parameters to your smart contract functions, enabling the simulation of diverse conditions and scenarios without impacting the authentic contract state or dependencies.
## Best Practices to Keep in Mind
* **Organize Test Modules**: Arrange your tests by grouping them in separate modules or files according to the functionality they evaluate.
* **Adhere to Naming Conventions**: Employ descriptive names for your tests that explicitly convey what aspect they are assessing, for instance, using names like `test_transfer_funds_success` or `test_invalid_name_rejection`.
* **Maintain Clarity and Conciseness**: Develop tests that are lucid and succinct, concentrating on specific components of the smart contract. Avoid creating overly intricate or unrelated tests.
* **Cover Edge Cases and Failures**: Ensure your tests encompass edge cases and potential failure scenarios, thus verifying that your smart contract can gracefully handle a variety of situations.
* **Isolate Test Cases**: Keep your tests independent of one another, so that the failure of one test does not impact the execution of others. This enhances the reliability of your test suite
# Deployment and Interaction
You now have the wasm binary ready. It프로젝트로 돌아가기