MANTRA Chain
  • Introduction
    • Overview
    • Why MANTRA Chain
    • Building on MANTRA Chain
    • MANTRA RWA Suite
  • Using MANTRA Chain
    • MANTRA Chain Wallet Setup
      • Connect to Testnet
      • Connect to Mainnet
      • Testnet Faucet
    • MANTRA Zone
    • MANTRA Bridge
      • MANTRA Bridge User Guide
      • MANTRA Bridge FAQs
    • Stake
      • Stake User Guide
      • Stake FAQs
    • MANTRA Swap
      • MANTRA Swap User Guide
      • Liquidity Pools User Guide
      • MANTRA Swap FAQs
    • Claiming Journey
      • Check If You're Eligible
      • Claiming Journey User Guide
      • I've redeemed my rewards, now what?
    • Chakra Pool
      • What can I do with my USDY
      • Chakra Pool Deposit Guide
      • How KARMA works for Chakra Pool
        • How much KARMA do I get for depositing into Chakra Pool?
        • Can I make multiple deposits and how will KARMA be calculated then?
        • My KARMA is not updated even though I make multiple deposits?
        • Will I get daily KARMA for my deposit on USDY Chakra Pool launched on Hongbai earlier?
      • Chakra Pool FAQs
    • MANTRA Zone Leaderboard
      • MANTRA Zone Leaderboard User Guide
        • Mission Guides
          • Pledge your OM 🕉️
          • Claim OM Staking Rewards
          • OMly Drip 💧
      • MANTRA Zone Leaderboard FAQs
  • Developing on MANTRA Chain
    • Getting Started
      • DuKong Testnet
      • Install Prerequisites
      • Setting Up Dev Environment
      • Compiling a Contract
      • Deployment and Interaction
    • CosmWasm Quick Start Guide
      • CosmWasm Contracts
      • Understanding CosmWasm File Structure
    • DAPP Tooling
      • Cosmos SDK
      • Important Libraries
      • Developer Resources
    • Developer FAQs
  • MANTRA Smart Contracts
    • Overview
    • MANTRA Dex
      • 🚢Deployments
      • 📚Common Types
      • 💰Fee Collector
      • ⌛Epoch Manager
      • 🌊Pool Manager
      • 🎁Farm Manager
    • Claimdrop Contract
    • Audits
  • Node & Validator Operations
    • Overview
    • Node Setup & Deployment
      • Node System Requirements
      • Running a Node
      • How to run Mantrachain with Systemd
      • Validator Nodes
        • Connect sidecar
    • Validator Architecture Recommendations
      • Secure Validator
    • Governance
      • Draft a Proposal
        • Text Proposal
        • Community Spend Proposal
        • Software Upgrade
        • Cancel Software Upgrade
      • Submitting a Proposal
      • Verifying your transaction
      • Depositing funds
      • Voting on a Proposal
    • Download nodes snapshots
  • MANTRA Chain with EVM (Alpha)
    • Getting Started on OMSTEAD Testnet
  • Setup Instructions
  • Using Foundry
    • Deployment with Foundry
  • Using Hardhat
    • Deployment with Hardhat
  • Mainnet OM Information
    • Background
    • Updated OM Tokenomics
    • OM Distribution Updates
    • Inflation & Vesting Schedule
    • Legacy tokens to mainnet staking tokens
  • Appendix
    • Frequently Asked Questions
      • General FAQs
        • What is MANTRA Chain?
        • What are the key features/ modules available to builders on MANTRA Chain?
        • What support is available for developers and validators that join the ecosystem
        • Where can i find MANTRA Social Accounts & Communities?
        • How can an Issue or a bug be reported?
        • How can I identify official MANTRA communication and websites?
      • Validator FAQs
        • What does a new validator’s journey look like?
        • What are my key responsibilities as a validator?
        • What is uptime and how is it maintained?
        • What are the hardware requirements?
        • How to get validator keys?
        • How can I connect a validator from an older testnet to the newest testnet?
        • How do I create a backup snapshot of a node?
        • How do I restore a node from a snapshot?
        • What are the different states a validator can be in?
        • How do I unjail a validator?
        • How do I edit a validator's description?
        • What is self-delegation?
        • Is there a minimum amount of OM that must be delegated to be an active validator?
      • Developer FAQs
        • What is MANTRA Chain, and how does it utilize the Cosmos ecosystem?
        • How does MANTRA Chain ensure interoperability with other blockchains in the Cosmos ecosystem?
        • What is the Cosmos ecosystem, and how does it differ from other blockchain platforms?
        • Which programming languages are commonly used for developing on the Cosmos ecosystem?
        • How do I get started with development on the Cosmos ecosystem?
        • What are Cosmos SDK and Tendermint, and how do they work together?
        • What are Cosmos zones and how do they interact?
        • How do I build and deploy smart contracts on the Cosmos ecosystem?
        • How do I interact with Cosmos chains and applications programmatically?
        • What is the best way to learn about developing for the MANTRA Chain and Cosmos ecosystem?
      • Hongbai FAQs
        • Where do I sign up for Hongbai?
        • Why do I need to provide 2 wallets during signup?
        • How can I Login?
        • What should I do if I forgot my password?
        • What can I do if i forget my registered email?
        • Where do i verify my email?
        • How to connect my Metamask wallet?
        • Is Hongbai app a testnet or live app?
        • Can I change my wallet ?
        • Error “invalid user credentials“
        • Why can i not Invest?
      • How to Guides
        • Install Keplr Wallet
        • Keplr and Ledger
        • Add DuKong Testnet to Keplr
        • Get Tokens from Faucet
        • Track activity on Leaderboard
      • More Help & Support
      • MANTRA Zone FAQs
        • MANTRA Zone General FAQs
          • What wallets are currently supported on the MANTRA Zone?
          • How do I connect my wallet to the MANTRA Zone?
          • How do I copy my connected wallet’s address?
          • How do I connect a different wallet to the MANTRA Zone?
          • Can I disconnect my wallet from MANTRA Zone?
          • How can I resolve seeing multiple entires of the same amount of testnet OM in my Keplr wallet?
          • The question that I have is not covered by the FAQ, what should I do?
        • MANTRA Bridge FAQs
          • What is MANTRA Bridge?
          • Why should I use the MANTRA Bridge?
          • Is there a fee for using the MANTRA Bridge?
          • Do I have to pay gas fees?
          • What tokens will I receive?
          • How does the migration process work?
          • How long should the MANTRA Bridge order take?
          • How can I track the status of my MANTRA Bridge order?
          • What happens to my ERC20 OM tokens once I use the MANTRA Bridge?
          • Which network can I use on the MANTRA Bridge?
          • What should I do if I see ‘Wrong network’ error on the app?
          • Will there be a two-way bridge in the future?
          • My MANTRA Bridge order is stuck on Ethereum?! How can I fix this?
          • Who can I contact for support during the migration process?
          • Which EVM chains can I bridge from?
          • Are the OM tokens I receive wrapped tokens or the native MANTRA Chain OM tokens?
          • Is the MANTRA Bridge a non-custodial solution?
          • What happens if the MANTRA Bridge is hacked or goes offline?
          • Are there any risks associated with using the MANTRA Bridge?
          • How does the MANTRA Bridge ensure the security of my tokens during migration?
          • Can I use my existing Ethereum wallet to access the MANTRA Bridge?
          • How does wallet linking and airdrop participation work?
        • Stake FAQs
          • What is Stake?
          • What are validators, and how do I choose one?
          • What rewards can I earn by staking $OM?
          • How are staking rewards calculated?
          • Can I choose to unstake my $OM coins?
          • What is the unbonding period?
          • Can I change validators after staking $OM?
          • Can I stake $OM with multiple validators?
          • Are there any risks involved with staking $OM?
          • Will my rewards gets automatically restaked after redemption?
          • Do I lose my claimable rewards when performing actions with a validator with unclaimed rewards?
          • My wallet is showing a 0 balance even though I have funds. What should I do?
          • How do I know if my $OM is staked?
        • Chakra Pool FAQs
          • What are the Chakra Pool rewards?
          • What is USDY?
          • How do I get the yield from the treasury bonds by holding USDY?
          • Can I change my linked wallet?
          • I don’t remember my linked wallet - what can I do?
          • What are the bonus rewards and where I can see my rewards?
          • How are the USDY rewards calculated and when can I redeem my USDY rewards?
          • How are the $OM rewards calculated and when can I redeem my $OM rewards?
          • How are the $ONDO rewards calculated and when can I redeem my $ONDO rewards?
          • What can I do with my USDY and $OM rewards after redemption?
        • MANTRA Zone Leaderboard FAQs
          • I have someone that wants to participate in the MANTRA Zone Leaderboard but they don’t know how.
          • What does the ⚡icon and ‘Get + x KARMA’ text under the ‘KARMA’ section refer to?
          • The KARMA on the Zone Leaderboard only lists MANTRA Chain wallets, how to check my EVM wallet rank?
          • Which wallet IDs are visible on the Leaderboard Ranking Table?
          • Why are there three different categories for the Leaderboard Ranking Table?
          • How can I get the Leaderboard Ranking Table to show where my connected wallet ranks currently?
          • How can I search where a specific wallet ID ranks in the Leaderboard Ranking Table?
          • How can I search what wallet ID currently ranks in a specific ranking number?
          • My KARMA and/or multiplier amount did not update on the Leaderboard Ranking Table, why is that?
          • What is the calculation for the KARMA?
          • I’m unable to see the OMly Faucet on my Keplr/Cosmostation wallet
          • I'm unable to see my OMly Faucet Claim transaction on the explorer
          • The question that I have is not covered by the FAQ, what should I do?
        • MANTRA Swap FAQs
          • What is Swap?
          • How can I swap?
          • I have connected my EVM wallet, but I’m still unable to swap. Why?
          • Where can I view my past transactions?
          • Why is my swap button disabled?
          • Why can’t I swap with a slippage more than 5%?
          • What is Exchange Rate?
          • How do I get OM tokens in my wallet?
          • How do I get other tokens in my wallet?
          • Will the swap fee be deducted from my sell or buy token?
          • Why can’t I see the balance of tokens in my wallet but on the Swap panel?
          • How do I add liquidity to a pool?
          • I am unable to provide liquidity to the pool.
          • While adding liquidity, why are the two tokens USD value not equal?
          • How do I withdraw my funds from Liquidity Pools?
          • Why can I not see my tokens for withdrawal?
          • Why can I not remove liquidity?
          • Why is my deposited value of the two tokens changing in my position?
          • Do liquidity pools have a bonding period?
          • What are LP tokens?
          • What can I do with my LP tokens?
          • Why can I not see any LP token balance?
          • I am connected with my MANTRA wallet, but still cannot view my positions?
          • I provided liquidity, but I can’t see my position. What should I do?
          • Why is my transaction not successful?
    • Glossary
    • MANTRA's Incentivised Testnet
      • Testnet Phase 1
      • Hongbai - Testnet Phase 2
  • Third Party Bridges
    • Base Bridge
    • Polygon Bridge
