Giter VIP home page Giter VIP logo

terra.js's Introduction

 

The JavaScript SDK for Terra

diagram


GitHub npm (scoped)

Explore the Docs »

Examples · API Reference · NPM Package · GitHub

Terra.js is a JavaScript SDK for writing applications that interact with the Terra blockchain from either Node.js, browser, or React Native 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 Node.js, in the browser, and React Native
  • 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:

npm install @terra-money/terra.js

Usage

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

Getting blockchain data

❗ terra.js can connect both terra-classic and terra network. If you want to communicate with classic chain, you have to set isClassic as true.

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

// connect to pisco testnet
const terra = new LCDClient({
  URL: 'https://pisco-lcd.terra.dev',
  chainID: 'pisco-1',
  isClassic: false  // if it is unset, LCDClient assumes the flag is false.
});

// connect to columbus-5 terra classic network
const terra = new LCDClient({
  URL: 'https://columbus-lcd.terra.dev',
  chainID: 'columbus-5',
  isClassic: true  // *set to true to connect terra-classic chain*
});

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

// get the current balance of `terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v`
const balance = terra.bank.balance('terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v');
console.log(balance);

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 bombay testnet
const terra = new LCDClient({
  URL: 'https://pisco-lcd.terra.dev',
  chainID: 'pisco-1',
});

// 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: 1200000}
);

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.

Terra.js in React Native

In order to use Terra.js inside React Native, you need to add the node-libs-react-native package and react-native-get-random-values package to your React Native app's package.json.

yarn add node-libs-react-native react-native-get-random-values

You will need to register Node.js native modules in an entry point of your application, such as index.tsx:

import 'node-libs-react-native/globals';
import 'react-native-get-random-values';

Also, add resolvers to your metro.config.js

module.exports {
  // ...
  resolver: {
    // ...
    extraNodeModules: require('node-libs-react-native'),
  },
  // ...
}

License

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

© 2020 Terraform Labs, PTE.


 

terra.js's People

Contributors

ouiliame avatar hanjukim avatar yun-yeo avatar vritra4 avatar alecande11 avatar octalmage avatar fragwuerdig avatar rtviii avatar decryptdavid avatar jared-tfl avatar emidev98 avatar snyk-bot avatar gregnuj avatar dependabot[bot] avatar jkhaui avatar 0xslipk avatar alpac-4 avatar erichgorski avatar arian81 avatar trytocatcharg avatar romainlanz avatar matanhamilis avatar kmartin62 avatar jimryan avatar kjessec avatar inon-man avatar hinaser avatar bokuhe avatar hanwong avatar wengzilla avatar

Stargazers

mooryoung avatar Konstantin avatar  avatar Rrbin avatar Arunaday Basu avatar Jin Park avatar Vitaly avatar  avatar  avatar shawn avatar Joshua Boone avatar  avatar Michael avatar  avatar  avatar Nayuki avatar Errnull's candy avatar Daegyeom Ha avatar Keith Hörling avatar  avatar wudi avatar MEME Chain avatar Nikita avatar Steve Juneyoung Kang avatar IT avatar Patrick Kelly avatar Imran Javed avatar NunaX avatar  avatar K. N. avatar Boom avatar MIG TAM avatar Vishal Isharani avatar  avatar  avatar Igor Pancheski avatar Pablo Vinícius avatar Ankur Singhal avatar Diegotham avatar Samuel Safahi avatar  avatar ELI JOSEPH BRADLEY avatar Zack Zhong avatar  avatar Bora Lee avatar Mahdi Madah Pour avatar Sam avatar xmonader avatar Jeffrey Bodin avatar  avatar Lilith Roth avatar J. Brandon Johnson avatar HirokiYasui avatar Stéphane Busso avatar Joaquín Núñez avatar Damin Lee avatar Nick Wan avatar  avatar Joseph Toledano  avatar  avatar marty avatar  avatar Chai Phonbopit avatar James Nguyen avatar Victor Demin avatar Emery avatar Andrew Paulicek avatar Peng Peng avatar Rui Antunes avatar 22388o⚡️  avatar  avatar  avatar Joaquin Rivera Padron avatar Natawat Kwanpum avatar  avatar Tristan Blake avatar Javis avatar Jaime Barreto avatar  avatar  avatar Bruno Afonso avatar Guilherme Mota avatar Ilda Neta avatar Youngsoo Yi avatar Murilo Veiga avatar Emre Pehlivan avatar  avatar Nicolás Bevilacqua avatar Jeffrey H. Chen avatar Peter Kim avatar juancito avatar Lucas Alves avatar Kaom Te avatar  avatar Leo Lozach avatar OB avatar Sebastian Mandrean avatar Tennison Chan avatar Peter Ramos avatar Rocco Musolino avatar

Watchers

