> For the complete documentation index, see [llms.txt](https://initia.gitbook.io/initia/kBNuZF5MglV9d3zOOUeW/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://initia.gitbook.io/initia/kBNuZF5MglV9d3zOOUeW/references-and-tools/initia.js.md).

# Initia.js

**Initia.js** is the JavaScript SDK for Initia, written in Typescript.

## Main Features

* Improve user-friendly Typescript definitions with Initia core data structures integration
* Core Layer: key management, BCS serialization, support initia.proto
* Client Layer: API request generation, LCD provider

## Prerequisites

Initia.js requires the installation of the following packages in order to function properly

* node.js v14+
* npm

## Installation

```
npm install @initia/initia.js
```

## Usage

### LCD Client

LCD (Light Client Daemon) class facilitates interaction with the Initia blockchain

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

const lcd = new LCDClient('https://lcd.mahalo-2.initia.xyz', {
    chainId: 'stone-1',
    gasPrices: '0.005uinit', // default gas prices
    gasAdjustment: '2.0',    // default gas adjustment for fee estimation
})
```

### Key

An abstract key interface that enables transaction signing and provides bech32 address and public key derivation from a public key

```typescript
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
})
```

### BCS

BCS (Binary Canonical Serialization) is the binary encoding for Move resources and other non-module values published on-chain

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

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 others

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

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

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

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

const key = new MnemonicKey({ mnemonic: 'moral wise ... repair coyote' })
const lcd = new LCDClient('https://lcd.mahalo-1.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',
})
```

> When sending coins with `MsgSend`, sender address should be the wallet address

* `broadcast():` send/broadcast your transaction to the blockchain

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

### Queries

* `balance():` query balance of the account

```typescript
const balances = await lcd.bank.balance('init14l3c2vxrdvu6y0sqykppey930s4kufsvt97aeu')
```

* `viewfunction():` query the move contract view functions

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


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://initia.gitbook.io/initia/kBNuZF5MglV9d3zOOUeW/references-and-tools/initia.js.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