Powered by GitBook
On this page
  1. Developing on MANTRA Chain
  2. CosmWasm Quick Start Guide

Writing & Deploying CW20 Contract

This guide provides a step-by-step process to write and deploy a CW20 token contract on the MANTRA Chain using Rust and CosmWasm. CW20 contracts are similar to ERC20 contracts on Ethereum and are widely used for token creation and management on Cosmos-based blockchains.

In the previous sections, we have understood the dev environment setup, wallet setup and collect testnet OM tokens for the development purposes. Therefore, ensure your Keplr wallet is set up and contains OM testnet tokens for the deployment process.

Prerequisites

If you encounter any issues with your development environment setup or need to refresh your setup, follow these steps:

  1. Install Rust

First, you need to install Rust, a programming language used for developing smart contracts. You can do this by running the following command in your terminal:

curl --proto '=https' --tlsv1.2 <https://sh.rustup.rs> -sSf | sh

When prompted, choose the first option for standard installation. This will install Rust and its package manager, Cargo.

  1. Set Up Rust and Cargo

After installing Rust, set up Rust to use the stable version and verify the installation:

rustup default stable

cargo version

rustup target add wasm32-unknown-unknown

This ensures that you have the latest stable version of Rust and adds the WebAssembly target required for smart contract development.

  1. Install cargo-generate