Frank Dai avatar  avatar  avatar Do Kwon avatar  avatar Oozman avatar Jiri Jetmar avatar  avatar  avatar Carlos avatar crypto.nomad avatar Abdullah Al Maruf avatar Lukasz Maslanka avatar ip config avatar Hyungsuk Kang avatar sg avatar Jade Kim avatar Terence Lim avatar Djordje Simovic avatar  avatar Lim SangHyun(Blue) avatar Vlad J avatar Mike avatar Joshua Brigati avatar  avatar CTO avatar  avatar Skyler Shuman avatar kyro avatar  avatar  avatar  avatar  avatar

terra.js's Issues

Uncaught ReferenceError: process is not defined

Trying to use this code to connect to the extension:

const terraExtension = new Terra.Extension();
terraExtension.connect();
terraExtension.on("connect", (wallet) => {
  console.log(wallet);
});

The first time I ran it, Station wallet showed up and asked me to connect and I did.

However, on subsequent runs, I'm seeing these two errors:

readable-process
writable-error

The correct way of forecasting non-luna gas prices

I see two ways to estimate the gas price for non-luna currencies in the API. For simplicity, let's assume 'ukrw' on testnet:

  1. Take the luna gas price from lcd.config.gasPrices (as it's the only entry there) and multiply by the exchange rate for 'ukrw'
  2. Build a tx and use or /create /estimate_fee and get the uusd from gasPrices of the fee structure that it returned (here it is filled)

However, I get vastly different values. For ukrw in tequila-4 I get 2986.3737 for (1) and 0.022869 for (2).
Is this the expected behavior?
What is the correct way to estimate the gas price, optimally without creating the transaction beforehand?

chainID tequila-0004 still get info from mainnet columbus-4

The real code (node.js):

const TerraJS = require("@terra-money/terra.js");

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

terraClient.bank.balance("terra106h043ewfd0xrnwuazkf05q72cfm7kwj784la2")
    .then((res) => { console.log(res) })
    .catch((e) => { console.error(e) });

Returns information from the mainnet Columbus-4 instead of tequila-0004. What I do wrong?

Coins {
  _coins: {
    ukrw: Coin { denom: 'ukrw', amount: 3672534 },
    uluna: Coin { denom: 'uluna', amount: 654532 },
    umnt: Coin { denom: 'umnt', amount: 44034 },
    usdr: Coin { denom: 'usdr', amount: 8 },
    uthb: Coin { denom: 'uthb', amount: 3 },
    uusd: Coin { denom: 'uusd', amount: 39796706 }
  }
}

Any reason for limiting node version to >=12?

I've noticed the minimum required node version was restricted to 12 in #43.
I wonder if there is any particular reason for that?
The library seems to build and work just fine with node 10.
All tests pass

Getting an error when trying to use `terra.lcd.staking.delegations(delegator)`

I am getting an error when trying to use terra.lcd.staking.delegations(delegator);
This is the address I used in tequila:
https://tequila-fcd.terra.dev/staking/delegators/terra1xpjtwmemdwz053q4jxjx0ht4dtp25rc799deyf/delegations

Expected to receive the delegation state of the address.
Instead got a crash:

(node:22793) UnhandledPromiseRejectionWarning: Error: [DecimalError] Invalid argument: [object Object]
    at parseOther (/Users/amanusk/Code/Terra/terra-new-playground/node_modules/decimal.js/decimal.js:3604:13)
    at new Decimal (/Users/amanusk/Code/Terra/terra-new-playground/node_modules/decimal.js/decimal.js:4353:55)
    at new Int (/Users/amanusk/Code/Terra/terra-new-playground/node_modules/@terra-money/terra.js/dist/core/numeric.js:126:20)
    at Delegation.fromData (/Users/amanusk/Code/Terra/terra-new-playground/node_modules/@terra-money/terra.js/dist/core/staking/Delegation.js:40:96)
    at Array.map (<anonymous>)
    at /Users/amanusk/Code/Terra/terra-new-playground/node_modules/@terra-money/terra.js/dist/client/lcd/api/StakingAPI.js:82:72
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:22793) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:22793) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Exception has occurred: TypeError: Cannot set property 'sender' of undefined (Bombay-0007)

I'm getting the above error when using @terra-money/terra.js@bombay. It rhows in this method:

function MsgStoreCode(sender, wasm_byte_code) {
var _this = _super.call(this) || this;
_this.sender = sender;
_this.wasm_byte_code = wasm_byte_code;
return _this;
}

I'm calling MsgStoreCode like so:

const storeCode = MsgStoreCode(
wallet.key.accAddress,
contract_bytes
)

Error: instantiate failed.

Hello when i try to instantiate contract i receive:

(node:95071) UnhandledPromiseRejectionWarning: Error: instantiate failed. code: 4, codespace: sdk, raw_log: signature verification failed; please verify account number (48632), sequence (0) and chain-id (bombay-9): unauthorized

Source looks like this:

const instantiate = new MsgInstantiateContract(
    wallet.key.accAddress,
    '',
    3989,
    {
      buyer: 'terra1krq0p9qh9nujpf77cvma36acyeqy7gdedfamgw',
      seller: 'terra1krq0p9qh9nujpf77cvma36acyeqy7gdedfamgw',
      value: 1,
      expiration: 5,
      secret_hash: '688787d8ff144c502c7f5cffaafe2cc588d86079f9de88304c26b0cb99ce91c6'
    },
    { uluna: 1 },
  );

  const instantiateTx = await wallet.createAndSignTx({
    msgs: [instantiate]
  });


  const instantiateTxResult = await terra.tx.broadcast(instantiateTx);

  if (isTxError(instantiateTxResult)) {
    throw new Error(
      `instantiate failed. code: ${instantiateTxResult.code}, codespace: ${instantiateTxResult.codespace}, raw_log: ${instantiateTxResult.raw_log}`
    );
  }

  const {
    instantiate_contract: { contract_address }
  } = instantiateTxResult.logs[0].eventsByType;

  console.log('contract address', contract_address);

It's failing on:

const instantiateTx = await wallet.createAndSignTx({
    msgs: [instantiate]
  });

chain: bombay-9
terra.js: 2.1.0

It's working fine from the terra station

txInfo from col-4

Hi!

I have a problem calling txInfo for transaction made in col-4. I am getting 404 not found error while in terra finder it works like a charm.
Here is an example call:
await terra.tx.txInfo('D7BC896AAF3168DC44A2F2F30E47BD9DCB0ADDDB71F74EAFDAC49752205444C4')

terra is in this case LCDClient initialised with col-5

Could you please check this scenario?

How I can get max spendable amount?

Hi! Please, give me an example, how can I ask LCD to return:

  1. Max spendable amount uluna
  2. Generate tx with max spendable amount with a normal fee size

Or how I can calculate it from balance with all available public data (as treasuryTaxRate)?

I tried to found this on Station sources but unsuccessfully🥺

sign and verify message using `terra.js`

Hi, I am wondering if it is possible to sign a message using Terra Extension and in a result receive some signature and then verify if this message was signed with particular address using provided signature.

How it works in Ethereum (pseudocode):

var accounts = await web3.eth.getAccounts()
var signature = await web3.eth.personal.sign(message, accounts[0])

and later

var signing_address = await web3.eth.personal.ecRecover(message, signature)

additionally on Ethereum we can also hash a message like below:

message = web3.eth.accounts.hashMessage(message)

It is createSignature function a good starting point? if yes how to verify then, if no how to achieve such flow ?

error - ./node_modules/@terra-money/webapp-provider/contexts/bank.js:35:0

Getting this error from webapp-provider:

error - ./node_modules/@terra-money/webapp-provider/contexts/bank.js:35:0
Module not found: Can't resolve '@terra-dev/use-browser-inactive'

Here is the version I'm using

"dependencies": {
"@material-ui/core": "^4.11.4",
"@material-ui/icons": "^4.11.2",
"@terra-money/wallet-provider": "^0.14.0",
"@terra-money/webapp-provider": "^0.15.0",
"@types/react": "^17.0.9",
"next": "^10.0.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-use-clipboard": "^1.0.7",
"typescript": "^4.3.2"
}

invalid character -- Amino:JSON int/int64/uint/uint64 expects quoted values for javascript numeric support, got:

Hi, when I user terra js to instantiate a contract I get the error:

      error: 'invalid character -- Amino:JSON int/int64/uint/uint64 expects quoted values for javascript numeric support, got: {"count":"5"}.'

My code is

const instantiate = new MsgInstantiateContract(
  wallet.key.accAddress,
  code_id_num.toFixed(), // code ID
  { count: '5' }, // InitMsg
  { uluna: 10000000, ukrw: 1000000 }, // init coins
  false // migratable
);

const instantiateTx = await wallet.createAndSignTx({
  msgs: [instantiate],
});

Usage with rollup?

I had trouble getting this to work with Rollup for browser usage.

Not the end of the world since I can just use the prebuilt dist, but anyone else have this working and can share their rollup config?

I tried some combos of commonjs, noderesolve, etc...

Add an option to createTx not related to the stored key

When creating a transaction, it is only possible to create it with the initiated key

https://github.com/terra-project/terra.js/blob/a2e630f59e108e42d869e522c5dcf113a1eeabe7/src/client/lcd/Wallet.ts#L66

It would be useful if createTx could optionally received an address and use it to create the transaction. The account address associated with the key can be used by default, if not address is passed as parameter.

This can help creating transaction that can then be signed by an external signer, such as a remote server/hardware device.

Getting error api is deprecate

Here is my package.json

 "dependencies": {
    "@terra-money/terra.js": "^2.0.14"
  },

Here is transaction info:

https://finder.terra.money/bombay-12/tx/ED36C9530CF5F64C5460E7D2E3A62D33BC30D3AA4D4AEEF5098AF0F52660EC3A

const terra = new LCDClient({
     URL: "https://lcd.terra.dev",
     chainID: "columbus-5"
});

