Options
All
  • Public
  • Public/Protected
  • All
Menu

 

The JavaScript SDK for Terra

diagram


GitHub npm (scoped)

Explore the Docs »

Examples · API Reference · NPM Package · GitHub

Terra.js a JavaScript SDK for writing applications that interact with the Terra blockchain from either a Node.js or browser environments and provides simple abstractions over core data structures, serialization, key management, and API request generation.

Features

  • Written in TypeScript, with type definitions
  • Versatile support for key management solutions
  • Works in both Node.js and in the browser
  • Exposes the Terra API through LCDClient
  • Parses responses into native JavaScript types

We highly suggest using Terra.js with TypeScript, or JavaScript in a code editor that has support for type declarations, so you can take advantage of the helpful type hints that are included with the package.

Installation

Grab the latest version off NPM:

yarn add @terra-money/terra.js

Usage

Terra.js can be use in Node.js, as well as inside the browser. Please check the GitHub Wiki for notes on how to get up and running.

Getting blockchain data

import { LCDClient, Coin } from '@terra-money/terra.js';

// connect to soju testnet
const terra = new LCDClient({
  URL: 'https://soju-lcd.terra.dev',
  chainID: 'soju-0014',
});

// To use LocalTerra
// const terra = new LCDClient({
//   URL: 'http://localhost:1317',
//   chainID: 'localterra'
// });

// get the current swap rate from 1 TerraUSD to TerraKRW
const offerCoin = new Coin('uusd', '1000000');
terra.market.swap(offerCoin, 'ukrw').then(c => {
  console.log(`${offerCoin.toString()} can be swapped for ${c.toString()}`);
});

Broadcasting transactions

First, get some testnet tokens for terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v, or use LocalTerra.

import { LCDClient, MsgSend, MnemonicKey } from '@terra-money/terra.js';

// create a key out of a mnemonic
const mk = new MnemonicKey({
  mnemonic:
    'notice oak worry limit wrap speak medal online prefer cluster roof addict wrist behave treat actual wasp year salad speed social layer crew genius',
});

// connect to soju testnet
const terra = new LCDClient({
  URL: 'https://soju-lcd.terra.dev',
  chainID: 'soju-0014',
});

// To use LocalTerra
// const terra = new LCDClient({
//   URL: 'http://localhost:1317',
//   chainID: 'localterra'
// });

// a wallet can be created out of any key
// wallets abstract transaction building
const wallet = terra.wallet(mk);

// create a simple message that moves coin balances
const send = new MsgSend(
  'terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v',
  'terra17lmam6zguazs5q5u6z5mmx76uj63gldnse2pdp',
  { uluna: 1000000, ukrw: 1230201, uusd: 1312029 }
);

wallet
  .createAndSignTx({
    msgs: [send],
    memo: 'test from terra.js!',
  })
  .then(tx => terra.tx.broadcast(tx))
  .then(result => {
    console.log(`TX hash: ${result.txhash}`);
  });

Terra.js in the browser

You can access all the objects of the @terra-money/terra.js from the global Terra object if you load Terra.js with a <script> tag.

Include the following in your browser:

<script
  crossorigin
  src="https://unpkg.com/@terra-money/terra.js/dist/bundle.js"
></script>

You can find a small JSFiddle example that refreshes current Oracle votes here.

License

This software is licensed under the MIT license. See LICENSE for full disclosure.

© 2020 Terraform Labs, PTE.


 

Powering the innovation of money.

Index

Namespaces

Enumerations

Classes

Interfaces

Type aliases

Variables

Functions

Object literals

Type aliases

AccAddress

AccAddress: string

terra- prefixed account address

AccPubKey

AccPubKey: string

terrapub- prefixed account public key

BasePool

BasePool: Type<"market", "basepool", Dec>

BaseProposerReward

BaseProposerReward: Type<"distribution", "baseproposerreward", Dec>

BondDenom

BondDenom: Type<"staking", "BondDenom", Denom>

BonusProposerReward

BonusProposerReward: Type<"distribution", "bonusproposerreward", Dec>

CommunityTax

CommunityTax: Type<"distribution", "communitytax", Dec>

DepositParamsParamChange

DepositParamsParamChange: Type<"gov", "depositparams", DepositParams>

DowntimeJailDuration

DowntimeJailDuration: Type<"slashing", "DowntimeJailDuration", number>

GasMultiplier

GasMultiplier: Type<"wasm", "gasmultiplier", number>

IlliquidTobinTaxList

IlliquidTobinTaxList: Type<"market", "illiquidtobintaxlist", TaxRate[]>

MaxContractGas

MaxContractGas: Type<"wasm", "maxcontractgas", number>

MaxContractMsgSize

MaxContractMsgSize: Type<"wasm", "maxcontractmsgsize", number>

MaxContractSize

MaxContractSize: Type<"wasm", "maxcontractsize", number>

MaxEntries

MaxEntries: Type<"staking", "KeyMaxEntries", number>

MaxEvidenceAge