cargo-generate is a tool that helps you to generate a new Rust project from a template. Install it using the following command:

cargo install cargo-generate --features vendored-openssl
  1. Install mantrachaind

Download and extract the pre-built mantrachaind binary:

On Linux:

# Download the CLI
curl -LO <https://github.com/MANTRA-Finance/public/raw/main/mantrachain-testnet/mantrachaind-linux-amd64.zip>

# Unzip the CLI
unzip mantrachaind-linux-amd64.zip

On MacOS:

# Download the CLI for Intel chips
curl -LO <https://github.com/MANTRA-Finance/public/raw/main/mantrachain-hongbai/mantrachaind-static-darwin-amd64.tar.gz>

# Download the CLI for Silicon chips (M1, M2...)
curl -LO <https://github.com/MANTRA-Finance/public/raw/main/mantrachain-hongbai/mantrachaind-static-darwin-arm64.tar.gz>

# Extract the CLI
tar -xzvf mantrachaind-static-darwin-*.tar.gz

If you encounter a missing libwasmvm.x86_64.so error, download the library:

sudo wget -P /usr/lib <https://github.com/CosmWasm/wasmvm/releases/download/v2.1.0/libwasmvm.x86_64.so>

Writing & deployment of CW20 contract

Step 1: Clone the Project

