Get started with Terra.js#

This is an in-depth guide on how to use the terra.js SDK.

In this tutorial, you’ll learn how to:

  1. Set up your project

  2. Set up a Terra LCD (light client daemon)

  3. Create and connect a wallet

  4. Query a swap contract

  5. Create, sign, and broadcast a transaction

By the end of this guide, you’ll be able to execute a token swap from your application using Terra.js.

Prerequisites#

1. Set up your project#

  1. Create a new directory for your project:

    mkdir my-terra-js-project
    
  2. Enter your new project directory:

    cd <my-terra-js-project>
    
  3. Next, initialize npm, install the terra.js package, and create an index.js file to house the code:

    npm init -y
    npm install @terra-money/terra.js
    touch index.js
    
  4. Open the package.json file in a code editor and add "type": "module",.

      {
            // ...
            "type": "module",
            // ...
        }
    

2. Initialize the LCD#

Terra’s LCD or Light Client Daemon allows users to connect to the blockchain, make queries, create wallets, and submit transactions. It’s the main workhorse behind terra.js.

  1. Install a fetch library to make HTTP requests and dynamically pull recommended gas prices. You can use the one referenced below or choose your favorite.

    npm install --save isomorphic-fetch
    
  2. Open your index.js file in a code editor and input the following to initialize the LCD:

    import fetch from 'isomorphic-fetch';
    import { Coins, LCDClient } from '@terra-money/terra.js';
    const gasPrices =  await fetch('https://bombay-fcd.terra.dev/v1/txs/gas_prices');
    const gasPricesJson = await gasPrices.json();
    const gasPricesCoins = new Coins(gasPricesJson); 
    const lcd = new LCDClient({
      URL: "https://bombay-lcd.terra.dev/", // Use "https://lcd.terra.dev" for prod "http://localhost:1317" for localterra.
      chainID: "bombay-12", // Use "columbus-5" for production or "localterra".
      gasPrices: gasPricesCoins,
      gasAdjustment: "1.5", // Increase gas price slightly so transactions go through smoothly.
      gas: 10000000,
    });
    

    Switching to LocalTerra or the mainnet

    The previous code block shows how to connect to the Bombay testnet. To connect to LocalTerra, change the URL to ”http://localhost:1317”. To connect to the Columbus-5 mainnet for production, use “https://lcd.terra.dev”.

    You will also need to change the chainID from "bombay-12" to ”localterra” or "columbus-5".

3. Create a Bombay testnet wallet#

  1. You’ll need a wallet to sign and submit transactions. Create a new wallet using the Terra Station extension. Be sure to save your mnemonic key!

  2. After creating your wallet, you’ll need to set it to use the testnet. Click the gear icon in the extension and change the network from mainnet to testnet.

  3. Add the following code to your index.js file and input your mnemonic key:

    import { MnemonicKey } from '@terra-money/terra.js';
    const mk = new MnemonicKey({
      mnemonic: ' //Input your 24-word mnemonic key here//',
    });
    const wallet = lcd.wallet(mk);
    

    Mnemonic security

    Although this tutorial has you input your mnemonic directly, this practice should be avoided in production. For security reasons, it’s better to store your mnemonic key data in your environment by using process.env.SECRET_MNEMONIC or process.env.SECRET_PRIV_KEY. This practice is more secure than a hard-coded string.

  4. Request testnet funds for your wallet by navigating to the Terra faucet and inputting your wallet address. You’ll need these funds to perform swaps and pay for gas fees. Once the funds are in your wallet, you’re ready to move on to the next step.

4. Find a contract address#

To find the contract address for a specific Terraswap pair, visit https://app.terraswap.io/

This tutorial uses the Luna/UST contract testnet address:

terra156v8s539wtz0sjpn8y8a8lfg8fhmwa7fy22aff

5. Query a Terraswap contract and set up the transaction#

Before you can perform a swap, you’ll need a belief price. You can calculate the belief price of UST by querying the proportion of the Luna and UST pools. The belief price +/- the max_spread is the range of possible acceptable prices for this swap.

  1. Add the following code to your index.js file. Make sure the contract address is correct.

    const pool = "terra156v8s539wtz0sjpn8y8a8lfg8fhmwa7fy22aff"; // The LUNA/UST terraswap contract address on Bombay.
    const { assets } = await lcd.wasm.contractQuery(pool, { pool: {} }); // Fetch the amount of each asset in the pool.
    const beliefPrice = (assets[0].amount / assets[1].amount).toFixed(18); // Calculate belief price using proportion of pool balances.
    
  2. Next, generate a message to broadcast to the network:

    import { MsgExecuteContract } from '@terra-money/terra.js';
    // Swap LUNA to UST with 0.1% slippage tolerance.
    const terraSwap = new MsgExecuteContract(
      wallet.key.accAddress,
      pool, 
      {
        swap: {
          max_spread: "0.001",
          offer_asset: {
            info: {
              native_token: {
                denom: "uluna",
              },
            },
            amount: "100000",
          },
          belief_price: beliefPrice,
        },
      },
      new Coins({ uluna: '100000' })
    );
    

6. Broadcast the transaction#

  1. Add the following code to index.js to create, sign, and broadcast the transaction. It’s important to specify uluna as the fee denomination becuase Luna is the only denomination the faucet sends.

        const tx = await wallet.createAndSignTx({ msgs: [terraSwap], feeDenoms: ['uluna'] });
        const result = await lcd.tx.broadcast(tx);
        console.log(result);
    
  2. Run the code in your terminal:

    node index.js
    

If successful, you’ll see a log of the successful transaction and some new UST tokens in your wallet.

And that’s it! You can find other pool addresses here to call other swaps. Be sure to use the correct testnet or mainnet contract address.

More examples#

View the Common examples section for more information on using Terra.js.