terra.tx.txInfo("ED36C9530CF5F64C5460E7D2E3A62D33BC30D3AA4D4AEEF5098AF0F52660EC3A")
.then(res=>{console.log(res)})
.catch(err=>{ console.log(err)});

Even my wallet api is also not working:

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

Getting error:

   link: '<https://docs.cosmos.network/master/migrations/rest.html>; rel="deprecation"',
      warning: '199 - "this endpoint is deprecated and may not work as before, see deprecation link for more info"',
      'x-server-time': '1633615986',
      'access-control-allow-origin': '*',
      'access-control-allow-methods': 'GET, POST, OPTIONS',
      'access-control-allow-headers': 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range',
      'access-control-expose-headers': 'Content-Length,Content-Range',
      'cf-cache-status': 'DYNAMIC',
      'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
      'set-cookie': [Array],
Can please anyone tell me. What should I do, to fix this?

Get transaction info API is break when message pubic key is null

Hi, I have using the LCD client to get transaction information but, I occurred an error when get the transaction FA82961B5EEB305BD5CF5BEDC0B3E021A33537CD724EE049A4609737C508FFAA in tequila-0004 testnet. Link to finder

As far as I found, the pubkey of the message is this transaction is null and this makes the StdTx.fromData() broken.

The library version I used is v1.8.10

{
  "height": "5847659",
  "txhash": "FA82961B5EEB305BD5CF5BEDC0B3E021A33537CD724EE049A4609737C508FFAA",
  "raw_log": "[{\"msg_index\":0,\"log\":\"\",\"events\":[{\"type\":\"message\",\"attributes\":[{\"key\":\"action\",\"value\":\"send\"},{\"key\":\"sender\",\"value\":\"terra1qvvcyuzufug9ez7u0emkxxjvjetvfncjdjxk9s\"},{\"key\":\"module\",\"value\":\"bank\"}]},{\"type\":\"transfer\",\"attributes\":[{\"key\":\"recipient\",\"value\":\"terra1974a32vkgh9x8gufwcpm7yt4gqw2kdadwmrf0j\"},{\"key\":\"sender\",\"value\":\"terra1qvvcyuzufug9ez7u0emkxxjvjetvfncjdjxk9s\"},{\"key\":\"amount\",\"value\":\"1000000uluna\"}]}]}]",
  "logs": [
    {
      "msg_index": 0,
      "log": "",
      "events": [
        {
          "type": "message",
          "attributes": [
            { "key": "action", "value": "send" },
            {
              "key": "sender",
              "value": "terra1qvvcyuzufug9ez7u0emkxxjvjetvfncjdjxk9s"
            },
            { "key": "module", "value": "bank" }
          ]
        },
        {
          "type": "transfer",
          "attributes": [
            {
              "key": "recipient",
              "value": "terra1974a32vkgh9x8gufwcpm7yt4gqw2kdadwmrf0j"
            },
            {
              "key": "sender",
              "value": "terra1qvvcyuzufug9ez7u0emkxxjvjetvfncjdjxk9s"
            },
            { "key": "amount", "value": "1000000uluna" }
          ]
        }
      ]
    }
  ],
  "gas_wanted": "71978",
  "gas_used": "64757",
  "tx": {
    "type": "core/StdTx",
    "value": {
      "msg": [
        {
          "type": "bank/MsgSend",
          "value": {
            "from_address": "terra1qvvcyuzufug9ez7u0emkxxjvjetvfncjdjxk9s",
            "to_address": "terra1974a32vkgh9x8gufwcpm7yt4gqw2kdadwmrf0j",
            "amount": [{ "denom": "uluna", "amount": "1000000" }]
          }
        }
      ],
      "fee": {
        "amount": [{ "denom": "uluna", "amount": "10797" }],
        "gas": "71978"
      },
      "signatures": [
        {
          "pub_key": null,
          "signature": "qOq5OTkXlWgvmq92iK6osdodtq42SSX3IhwdtnCG4sAH5JT5Nu2PRD9RWln4Gvl7MmZcYv8rFu5AqW1pPMkN9w=="
        }
      ],
      "memo": "test memo"
    }
  },
  "timestamp": "2021-09-14T16:32:26Z"
}

Cannot submit transaction generated by StdSignMsg but CreateAndSignTx works fine

Hi,
I was trying to implement Terra for an offline wallet.
I used the following code to generate a signed transaction object:

  public async signOfflineTransaction(
    toAddress: string,
    ticker: string,
    value: number,
    gas: number,
    sequenceNumber: number,
    accountNumber: number,
    memo?: string,
  ): Promise<StdTx> {
    const amount = {
      uluna: 10000,
    };

    const send = new MsgSend(
      'terra13qz3dqq9g5wpqqkf7ca5yxk3jsgz94a4rrrpak',
      'terra17ymz26ky4jfzmw6uedu0g397hljr70a7k9ne4v',
      amount,
    );

    const fee = new StdFee(1000, { uluna: 10000 });

    const unsignedTx = new StdSignMsg(
      'tequila-0004',
      10,
      1720,
      fee,
      [send],
      memo,
    );

    const signedTx = await this.wallet.key.signTx(unsignedTx);
    return signedTx;
  }