Clone the repository that contains the boilerplate code for the CW20 contract:

git clone <https://github.com/MANTRA-Finance/first_token_cw20contract>

After cloning the repository, open the project in your preferred code editor, such as Visual Studio Code.

Step 2: Update Dependencies

Navigate to the Cargo.toml file in the root directory of your project. This file manages the dependencies for your Rust project. Add the following dependency to include the cw20-base package:

Cargo.toml

[dependencies]
cw20-base = {  version = "2.0.0", features = ["library"] }
cw20 = "2.0.0"
cw-utils = "2.0.0"
cosmwasm-std = "2.1.3"
cosmwasm-storage = "1.1.1"
cw-storage-plus = "2.0.0"
cw2 = "2.0.0"
schemars = "0.8.21"
serde = { version = "1.0.207", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.63" }
cosmwasm-schema = "2.1.3"
prost = "0.13.1"

This ensures that you have the necessary libraries to work with CW20 tokens, providing essential functionalities like token transfer, allowance, and minting.

Now that we have completed the setup , let's modify the boilerplate code and get our token ready .

We will be changing or creating the logic inside the following files :

  • scr/msg.rs

  • src/contract.rs

  • src/lib.rs

Step 3: Modify Contract Files

Update msg.rs

use cosmwasm_schema::cw_serde;

#[cw_serde]
pub enum MigrateMsg {}

Update contract.rs

#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{
    to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult,
};
use cw20_base::ContractError;
use cw20_base::enumerable::{query_all_allowances, query_all_accounts};
use cw20_base::msg::{QueryMsg,ExecuteMsg};

