Staking/Unstaking LP Tokens with CosmJS
Overview
This tutorial is a complete CosmJS script that stakes a pool's LP tokens in the Incentives contract, checks the position and pending rewards, claims rewards and unstakes. It works with both LP token types: native tokenfactory LP tokens (factory/<pool>/astroport/share) and CW20 LP tokens.
For an explanation of each message, see Staking/Unstaking LP Tokens and Claiming Rewards.
| Chain | Incentives |
|---|---|
| Terra | terra1eywh4av8sln6r45pxq45ltj798htfy0cfcf7fy3pxc2gcv6uc07se4ch9x |
| Neutron | neutron173fd8wpfzyqnfnpwq2zhtgdstujrjz2wkprkjfr6gqg4gknctjyq6m3tch |
There are no ASTRO emissions. Staked LP tokens earn only the external incentive schedules added to their pool. Check a pool's pool_info in Incentives to see whether it has any.
Step 1: Connect
The script uses Terra and the LUNA/USDC pool. For Neutron, change the constants, use prefix: "neutron" without hdPaths, and an untrn gas price.
_17import { SigningCosmWasmClient, toBinary } from "@cosmjs/cosmwasm-stargate";_17import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";_17import { stringToPath } from "@cosmjs/crypto";_17import { GasPrice } from "@cosmjs/stargate";_17_17const rpc = "https://terra-rpc.publicnode.com";_17const incentives = "terra1eywh4av8sln6r45pxq45ltj798htfy0cfcf7fy3pxc2gcv6uc07se4ch9x";_17const pool = "terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu"; // LUNA/USDC_17_17const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {_17 prefix: "terra",_17 hdPaths: [stringToPath("m/44'/330'/0'/0/0")],_17});_17const [{ address: sender }] = await wallet.getAccounts();_17const client = await SigningCosmWasmClient.connectWithSigner(rpc, wallet, {_17 gasPrice: GasPrice.fromString("0.015uluna"),_17});
Step 2: Find the LP Token
_2const { liquidity_token: lpToken } = await client.queryContractSmart(pool, { pair: {} });_2const isNativeLp = lpToken.startsWith("factory/");
Step 3: Stake
Native LP tokens are attached to deposit. CW20 LP tokens are sent to Incentives with a send that embeds deposit.
_13const stake = async (amount) => {_13 if (isNativeLp) {_13 return client.execute(sender, incentives, { deposit: {} }, "auto", "", [_13 { denom: lpToken, amount },_13 ]);_13 }_13 return client.execute(_13 sender,_13 lpToken,_13 { send: { contract: incentives, amount, msg: toBinary({ deposit: {} }) } },_13 "auto"_13 );_13};
Step 4: Check the Position
_7const staked = await client.queryContractSmart(incentives, {_7 deposit: { lp_token: lpToken, user: sender },_7});_7_7const pending = await client.queryContractSmart(incentives, {_7 pending_rewards: { lp_token: lpToken, user: sender },_7});
Step 5: Claim Rewards
_2const claim = () =>_2 client.execute(sender, incentives, { claim_rewards: { lp_tokens: [lpToken] } }, "auto");
Step 6: Unstake
withdraw returns the LP tokens and pays out pending rewards in the same transaction.
_2const unstake = (amount) =>_2 client.execute(sender, incentives, { withdraw: { lp_token: lpToken, amount } }, "auto");
Complete Script
_68import { SigningCosmWasmClient, toBinary } from "@cosmjs/cosmwasm-stargate";_68import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";_68import { stringToPath } from "@cosmjs/crypto";_68import { GasPrice } from "@cosmjs/stargate";_68_68const rpc = "https://terra-rpc.publicnode.com";_68const incentives = "terra1eywh4av8sln6r45pxq45ltj798htfy0cfcf7fy3pxc2gcv6uc07se4ch9x";_68const pool = "terra1v3lqxl0eyte9x3nhdgcj8hwvjq76aupnnzz0yll8mxs5cckc29pqvg2scu";_68const amount = "1000000"; // LP tokens to stake, in base units_68_68const main = async () => {_68 const wallet = await DirectSecp256k1HdWallet.fromMnemonic(process.env.MNEMONIC, {_68 prefix: "terra",_68 hdPaths: [stringToPath("m/44'/330'/0'/0/0")],_68 });_68 const [{ address: sender }] = await wallet.getAccounts();_68 const client = await SigningCosmWasmClient.connectWithSigner(rpc, wallet, {_68 gasPrice: GasPrice.fromString("0.015uluna"),_68 });_68_68 const { liquidity_token: lpToken } = await client.queryContractSmart(pool, { pair: {} });_68 const isNativeLp = lpToken.startsWith("factory/");_68_68 // Stake_68 const stakeTx = isNativeLp_68 ? await client.execute(sender, incentives, { deposit: {} }, "auto", "", [_68 { denom: lpToken, amount },_68 ])_68 : await client.execute(_68 sender,_68 lpToken,_68 { send: { contract: incentives, amount, msg: toBinary({ deposit: {} }) } },_68 "auto"_68 );_68 console.log("Staked:", stakeTx.transactionHash);_68_68 // Position and pending rewards_68 const staked = await client.queryContractSmart(incentives, {_68 deposit: { lp_token: lpToken, user: sender },_68 });_68 const pending = await client.queryContractSmart(incentives, {_68 pending_rewards: { lp_token: lpToken, user: sender },_68 });_68 console.log("Staked amount:", staked, "Pending rewards:", pending);_68_68 // Claim_68 const claimTx = await client.execute(_68 sender,_68 incentives,_68 { claim_rewards: { lp_tokens: [lpToken] } },_68 "auto"_68 );_68 console.log("Claimed:", claimTx.transactionHash);_68_68 // Unstake everything_68 const unstakeTx = await client.execute(_68 sender,_68 incentives,_68 { withdraw: { lp_token: lpToken, amount: staked } },_68 "auto"_68 );_68 console.log("Unstaked:", unstakeTx.transactionHash);_68};_68_68main().catch((error) => {_68 console.error(error);_68 process.exit(1);_68});