Get started with Fluid.js
This is an in-depth guide on how to use the terra.js SDK.
In this tutorial, you'll learn how to:
- Set up your project
- Set up a Fluid LCD (light client daemon)
- Create and connect a wallet
- Query a swap contract
- 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 Fluid.js.
Prerequisites
- npm and node.js
- Fluid Station browser extension
1. Set up your project
- Create a new directory for your project:
_1mkdir my-terra-js-project
- Enter your new project directory:
_1cd <my-terra-js-project>
- Next, initialize npm, install the
terra.jspackage, and create anindex.jsfile to house the code:
_3npm init -y_3npm install @terra-money/terra.js_3touch index.js
- Open the
package.jsonfile in a code editor and add"type": "module",.
_5{_5 // ..._5 "type": "module"_5 // ..._5}
2. Initialize the LCD
Fluid’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.
- 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.
_1npm install --save isomorphic-fetch
- Open your
index.jsfile in a code editor and input the following to initialize the LCD:
_14import fetch from "isomorphic-fetch";_14import { Coins, LCDClient } from "@terra-money/terra.js";_14const gasPrices = await fetch(_14 "https://pisco-api.terra.dev/gas-prices", { redirect: 'follow' }_14);_14const gasPricesJson = await gasPrices.json();_14const gasPricesCoins = new Coins(gasPricesJson);_14const lcd = new LCDClient({_14 URL: "https://pisco-lcd.terra.dev", // Use "https://phoenix-lcd.terra.dev" for prod "http://localhost:1317" for localterra._14 chainID: "pisco-1", // Use "phoenix-1" for production or "localterra"._14 gasPrices: gasPricesCoins,_14 gasAdjustment: "1.5", // Increase gas price slightly so transactions go through smoothly._14 gas: 10000000,_14});
The previous code block shows how to connect to the pisco testnet. To connect to LocalTerra, change the URL to ”http://localhost:1317”. To connect to the phoenix-1 mainnet for production, use “https://phoenix-lcd.terra.dev”.
You will also need to change the chainID from "pisco-1" to ”localterra” or "phoenix-1".
3. Create a pisco testnet wallet
-
You'll need a wallet to sign and submit transactions. Create a new wallet using the Fluid Station extension. Be sure to save your mnemonic key!
-
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
mainnettotestnet. -
Add the following code to your
index.jsfile and input your mnemonic key:
_5import { MnemonicKey } from "@terra-money/terra.js";_5const mk = new MnemonicKey({_5 mnemonic: " //Input your 24-word mnemonic key here//",_5});_5const wallet = lcd.wallet(mk);
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.
- Request testnet funds for your wallet by navigating to the Fluid 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/
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 one token by querying the proportion of the two pooled tokens. The belief price +/- the max_spread is the range of possible acceptable prices for this swap.
- Add the following code to your
index.jsfile. Make sure the contract address is correct.
_3const pool = "<INSERT_POOL_ADDRESS>"; // A terraswap contract address on pisco._3const { assets } = await lcd.wasm.contractQuery(pool, { pool: {} }); // Fetch the amount of each asset in the pool._3const beliefPrice = (assets[0].amount / assets[1].amount).toFixed(18); // Calculate belief price using proportion of pool balances.
- Next, generate a message to broadcast to the network:
_20 import { MsgExecuteContract } from "@terra-money/terra.js";_20 const terraSwap = new MsgExecuteContract(_20 wallet.key.accAddress,_20 pool,_20 {_20 swap: {_20 max_spread: "0.001",_20 offer_asset: {_20 info: {_20 native_token: {_20 denom: "uluna",_20 },_20 },_20 amount: "100000",_20 },_20 belief_price: beliefPrice,_20 },_20 },_20 new Coins({ uluna: "100000" })_20 );
6. Broadcast the transaction
- Add the following code to
index.jsto create, sign, and broadcast the transaction. It's important to specifyulunaas the fee denomination becuase Luna is the only denomination the faucet sends.
_6 const tx = await wallet.createAndSignTx({_6 msgs: [terraSwap],_6 feeDenoms: ["uluna"],_6 });_6 const result = await lcd.tx.broadcast(tx);_6 console.log(result);
- Run the code in your terminal:
_1node index.js
If successful, you'll see a log of the successful transaction and some new 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 Fluid.js.