use crate::msg::MigrateMsg;
use cw2::set_contract_version;
use cw20_base::allowances::{
    execute_decrease_allowance, execute_increase_allowance, execute_send_from,
    execute_transfer_from, query_allowance, execute_burn_from,
};
use cw20_base::contract::{
    execute_mint, execute_send, execute_transfer, execute_update_marketing,
    execute_upload_logo, query_balance, query_token_info, query_minter, query_download_logo, query_marketing_info, execute_burn,
};

// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cw20-token";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use cosmwasm_std::{to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult};
use cw2::set_contract_version;
use cw20_base::allowances::{
    execute_burn_from, execute_decrease_allowance, execute_increase_allowance, execute_send_from,
    execute_transfer_from, query_allowance,
};
use cw20_base::contract::{
    execute_burn, execute_mint, execute_send, execute_transfer, execute_update_marketing,
    execute_update_minter, execute_upload_logo, query_balance, query_download_logo,
    query_marketing_info, query_minter, query_token_info,
};
use cw20_base::enumerable::{query_all_accounts, query_owner_allowances, query_spender_allowances};
use cw20_base::msg::{ExecuteMsg, QueryMsg};
use cw20_base::ContractError;

use crate::msg::MigrateMsg;

// version info for migration info
const CONTRACT_NAME: &str = "crates.io:cw20-token";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn instantiate(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    msg: cw20_base::msg::InstantiateMsg,
) -> Result<Response, ContractError> {
    set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
    Ok(cw20_base::contract::instantiate(deps, env, info, msg)?)
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    msg: ExecuteMsg,
) -> Result<Response, ContractError> {
    match msg {
        ExecuteMsg::Transfer { recipient, amount } => {
            execute_transfer(deps, env, info, recipient, amount)
        }
        ExecuteMsg::Burn { amount } => execute_burn(deps, env, info, amount),
        ExecuteMsg::Send {
            contract,
            amount,
            msg,
        } => execute_send(deps, env, info, contract, amount, msg),
        ExecuteMsg::Mint { recipient, amount } => execute_mint(deps, env, info, recipient, amount),
        ExecuteMsg::IncreaseAllowance {
            spender,
            amount,
            expires,
        } => execute_increase_allowance(deps, env, info, spender, amount, expires),
        ExecuteMsg::DecreaseAllowance {
            spender,
            amount,
            expires,
        } => execute_decrease_allowance(deps, env, info, spender, amount, expires),
        ExecuteMsg::TransferFrom {
            owner,
            recipient,
            amount,
        } => execute_transfer_from(deps, env, info, owner, recipient, amount),
        ExecuteMsg::BurnFrom { owner, amount } => execute_burn_from(deps, env, info, owner, amount),
        ExecuteMsg::SendFrom {
            owner,
            contract,
            amount,
            msg,
        } => execute_send_from(deps, env, info, owner, contract, amount, msg),
        ExecuteMsg::UpdateMarketing {
            project,
            description,
            marketing,
        } => execute_update_marketing(deps, env, info, project, description, marketing),
        ExecuteMsg::UploadLogo(logo) => execute_upload_logo(deps, env, info, logo),
        ExecuteMsg::UpdateMinter { new_minter } => {
            execute_update_minter(deps, env, info, new_minter)
        }
    }
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
    match msg {
        QueryMsg::Balance { address } => to_json_binary(&query_balance(deps, address)?),
        QueryMsg::TokenInfo {} => to_json_binary(&query_token_info(deps)?),
        QueryMsg::Minter {} => to_json_binary(&query_minter(deps)?),
        QueryMsg::Allowance { owner, spender } => {
            to_json_binary(&query_allowance(deps, owner, spender)?)
        }
        QueryMsg::AllAllowances {
            owner,
            start_after,
            limit,
        } => to_json_binary(&query_owner_allowances(deps, owner, start_after, limit)?),
        QueryMsg::AllAccounts { start_after, limit } => {
            to_json_binary(&query_all_accounts(deps, start_after, limit)?)
        }
        QueryMsg::AllSpenderAllowances {
            spender,
            start_after,
            limit,
        } => to_json_binary(&query_spender_allowances(
            deps,
            spender,
            start_after,
            limit,
        )?),
        QueryMsg::MarketingInfo {} => to_json_binary(&query_marketing_info(deps)?),
        QueryMsg::DownloadLogo {} => to_json_binary(&query_download_logo(deps)?),
    }
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> StdResult<Response> {
    Ok(Response::default())
}

Error Handling Logic

The error handling on this contract happens at the cw20-base library level, so you don’t need to implement specific errors unless you want to.

Step 4: Build Artifacts and Wasm file

To build the artifact, we need to run the rust-optimizer with docker:

docker run --rm -v "$(pwd)":/code \\
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \\
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \\
  cosmwasm/optimizer:0.16.0

Or if you are on MacOS:

docker run --rm -v "$(pwd)":/code \\
  --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \\
  --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \\
  cosmwasm/optimizer-arm64:0.16.0

This command generates a wasm file first_token_cw20contract.wasm under the artifacts folder.

Step 5: Deploy the contract

There are multiple ways to deploy a contract on chain, but the most common ones are via the mantrachaind cli tools and via scripts (bash, typescript).

  • Using the CLI:

RES=$(mantrachaind tx wasm store artifacts/first_token_cw20contract.wasm --from <wallet> --node <https://rpc.hongbai.mantrachain.io:443> --chain-id mantra-hongbai-1 --gas-prices 0.35uom --gas auto --gas-adjustment 1.4 -y --output json)
TX_HASH=$(echo $RES | jq -r .txhash)
CODE_ID=$(mantrachaind query tx $TX_HASH --node <https://rpc.hongbai.mantrachain.io:443> -o json| jq -r '.logs[0].events[] | select(.type == "store_code") | .attributes[] | select(.key == "code_id") | .value')
echo $CODE_ID

Once we get the code_id after storing the contract on chain, we can create an instance of the contract like this:

MSG='{
  "name": "MANTRACW20",
  "symbol": "MNTRA",
  "decimals": 6,
  "initial_balances": [
    {
      "address": "", // add your address here
      "amount": "10000000"
    }
  ]
}'

mantrachaind tx wasm instantiate <code_id> "$MSG" --from <wallet> --node <https://rpc.hongbai.mantrachain.io:443> --chain-id mantra-hongbai-1 --label "MANTRAcw20" --no-admin --gas-prices 0.35uom --gas auto --gas-adjustment 1.4 -y --output json

This will produce an output like the following:

gas estimate: 217659
{"height":"0","txhash":"BB3A0FEF8370B0A407D8AB93919212A4E39E8BA4D52D84836E2E27D76F707D0A","codespace":"","code":0,"data":"","raw_log":"[]","logs":[],"info":"","gas_wanted":"0","gas_used":"0","tx":null,"timestamp":"","events":[]}

We can get the contract address by exploring the transaction hash using jq:

hamantrachaind q tx BB3A0FEF8370B0A407D8AB93919212A4E39E8BA4D52D84836E2E27D76F707D0A --node <https://rpc.hongbai.mantrachain.io:443> -o json | jq -r '.logs[] | .events[] | select(.type == "instantiate") | .attributes[] | select(.key == "_contract_address") | .value'
  • Using typescript:

Create a new folder named “deployer” to manage the deployment scripts:

mkdir deployer

Navigate to the “deployer” folder and initialize it with npm:

cd deployer

npm init -y

npm i

This sets up a new Node.js project in the deployer folder.

Install TypeScript and initialize a TypeScript configuration file:

npm install typescript --save-dev

npx tsc --init

Install the necessary dependencies for the deployment script:

npm install @cosmjs/cosmwasm-stargate

npm install @cosmjs/proto-signing @cosmjs/stargate dotenv fs

Ensure your package.json in the deployer folder includes the following dependencies:

"dependencies": {
    "@cosmjs/cosmwasm-stargate": "^0.32.4",
    "@cosmjs/proto-signing": "^0.32.4",
    "@cosmjs/stargate": "^0.32.4",
    "dotenv": "^16.4.5",
    "fs": "^0.0.1-security"
  }

Now, manually copy the wasm file to the deployer folder, which was created under the artifacts file.

Now create an index.ts file in the deployer folder with the following code for deployment script.

const { DirectSecp256k1HdWallet } = require("@cosmjs/proto-signing");
const {
  assertIsBroadcastTxSuccess,
  SigningCosmWasmClient,
  CosmWasmClient,
} = require("@cosmjs/cosmwasm-stargate");
const { coins, GasPrice } = require("@cosmjs/stargate");
const fs = require("fs");
require("dotenv").config();

const mnemonic = process.env.MNEMONIC;// Replace with your mnemonic
 
const rpcEndpoint = "<https://rpc.hongbai.mantrachain.io>";
const contractWasmPath = "./first_token_cw20contract.wasm"; // Path to your compiled  contract (wasm file)

async function deploy() {
  // Step 1: Set up wallet and client
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: "mantra", // Replace with the correct prefix for your chain
  });
  const [account] = await wallet.getAccounts();
  console.log(`Wallet address: ${account.address}`);

  // Step 2: Connect to the blockchain
  const client = await SigningCosmWasmClient.connectWithSigner(
    rpcEndpoint,
    wallet,
    { gasPrice: GasPrice.fromString("0.0025uom") }
  );
  console.log("Connected to blockchain");

  // Step 3: Upload contract
  const wasmCode = fs.readFileSync("./first_token_cw20contract.wasm"); // wasm file
  const uploadReceipt = await client.upload(
    account.address,
    wasmCode,
    "auto",
    "Upload CosmWasm contract"
  );
  const codeId = uploadReceipt.codeId;
  console.log(`Contract uploaded with Code ID: ${codeId}`);

  // Step 4: Instantiate contract
  const initMsg = {
    name: "MANTRAcw20",
    symbol: "MNTRA",
    decimal: 6,
    initial_balances: [
      {
        address: " ", // add your wallet address
        amount: 10000000,
      },
    ],
  }; // Replace with your contract's init message
  const instantiateReceipt = await client.instantiate(
    account.address,
    codeId,
    initMsg,
    "My CW20 contract",
    "auto"
  );
  const contractAddress = instantiateReceipt.contractAddress;
  console.log(`Contract instantiated at reciept: ${instantiateReceipt}`);
  console.log(`Contract instantiated at address: ${contractAddress}`);
}

