# Deployment using TypeScript (Windows/Linux/Mac)

### **Deployment on DuKong Testnet**

This guide will walk you through deploying your contract on the DuKong Testnet. Before proceeding, ensure your development environment is set up and all prerequisites are installed. Ensure your wallet is configured and has sufficient OM test tokens to cover gas fees and contract instantiation costs.

#### **Setting Up Your Development Environment**

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

1. **Install Rust:**

CosmWasm contracts are written in Rust. Open your system terminal and run the following command:

{% code overflow="wrap" %}

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

{% endcode %}

Follow the prompts during installation. Choose the default installation option to install Rust on your system.

1. **Set Rust to Stable Version:**

```bash
$ rustup default stable
```

This sets the default Rust version to stable.

1. **Install Cargo:**

Ensure Cargo is installed by checking its version:

```bash
$ cargo --version
```

1. **Add WebAssembly Target:**

This command adds the WebAssembly target to Rust, necessary for compiling CosmWasm contracts.

```bash
$ rustup target add wasm32-unknown-unknown
```

1. **Install cargo-generate:**

**cargo-generate** allows you to generate new Rust projects from templates.

```bash
$ cargo install cargo-generate --features vendored-openssl
```

### ***Boilerplate Setup***

We have a boilerplate where all contracts and the working directory are already set up. We just need to deploy the contract.

**Clone the Repository**

```bash
git clone <https://github.com/MANTRA-Finance/contract_deploy.git>
```

Check dependencies by navigating to the `Cargo.toml` file in the root directory of your project. This file manages dependencies for your Rust project. Add the following dependencies:

{% code overflow="wrap" %}

```toml
[dependencies]
cw20-base = {  version = "0.13.2", features = ["library"] }
cw20 = "2.0.0"
cw-utils = "0.12.1"
cosmwasm-std = "1.0.0"
cosmwasm-storage = "1.1.1"
cw-storage-plus = "0.15.0"
cw2 = "0.15.0"
schemars = "0.8.10"
serde = { version = "1.0.144", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.31" }
cosmwasm-schema = "1.1.4"
prost = "0.12"

```

{% endcode %}

Now our boiler plate is ready and we can go ahead with deployment on DuKong Testnet and later verify our contract on Explorer.

#### **Build and Deploy the Contract**

Open your terminal in the project directory let’s build it using the rust optimizer with the following command:

{% code overflow="wrap" %}

```
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
```

{% endcode %}

This command will generate necessary `artifacts` including the `wasm` file and other required files.

#### **Deployment Script Setup**

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:

```json
"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** folder.

Create an `index.ts`file in the **deployer** folder with the following code for deployment script.

{% code overflow="wrap" %}

```tsx
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 = process.env.RPC; // Replace with your RPC endpoint
const rpcEndpoint = "<https://rpc.dukong.mantrachain.io>";
const contractWasmPath = "./dinonum.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.01uom") }
  );
  console.log("Connected to blockchain");

  // Step 3: Upload contract
  const wasmCode = fs.readFileSync("./dinonum.wasm");
  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 = {
    count: 10,
  }; // Replace with your contract's init message
  const instantiateReceipt = await client.instantiate(
    account.address,
    codeId,
    initMsg,
    "My Dinonum Contract",
    "auto"
  );
  const contractAddress = instantiateReceipt.contractAddress;
  console.log(`Contract instantiated at reciept: ${instantiateReceipt}`);
  console.log(`Contract instantiated at address: ${contractAddress}`);
}

deploy().catch(console.error);

```

{% endcode %}

{% hint style="info" %}
Remember to add your **mnemonic** and MANTRA Chain's **RPC endpoin**t “[https://rpc.dukong.mantrachain.io](https://rpc.dukong.mantrachain.io/)” wherever mentioned. And don’t share your **mnemonic** with anyone.
{% endhint %}

#### **Deploy the Contract**

**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
```

Once deployed, you will receive the wallet address and confirmation of contract instantiation.

<figure><img src="https://757023404-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHWR3GTzM6hfL5VomqMpE%2Fuploads%2Fgit-blob-ceac7267f3d955ecd32e1a2f5d4673eee2883cff%2Funnamed-3.png?alt=media" alt=""><figcaption></figcaption></figure>

Now, verify your deployment on the MANTRA Chain Explorer at <https://explorer.mantrachain.io>.

When you run the command `npx ts-node index.ts`, it executes your TypeScript script for deploying a smart contract on the DuKong Testnet. The output messages confirm various steps in the deployment process. First, the script prints the wallet address (`mantra1celwechlkzqj9vh3x8vcu26fwvtct6ey5l3uvc`), indicating that the wallet has been set up correctly. Next, it confirms a successful connection to the blockchain. The contract is then uploaded, and the script provides a **Code ID (401)** for the uploaded contract. Finally, the contract is instantiated, and although it shows an object for the receipt, it provides the address of the instantiated contract (`mantra18u93lf7jk3dc9d7dulsfdpqn5lqqzk9ee5fujle4v7y29sajelfs847jnm`). This means the contract is now deployed and live on the testnet.

Kudos!! Our CosmWasm contract is successfully deployed on DuKong Testnet.