MaxEvidenceAge: Type<"slashing", "MaxEvidenceAge", number>

MaxValidators

MaxValidators: Type<"staking", "MaxValidators", number>

MinSignedPerWindow

MinSignedPerWindow: Type<"slashing", "MinSignedPerWindow", Dec>

MinSpread

MinSpread: Type<"market", "minspread", Dec>

MinValidPerWindow

MinValidPerWindow: Type<"oracle", "minvalidperwindow", Dec>

MiningIncrement

MiningIncrement: Type<"treasury", "miningincrement", Dec>

PoolRecoveryPeriod

PoolRecoveryPeriod: Type<"market", "poolrecoveryperiod", number>

RewardBand

RewardBand: Type<"oracle", "rewardband", Dec>

RewardDistributionWindow

RewardDistributionWindow: Type<"oracle", "rewarddistributionwindow", number>

RewardPolicy

RewardPolicy: Type<"treasury", "rewardpolicy", PolicyConstraints>

SeigniorageBurdenTarget

SeigniorageBurdenTarget: Type<"treasury", "seigniorageburdentarget", Dec>

SignedBlocksWindow

SignedBlocksWindow: Type<"slashing", "SignedBlocksWindow", number>

SlashFraction

SlashFraction: Type<"oracle", "slashfraction", Dec>

SlashFractionDoubleSign

SlashFractionDoubleSign: Type<"slashing", "SlashFractionDoubleSign", Dec>

SlashFractionDowntime

SlashFractionDowntime: Type<"slashing", "SlashFractionDowntime", Dec>

SlashWindow

SlashWindow: Type<"oracle", "slashwindow", number>

TallyParamsParamChange

TallyParamsParamChange: Type<"gov", "tallyparams", TallyParams>

TaxPolicy

TaxPolicy: Type<"treasury", "taxpolicy", PolicyConstraints>

UnbondingTime

UnbondingTime: Type<"staking", "UnbondingTime", number>

ValAddress

ValAddress: string

terravaloper- prefixed validator operator address

ValConsAddress

ValConsAddress: string

terravalcons- prefixed validator consensus address

ValConsPubKey

ValConsPubKey: string

terravalconspub- prefixed validator consensus public key

ValPubKey

ValPubKey: string

terravaloperpub- prefixed validator public key

VotePeriod

VotePeriod: Type<"oracle", "voteperiod", number>

VoteThreshold

VoteThreshold: Type<"oracle", "votethreshold", Dec>

VotingParamsParamChange

VotingParamsParamChange: Type<"gov", "votingparams", VotingParams>

Whitelist

Whitelist: Type<"oracle", "whitelist", Denom[]>

WindowLong

WindowLong: Type<"treasury", "windowlong", number>

WindowProbation

WindowProbation: Type<"treasury", "windowprobation", number>

WindowShort

WindowShort: Type<"treasury", "windowshort", number>

WithdrawAddrEnabled

WithdrawAddrEnabled: Type<"distribution", "withdrawaddrenabled", boolean>

Variables

Const BECH32_PUBKEY_DATA_PREFIX

BECH32_PUBKEY_DATA_PREFIX: "eb5ae98721" = "eb5ae98721"

Const DEC_PRECISION

DEC_PRECISION: 18 = 18

Const LUNA_COIN_TYPE

LUNA_COIN_TYPE: 330 = 330

Const _Dec

_Dec: Decimal = Decimal.clone()

Const _Int

_Int: Decimal = Decimal.clone()

Functions

addressFromPublicKey

  • addressFromPublicKey(publicKey: Buffer): Buffer
  • Gets a raw address from a compressed bytes public key.

    Parameters

    • publicKey: Buffer

      raw public key

    Returns Buffer

aggregateVoteHash

  • aggregateVoteHash(exchangeRates: Coins, salt: string, validator: ValAddress): string

hashAmino

  • hashAmino(txData: string): string
  • Calculates the transaction hash from Amino-encoded string.

    Parameters

    • txData: string

      Amino-encoded string (base64)

    Returns string

prepareSignBytes

  • prepareSignBytes(obj: any): any

pubKeyFromPublicKey

  • pubKeyFromPublicKey(publicKey: Buffer): Buffer
  • Gets a bech32-words pubkey from a compressed bytes public key.

    Parameters

    • publicKey: Buffer

      raw public key

    Returns Buffer

voteHash

  • voteHash(exchangeRate: string, denom: Denom, salt: string, validator: ValAddress): string

Object literals

Const DEFAULT_LCD_OPTIONS

DEFAULT_LCD_OPTIONS: object

gasAdjustment

gasAdjustment: number = 1.4

gasPrices

gasPrices: object

uluna

uluna: number = 0.015

Const DEFAULT_OPTIONS

DEFAULT_OPTIONS: object

account

account: number = 0

coinType

coinType: number = LUNA_COIN_TYPE

index

index: number = 0

Legend

  • Constructor
  • Property
  • Method
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Static property
  • Static method
  • Property

Generated using TypeDoc