deploy().catch(console.error);

Compile TypeScript: Execute the following command to compile index.ts It will automatically create an index.js file upon successful compilation:

tsc index.ts

Deploy Contract: Run the final command to deploy your CW20 contract on the MANTRA Chain. Ensure your wallet contains sufficient OM test tokens:

npx ts-node index.ts

Last updated 8 months ago

For more details on setting up the development environment, check the section .

In the file, define the core contract logic. This includes handling instantiation, execution, and query messages:

These functions define the contract's entry points (instantiate, execute, query, migrate) and handle token operations such as transfers, burns, minting, allowances, and querying uses helper functions from the cw20-base package to handle common CW20 operations.

Once deployed, you will receive the wallet address and confirmation of contract instantiation. Verify your deployment on the MANTRA Chain Explorer at.

Remember to add your mnemonic and MANTRA Chain's RPC endpoint “” wherever mentioned. Additionally, include your wallet address in the initMsg structure. Modify contract.rs, index.ts, and msg.rs as per your contract requirements.

Once deployed, you will receive the wallet address and confirmation of contract instantiation. Verify your deployment on the MANTRA Chain Explorer at .

Install Prerequisites
contract.rs
balances.It
http://explorer.hongbai.mantrachain.io
https://rpc.hongbai.mantrachain.io
http://explorer.hongbai.mantrachain.io