When I run this program I get the following result:
SIGNED OBJECT A

{
  "type": "core/StdTx",
  "value": {
    "fee": {
      "amount": [
        {
          "amount": "10000",
          "denom": "uluna"
        }
      ],
      "gas": "1000"
    },
    "memo": "",
    "msg": [
      {
        "type": "bank/MsgSend",
        "value": {
          "amount": [
            {
              "amount": "10000",
              "denom": "uluna"
            }
          ],
          "from_address": "terra13qz3dqq9g5wpqqkf7ca5yxk3jsgz94a4rrrpak",
          "to_address": "terra17ymz26ky4jfzmw6uedu0g397hljr70a7k9ne4v"
        }
      }
    ],
    "signatures": [
      {
        "pub_key": {
          "type": "tendermint/PubKeySecp256k1",
          "value": "AxkYYhGJ5JoGd+GXzSCkdiur4/CCFJ26UluiQxshxve3"
        },
        "signature": "2foLuO919vLrOTMzCImWM10HylFPJg4XeLB+6jextXduUyWy6ATuRfM6gb9rf0ssHQZCxXYYcNJ9quJrWEUt9g=="
      }
    ]
  }
}

This looks fine, as I generated another transaction with the exact same wallet, but this time with CreateAndSignTx (cannot use this as it requires a call for sequence number and account number which is not possible for my offline wallet).
The CreateAndSignTx looks something like this:
(SIGNED OBJECT B)

{
  "type": "core/StdTx",
  "value": {
    "fee": {
      "amount": [
        {
          "amount": "91418000",
          "denom": "uluna"
        }
      ],
      "gas": "91418"
    },
    "memo": "",
    "msg": [
      {
        "type": "bank/MsgSend",
        "value": {
          "amount": [
            {
              "amount": "10000",
              "denom": "uluna"
            }
          ],
          "from_address": "terra13qz3dqq9g5wpqqkf7ca5yxk3jsgz94a4rrrpak",
          "to_address": "terra17ymz26ky4jfzmw6uedu0g397hljr70a7k9ne4v"
        }
      }
    ],
    "signatures": [
      {
        "pub_key": {
          "type": "tendermint/PubKeySecp256k1",
          "value": "AxkYYhGJ5JoGd+GXzSCkdiur4/CCFJ26UluiQxshxve3"
        },
        "signature": "lhy7nSlV9jJ+kCdxu/CA5Zcf+R+9sHMIpEkwy4ZH5Q8Vlu1boRbgObcR+cw3RO80rpiGNM77C0FAcPlJW9Z+3g=="
      }
    ]
  }
}

Submitting this signed object B was a success: 005F5DC78379EA293F6A687117699F896070D735B82F38A2AFC5C0422254E1ED you can verify it on the explorer.

But whenever I try to submit signed object A, I get an error like:

{ height: 0,
  txhash:
   'BAC34EEA8472591F787E69DCC9A082BCDECFDDAD602B05DE714951BB7D4BBD0D',
  raw_log:
   'out of gas: out of gas in location: ReadPerByte; gasWanted: 1000, gasUsed: 1054',
  gas_wanted: 1000,
  gas_used: 1054,
  code: 11,
  codespace: 'sdk' }

I tried increasing the gas, but then it requires even more gas. For example if I write, 6000 it will give me an error like:

{ height: 0,
  txhash:
   '1C07F3AD2FB532ABDAB12767D13E61630E1DDBBBC07F3FCF3BCD015FA22083A8',
  raw_log:
   'out of gas: out of gas in location: ReadFlat; gasWanted: 6000, gasUsed: 6111',
  gas_wanted: 6000,
  gas_used: 6111,
  code: 11,
  codespace: 'sdk' }

and so on and so forth (3000 gas requires -> 3069).
Not completely sure why this is not working, given I tried to follow what is there in the documentations.
If there is something missing, is there a way to implement Terra for offline wallets? Do I need to make some changes in how I am feeding data into StdSignMsg (since I see the gas and value being sent is different to CreateAndSignTx method).

[ISSUE] Jest testing: Crypto module not found

Reproduction steps:

  1. Boilerplate new CRA project and check basic rendering test

npx create-react-app dep-check --template typescript
cd dep-check
npm i
npm run test

All works fine.

  1. Add terra.js dependency

npm i --save @terra-money/terra.js

  1. Modify App.tsx with first example from terra.js Readme
`import React, {useState} from 'react';
import './App.css';
import { LCDClient, Coin } from '@terra-money/terra.js';

const terra = new LCDClient({
  URL: 'https://tequila-lcd.terra.dev',
  chainID: 'tequila-0004',
});
const App = () => {
  const [coins, setCoins] = useState('');
  const offerCoin = new Coin('uusd', '1000000');
  terra.market.swapRate(offerCoin, 'ukrw').then(c => {
    setCoins(`${offerCoin.toString()} can be swapped for ${c.toString()}`);
  });
  return (
      <div>
        {coins}
      </div>
  );
};

export default App;`
  1. Run again basic test:

npm run test

It fails:

 FAIL  src/App.test.tsx
  ● Test suite failed to run

    Crypto module not found
    
      at node_modules/jscrypto/SHA256.js:1:5962
      at Object.9054 (node_modules/jscrypto/SHA256.js:1:6223)
      at r (node_modules/jscrypto/SHA256.js:1:6324)
      at Object.3354 (node_modules/jscrypto/SHA256.js:1:491)
      at r (node_modules/jscrypto/SHA256.js:1:6324)
      at Object.7211 (node_modules/jscrypto/SHA256.js:1:2275)
      at r (node_modules/jscrypto/SHA256.js:1:6324)
      at Object.1868 (node_modules/jscrypto/SHA256.js:1:3145)
      at r (node_modules/jscrypto/SHA256.js:1:6324)
      at node_modules/jscrypto/SHA256.js:1:6935
      at node_modules/jscrypto/SHA256.js:1:8672
      at node_modules/jscrypto/SHA256.js:1:8677
      at node_modules/jscrypto/SHA256.js:1:173
      at Object.<anonymous> (node_modules/jscrypto/SHA256.js:1:366)
      at Object.<anonymous> (node_modules/@terra-money/terra.js/src/core/oracle/msgs/MsgExchangeRateVote.ts:1:1)
      at Object.<anonymous> (node_modules/@terra-money/terra.js/src/core/oracle/msgs/index.ts:9:1)
      at Object.<anonymous> (node_modules/@terra-money/terra.js/src/core/Msg.ts:17:1)
      at Object.<anonymous> (node_modules/@terra-money/terra.js/src/core/index.ts:5:1)
      at Object.<anonymous> (node_modules/@terra-money/terra.js/src/index.ts:1:1)
      at Object.<anonymous> (src/App.tsx:4:1)
      at Object.<anonymous> (src/App.test.tsx:3:1)

Is there anyway to disable that module on test level or something? I know that you introduced jscrypto instead of crypto-js, but it seems like this package is a little bit problematic as well.

Will appreciate any possible solutions.

Add new mAssets to DEFAULT_MIRROR_OPTIONS

In mirror.js, only the following mAssets pre-defined in default options

