initia.js

Overview

Initia.js is a TypeScript-written JavaScript SDK tailored for the Initia blockchain, enhancing the development experience with user-friendly TypeScript definitions and integration with Initia's core data structures.

Main Features

  • Improved TypeScript Definitions: Offers comprehensive integration with Initia core data structures for an enhanced developer experience.

  • Core Layer: Includes key management, BCS serialization, and support for initia.proto.

  • Client Layer: Facilitates API request generation and LCD provider interaction.

Prerequisites

To use Initia.js effectively, you must have the following installed:

Installation

To install Initia.js, run the following command:

npm install @initia/initia.js

Examples

LCD Client

The LCD (Light Client Daemon) class enables easy interaction with the Initia blockchain.

import { LCDClient } from '@initia/initia.js'

const lcd = new LCDClient('https://lcd.[chain-id].initia.xyz', {
    chainId: '[chain-id]',
    gasPrices: '0.15uinit', // default gas prices
    gasAdjustment: '2.0',   // default gas adjustment for fee estimation
})

Adjust gasPrices and gasAdjustment according to current network conditions for optimal transaction processing.

Key Management

The SDK provides an abstract key interface for transaction signing and address/public key derivation.

import { MnemonicKey } from '@initia/initia.js'

const key = new MnemonicKey({
    mnemonic: 'bird upset ... evil cigar', // (optional) if undefined, generate a new Mnemonic key
    account: 0,    // (optional) BIP44 account number. default = 0
    index: 0,      // (optional) BIP44 index number. defualt = 0
    coinType: 118, // (optional) BIP44 coinType. default = 118
})

Securely store your mnemonic. If not provided, a new mnemonic will be generated, which you should save in a secure location.

BCS

BCS (Binary Canonical Serialization) is crucial for Move contract interactions. Ensure data types match contract expectations.

import { bcs } from '@initia/initia.js'

// serialize value to BCS and encode it to base64
const serializedU64 = bcs
  .u64() // type
  .serialize(1234) // value 
  .toBase64()

// deserialize
const deserializedU64 = bcs
  .u64() // type
  .parse(
    Uint8Array.from(Buffer.from(serializedU64, 'base64'))
  )

// vector
const serializedVector = bcs
  .vector(bcs.u64())
  .serialize([123, 456, 789])
  .toBase64();

// option
const serializedSome = bcs.option(bcs.u64()).serialize(123);
const serializedNone = bcs.option(bcs.u64()).serialize(null);

Supported types for BCS

`u8`, `u16`, `u32`, `u64`, `u128`, `u256`, `bool`, `vector`, `address`, `string`, `option`, 'fixed_point32', 'fixed_point64', 'decimal128', 'decimal256'

Msg Objects

Msgs are objects whose end-goal is to trigger state-transitions. They are wrapped in transactions, which may contain one or more of them.

  • MsgSend() : send coins to other address

import { MsgSend } from '@initia/initia.js'

const msg = new MsgSend(
    'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu',   // sender address
    'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np',   // recipient address
    '1000uinit'                                      // send amount
)
  • MsgDelegate() : delegate governance coin to validators (staking)

import { MsgDelegate } from '@initia/initia.js'

const msg = new MsgDelegate(
    'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // delegator address
    'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np', // validator's operator addres
    '100000uinit',                                 // delegate amount
)
  • MsgExecute() : execute move contract entry functions

import { MsgExecute } from '@initia/initia.js'

const msg = new MsgExecute(
    'init1kdwzpz3wzvpdj90gtga4fw5zm9tk4cyrgnjauu', // sender address
    '0x1',                                         // module owner address
    'dex',                                         // module name
    'swap_script',                                 // function name
    [],                                            // type arguments
    [
        bcs.address().serialize('0x2').toBase64(), // arguments, BCS-encoded
        bcs.address().serialize('0x3').toBase64(), // arguments, BCS-encoded
        bcs.u64().serialize(10000).toBase64()      // arguments, BCS-encoded
    ], 
)

TX Broadcasting

  • createAndSignTx() : create and sign transaction

import { Wallet, LCDClient, MnemonicKey } from '@initia/initia.js'

const key = new MnemonicKey({ mnemonic: 'moral wise ... repair coyote' })
const lcd = new LCDClient('https://lcd.[chain-id].initia.xyz')
const wallet = new Wallet(lcd, key)

const sendMsg = new MsgSend(
    'init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu',   // sender address
    'init18sj3x80fdjc6gzfvwl7lf8sxcvuvqjpvcmp6np',   // recipient address
    '1000uinit',                                     // send amount
)

const signedTx = await wallet.createAndSignTx({
    msgs: [sendMsg],
    memo: 'sample memo',
})
  • broadcast() : send/broadcast your transaction to the blockchain

const broadcastResult = await lcd.tx.broadcast(signedTx)

Queries

  • balance() : query the balance of an account

const balances = await lcd.bank.balance('init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu')
  • viewfunction() : query the move contract view functions

const res = await lcd.move.viewFunction(
    '0x1',                                                  // owner of the module
    'dex',                                                  // name of the module
    'get_swap_simulation',                                  // function name
    ['0x1::native_uinit::Coin', '0x1::native_uusdc::Coin'], // type arguments
    [bcs.u64().serialize(10000).toBase64()]                 // arguments
)

Last updated

Logo

© 2024 Initia Foundation, All rights reserved.