{
    ...,
    assets: {
        MIR: {
            symbol: 'MIR',
            name: 'Mirror',
            token: 'terra15gwkyepfc6xgca5t5zefzwy42uts8l2m4g40k6',
            pair: 'terra1amv303y8kzxuegvurh0gug2xe9wkgj65enq2ux',
            lpToken: 'terra17gjf2zehfvnyjtdgua9p9ygquk6gukxe7ucgwh'
        },
        mAAPL: {
            symbol: 'mAAPL',
            name: 'Apple',
            token: 'terra1vxtwu4ehgzz77mnfwrntyrmgl64qjs75mpwqaz',
            pair: 'terra1774f8rwx76k7ruy0gqnzq25wh7lmd72eg6eqp5',
            lpToken: 'terra122asauhmv083p02rhgyp7jn7kmjjm4ksexjnks'
        },
        mGOOGL: {
            symbol: 'mGOOGL',
            name: 'Google',
            token: 'terra1h8arz2k547uvmpxctuwush3jzc8fun4s96qgwt',
            pair: 'terra1u56eamzkwzpm696hae4kl92jm6xxztar9uhkea',
            lpToken: 'terra1falkl6jy4087h4z567y2l59defm9acmwcs70ts'
        },
        mTSLA: {
            symbol: 'mTSLA',
            name: 'Tesla',
            token: 'terra14y5affaarufk3uscy2vr6pe6w6zqf2wpjzn5sh',
            pair: 'terra1pdxyk2gkykaraynmrgjfq2uu7r9pf5v8x7k4xk',
            lpToken: 'terra1ygazp9w7tx64rkx5wmevszu38y5cpg6h3fk86e'
        },
        mNFLX: {
            symbol: 'mNFLX',
            name: 'Netflix',
            token: 'terra1jsxngqasf2zynj5kyh0tgq9mj3zksa5gk35j4k',
            pair: 'terra1yppvuda72pvmxd727knemvzsuergtslj486rdq',
            lpToken: 'terra1mwu3cqzvhygqg7vrsa6kfstgg9d6yzkgs6yy3t'
        },
        mQQQ: {
            symbol: 'mQQQ',
            name: 'Invesco QQQ Trust',
            token: 'terra1csk6tc7pdmpr782w527hwhez6gfv632tyf72cp',
            pair: 'terra1dkc8075nv34k2fu6xn6wcgrqlewup2qtkr4ymu',
            lpToken: 'terra16j09nh806vaql0wujw8ktmvdj7ph8h09ltjs2r'
        },
        mTWTR: {
            symbol: 'mTWTR',
            name: 'Twitter',
            token: 'terra1cc3enj9qgchlrj34cnzhwuclc4vl2z3jl7tkqg',
            pair: 'terra1ea9js3y4l7vy0h46k4e5r5ykkk08zc3fx7v4t8',
            lpToken: 'terra1fc5a5gsxatjey9syq93c2n3xq90n06t60nkj6l'
        },
        mMSFT: {
            symbol: 'mMSFT',
            name: 'Microsfot Corporation',
            token: 'terra1227ppwxxj3jxz8cfgq00jgnxqcny7ryenvkwj6',
            pair: 'terra10ypv4vq67ns54t5ur3krkx37th7j58paev0qhd',
            lpToken: 'terra14uaqudeylx6tegamqmygh85lfq8qg2jmg7uucc'
        },
        mAMZN: {
            symbol: 'mAMZN',
            name: 'Amazon.com',
            token: 'terra165nd2qmrtszehcfrntlplzern7zl4ahtlhd5t2',
            pair: 'terra1vkvmvnmex90wanque26mjvay2mdtf0rz57fm6d',
            lpToken: 'terra1q7m2qsj3nzlz5ng25z5q5w5qcqldclfe3ljup9'
        },
        mBABA: {
            symbol: 'mBABA',
            name: 'Alibaba Group Holdings Ltd ADR',
            token: 'terra1w7zgkcyt7y4zpct9dw8mw362ywvdlydnum2awa',
            pair: 'terra1afdz4l9vsqddwmjqxmel99atu4rwscpfjm4yfp',
            lpToken: 'terra1stfeev27wdf7er2uja34gsmrv58yv397dlxmyn'
        },
        mIAU: {
            symbol: 'mIAU',
            name: 'iShares Gold Trust',
            token: 'terra15hp9pr8y4qsvqvxf3m4xeptlk7l8h60634gqec',
            pair: 'terra1q2cg4sauyedt8syvarc8hcajw6u94ah40yp342',
            lpToken: 'terra1jl4vkz3fllvj6fchnj2trrm9argtqxq6335ews'
        },
        mSLV: {
            symbol: 'mSLV',
            name: 'iShares Silver Trust',
            token: 'terra1kscs6uhrqwy6rx5kuw5lwpuqvm3t6j2d6uf2lp',
            pair: 'terra1f6d9mhrsl5t6yxqnr4rgfusjlt3gfwxdveeyuy',
            lpToken: 'terra178cf7xf4r9d3z03tj3pftewmhx0x2p77s0k6yh'
        },
        mUSO: {
            symbol: 'mUSO',
            name: 'United States Oil Fund, LP',
            token: 'terra1lvmx8fsagy70tv0fhmfzdw9h6s3sy4prz38ugf',
            pair: 'terra1zey9knmvs2frfrjnf4cfv4prc4ts3mrsefstrj',
            lpToken: 'terra1utf3tm35qk6fkft7ltcnscwml737vfz7xghwn5'
        },
        mVIXY: {
            symbol: 'mVIXY',
            name: 'ProShares VIX',
            token: 'terra1zp3a6q6q4953cz376906g5qfmxnlg77hx3te45',
            pair: 'terra1yngadscckdtd68nzw5r5va36jccjmmasm7klpp',
            lpToken: 'terra1cmrl4txa7cwd7cygpp4yzu7xu8g7c772els2y8'
        }
    }
};```

12 words mnemonic

any wallet out there using a 12 words mnemonic?
Does MnemonicKey accepts 12 words?

signing MsgExecuteContract failing

Hi!

I detected an error while signing transaction. Here is sample code to ilustrate the issue:

  const wallet = terra.wallet(mk);
  const singInKYCVault = new MsgExecuteContract(
    wallet.key.accAddress,
    config.terra.kycVaultContract,
    {
      "register_address":
        {
            "address": "terra1x46rqay4d3cssq8gxxvqz8xt6nwlz4td20k38v"
        }
    }
  )
  

  const signedTxs2 = await wallet
    .createAndSignTx({
      msgs: [singInKYCVault],
    });

While running wallet.createAndSignTx i get this error: 'json: cannot unmarshal object into Go value of type string'.
Testing on version 2.0.5
For exapmle the same code is working properly on version 1.8.5

Future of this SDK

Hey there! 👋

It is very hard (and nearly impossible in crypto-land) to write an isomorphic library.

I plan to rewrite some of the dependencies of the SDK in a better isomorphic JavaScript, and I was wondering how to make it easier to work with new frontend-building tools with this SDK.

As you may know, a bunch of dependencies is node-dependent. So the builder polyfill them during the build, but this is not working well with all bundler's new version (Webpack 5, Vite, Rollup, ...).

Instead of creating an isomorphic library, I thought, what do you think about creating three libraries?

  • @terra-money/core => Common isomorphic part of the SDK
  • @terra-money/sdk => Node part of the SDK
  • @terra-money/client => JavaScript (Client) part of the SDK

People would choose to use the Node or the Browser version of the SDK, depending on their runtime.

This will not be easy to achieve well.
I have opened this issue to start discussing doing something similar in the "near" future.

Is there a way to validate terra account address?

Is there a way to validate terra account address, for example:

isAccAddress("terra15h6vd5f0wqps26zjlwrc6chah08ryu4hzzdwhc") // true
isAccAddress("helloworld") // false
isAccAddress("terravaloperasdflmkwmewlkemrwoidoisdfsdoifjwoie") // false

Example send tx with memo with Extension please

Hi! Please add to this wiki page a working example or jsFiddle for sending simple (bank module) transaction with Terra Extension and in-browser package.

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

For example with this data:

to: terra123kjh21j3hk21
amount: 10000uusd
memo: Hello!

I've been trying to do this all day, unsuccessfully

[Question] Pagination for Wasm ContractQuery

Hello. I am using:

terra.wasm.contractQuery(contractAddress, {all_accounts: {limit: LIMIT, start_after: lastAddress}})

For querying accounts that have particular token. And I have 2 questions regarding it.

  1. Pagination. Is there a way to get the full count of addresses or number of pages with given limit?

  2. If there is no way to get information from point 1. How are new addresses added to that list? As first items or as last items?

WebSocketClient does not connect

After updating to version 2.0.14 I cannot connect via WebSocketClient.

I checked the cause of the problem:

  • the WebSocketClient start() function is not called. Previously, it was called at the end of subscribe()
    So this should be corrected, or the start() function should be made public.

extension.isAvailable returns false after refreshing the page

I have a .ts script on my website. When i call the getters:

extension.isAvailable
extension.isAvailable

I correctly get values

true
true

But after refreshing the page I get values

false
false

I have to hard refresh the page to again get correct values.
I'm using terra.js 1.6.0

query and Binary data?

(still getting my feet wet - apologies if I missed something)

  1. The CosmWasm docs and examples show that it's allowed for a contract to return Binary data. However, I don't see this when I look in the TxLogs ... is there a different way of getting this data via Terra.JS? I do see attributes...

  2. Similarly, the CosmWasm docs show a separate ability for Query messages. I don't see this in Terra.JS

Missing message type MsgGrantAllowance

Version: 2.0.14
ChainId: columbus-5
Hello, I'm using lcdClient.tx.txInfo to get TxInfo of 169239F6BA081739049398814C4AEA9EF00971F444C26601094F1C3DD16D43B5 but MsgGrantAllowance is not available. This lead to "unable to parse msg: [object Object] unrecognized" exception when trying to parse transaction message from data.
Please tell me which version of this library I should use for columbus-5?

Failed to parse param change proposal

const txResult = await this.LCDClient.tx.search({
        'tx.height': targetHeight,
        page,
        limit,
});

method failed to parse txs which is tx.height= 1150551.

I guess it is due to param change proposal.

Unable to load terra.js in the browser

Uncaught TypeError: Cannot read property 'WordArray' of undefined
at sha256.js:20
at Object.2153 (sha256.js:16)
at r (bootstrap:18)
at Object.6152 (MsgExchangeRateVote.ts:6)
at r (bootstrap:18)
at Object.8470 (index.ts:9)
at r (bootstrap:18)
at Object.7094 (Msg.ts:17)
at r (bootstrap:18)
at Object.6676 (index.ts:5)

Steps to reproduce: Include the following in your browser

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

`exchangeRate` does not return prices in the requested denomination

The exchangeRate docstring says:

/**
* Gets the Oracle module's currently registered exchange rate for the specific denomination.
* @param denom denomination in which to get the exchange rate of LUNA
*/
public async exchangeRate(denom: Denom): Promise<Coin | undefined> {

But terra.oracle.exchangeRate("uusd") returns 43.114990898875845, i.e. the price in USD, not uusd

Execute wasm contract failed when using extension

When I try to executing contract using Extension, I'm got an error: "rpc error: code = InvalidArgument desc = failed to execute message; message index: 0: Error parsing into type contract::msg::HandleMsg: unknown variant eyJhZGRfcGxheWVyIjp7fX0=, expected add_user: execute wasm contract failed: invalid request".
What's the correct way of using the extension?
Code:
`
this.client = new LocalTerra();
this.extension = new Extension();
this.extension.connect();
this.extension.on("onConnect", (w: Wallet) => {
this.wallet = w;
});

const execute = new MsgExecuteContract(
this.wallet.address, // sender
"terra1tndcaqxkpc5ce9qee5ggqf430mr2z3pefe5wj6", // contract account address
{ add_user: {} }, // handle msg
{ uluna: 100000} // coins
);

this.extension.post({
msgs: [execute],
});

this.extension.once("onPost", async (data: any) => {
console.log("post", data);
});
`

window.isTerraExtensionAvailable is true but ext do not open

I'm trying to inject a wallet in terra dapps and i have debugged the wallet provider from where i check is looking for prop in window which is isTerraExtensionAvailable, I have mine setted to true but still my wallet is not recognized from the dapps any suggestions on that? Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.