Giter Club home page Giter Club logo

cosmos-client-ts's Introduction

@cosmos-client/core

REST API client for Cosmos SDK blockchain

Install

npm install @cosmos-client/core

Caution

The package name cosmos-client is deprecated. Please use @cosmos-client/core alternatively.

Discord community

Invitation link

Plugin modules

Examples

import cosmosclient from '@cosmos-client/core';
import Long from 'long';

describe('bank', () => {
  it('send', async () => {
    expect.hasAssertions();

    const sdk = new cosmosclient.CosmosSDK('http://localhost:1317', 'testchain');

    const privKey = new cosmosclient.proto.cosmos.crypto.secp256k1.PrivKey({
      key: await cosmosclient.generatePrivKeyFromMnemonic('joke door law post fragile cruel torch silver siren mechanic flush surround'),
    });
    const pubKey = privKey.pubKey();
    const address = cosmosclient.AccAddress.fromPublicKey(pubKey);

    expect(address.toString()).toStrictEqual('cosmos14ynfqqa6j5k3kcqm2ymf3l66d9x07ysxgnvdyx');

    const fromAddress = address;
    const toAddress = address;

    // get account info
    const account = await cosmosclient.rest.auth
      .account(sdk, fromAddress)
      .then((res) => cosmosclient.codec.protoJSONToInstance(cosmosclient.codec.castProtoJSONOfProtoAny(res.data.account)))
      .catch((_) => undefined);

    if (!(account instanceof cosmosclient.proto.cosmos.auth.v1beta1.BaseAccount)) {
      console.log(account);
      return;
    }

    // build tx
    const msgSend = new cosmosclient.proto.cosmos.bank.v1beta1.MsgSend({
      from_address: fromAddress.toString(),
      to_address: toAddress.toString(),
      amount: [{ denom: 'token', amount: '1' }],
    });

    const txBody = new cosmosclient.proto.cosmos.tx.v1beta1.TxBody({
      messages: [cosmosclient.codec.instanceToProtoAny(msgSend)],
    });
    const authInfo = new cosmosclient.proto.cosmos.tx.v1beta1.AuthInfo({
      signer_infos: [
        {
          public_key: cosmosclient.codec.instanceToProtoAny(pubKey),
          mode_info: {
            single: {
              mode: cosmosclient.proto.cosmos.tx.signing.v1beta1.SignMode.SIGN_MODE_DIRECT,
            },
          },
          sequence: account.sequence,
        },
      ],
      fee: {
        gas_limit: Long.fromString('200000'),
      },
    });

    // sign
    const txBuilder = new cosmosclient.TxBuilder(sdk, txBody, authInfo);
    const signDocBytes = txBuilder.signDocBytes(account.account_number);
    txBuilder.addSignature(privKey.sign(signDocBytes));

    // broadcast
    const res = await cosmosclient.rest.tx.broadcastTx(sdk, {
      tx_bytes: txBuilder.txBytes(),
      mode: rest.tx.BroadcastTxMode.Block,
    });
    console.log(res);

    expect(res.data.tx_response?.raw_log?.match('failed')).toBeFalsy();
  });
});

For frontend developers

In something like polyfill.ts in Angular (of course something like that in other frontend frameworks), don't forget to input this statement. If there isn't this statement, the outcome of serializing JSON of instances including Long type field will be wrong.

import Long from 'long';
import * as $protobuf from 'protobufjs/minimal';

$protobuf.util.Long = Long;
$protobuf.configure();

For library developlers

Install Protocol Buffer Compiler

sudo apt -y install protobuf-compiler

or

brew install protobuf 

Use starport to test.

The first digit major version and the second digit minor version should match Cosmos SDK. The third digit patch version can be independently incremented.

for proto.d.ts error

Add the following line to the end of the proto.d.ts file and replace tendermint with global_tendermint at the error points.

import global_tendermint = tendermint;

cosmos-client-ts's People

Contributors

bcts369 avatar dependabot[bot] avatar jeijeijei777 avatar jonnyburger avatar keppel avatar kimurayu45z avatar mappum avatar mkxultra avatar senna46 avatar taro04 avatar uuyu-g avatar veado avatar yasunorimatsuoka avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

cosmos-client-ts's Issues

Is `sr25519` library still required?

We are trying to run this library in React Native and struggle because of the sr25519 library.

We see that it's in the package.json but not imported anywhyere. Can we send a pull request to remove it? Or is it needed in way still?

unable to resolve type URL : tx parse error

Hi!
I have some problem with broadcasting tx.
When I broadcasted Tx, I got Error "Broadcasting transaction failed with code2 (codespace : sdk) Log: invalid length; proto: invalid field number : tx parse error".
What is the cause of this and do you have any proper way to solve this?

// broadcast
const res = await cosmosclient.rest.tx.broadcastTx(sdk, {
  tx_bytes: txBuilder.txBytes(),
  mode: rest.tx.BroadcastTxMode.Block,
});
console.log(res);

npm CD

【手持ち無沙汰なとき用タスク・優先順位低】

やること1

githubでreleaseしたら自動でnpmにpublishさせたい。

やること2

パッケージバージョンを、cosmos sdkのバージョンにあわせたい(0.38.x)
1桁目メジャーバージョンと2桁目マイナーバージョンは、sdkにあわせる。
3桁目fixバージョンは、独自にインクリメントしていっておk.

やること3

1桁目メジャーバージョンと2桁目マイナーバージョンは、sdkにあわせる。
3桁目fixバージョンは、独自にインクリメントしていっておk.
というルールを、READMEのfor library developersに書く。

How to get Linear point from AccAddress

Hello guys, how I can get the linear point (aka PubKey.key) to instantiate a PubKey object using: proto.cosmos.crypto.secp256k1.PubKey
Also, what is the best approach to use this package in other cosmos-based blockchains?

Thank you

support custom HTTP headers on requests

we have a need to support custom HTTP headers on requests to our endpoints (to control traffic). It does not look like we are able to do that with this library. can you confirm this is the case? and if so, would it be possible for you to make a change to support this?

Failed broadcast tx signed by ledger

Package: @cosmos-client/core V0.45.1

Steps

  1. Connect ledger and get pubKey
  2. Sign tx using Ledger and get signature
  3. create txBuilder and addSignature
  4. broadcast tx fails with Error broadcasting: panic message redacted to hide potentially sensitive system info: panic

Question

In the cosmos-client v0.45.1, is there any way to broadcast tx using signature signed by 3rd party (ledger or Trustwallet) ?

In the cosmos-client v0.39, I was able to broadcast tx using stdTX.

      const txObj = {
        msg: unsignedMsgs,
        fee,
        memo,
        signatures,
      }

      // broadcast raw tx
      const stdTx = StdTx.fromJSON(txObj)

      const { data }: any = await auth.txsPost(
        cosmosSDKClient.sdk,
        stdTx,
        'block',
      )

Current implementation with broadcast fails

// get tx signing msg
      const rawSendTx: LedgerTypes.THORChainSendTx = orderJSON({
        account_number: accountNumber,
        chain_id: this.chainIds[this.client.getNetwork()],
        fee,
        memo,
        msgs: [msg],
        sequence,
      })

      // request tx signing to walletconnect
      const signatures = await this.ledgerClient.signTransaction(
        JSON.stringify(rawSendTx),
      )

      const enc = new TextEncoder()
      const pubKey = new proto.cosmos.crypto.secp256k1.PubKey({
        key: enc.encode(signatures[0].pub_key.value),
      })
      const { signature } = signatures[0]

      cosmosSDKClient.setPrefix()
      registerSendCodecs()

      const msgSend = new proto.cosmos.bank.v1beta1.MsgSend({
        from_address,
        to_address,
        amount: [
          {
            amount,
            denom,
          },
        ],
      })

      const txBody = new proto.cosmos.tx.v1beta1.TxBody({
        messages: [cosmosclient.codec.packAny(msgSend)],
        memo,
      })

      const authInfo = new proto.cosmos.tx.v1beta1.AuthInfo({
        signer_infos: [
          {
            public_key: cosmosclient.codec.packAny(pubKey),
            mode_info: {
              single: {
                mode: proto.cosmos.tx.signing.v1beta1.SignMode.SIGN_MODE_DIRECT,
              },
            },
            sequence,
          },
        ],
        fee: DEFAULT_FEE,
      })

      // txBuilder
      const txBuilder = new cosmosclient.TxBuilder(
        cosmosSDKClient.sdk,
        txBody,
        authInfo,
      )

      const signatureUint8Array = enc.encode(signature)
      txBuilder.addSignature(signatureUint8Array)


      // broadcast
      const res = await rest.tx.broadcastTx(cosmosSDKClient.sdk, {
        tx_bytes: txBuilder.txBytes(),
        mode: rest.tx.BroadcastTxMode.Sync,
      })

Thanks in advance.

Docker issue

Apologies if this is outside the scope of this repo, but I encounter typescript issue when building with Docker. I tried versions 0.45.3 through 0.45.9 of @cosmos-client/core.

Docker file looks like this:

FROM node:16-alpine
WORKDIR /app

COPY package.json ./
# RUN npm install @cosmos-client/core
RUN yarn

COPY tsconfig.json ./
COPY src/. src/.
RUN yarn build

ENV PORT='9000'
EXPOSE 9000

COPY .env ./
CMD ["node", "./build/main.js"]

and I get these errors on Mac and Google Cloud Run, but only when transpiling in Docker:

 => ERROR [7/8] RUN yarn build                                                                                                                                                                                              3.0s
------                                                                                                                                                                                                                           
 > [7/8] RUN yarn build:                                                                                                                                                                                                         
#11 0.262 yarn run v1.22.19                                                                                                                                                                                                      
#11 0.282 $ npx tsc
#11 2.912 src/wallets/myFile.ts(48,58): error TS2339: Property 'unpackCosmosAny' does not exist on type 'typeof import("/app/node_modules/@cosmos-client/core/cjs/types/codec/module")'.
#11 2.913 src/wallets/myFile.ts(120,33): error TS2339: Property 'Long' does not exist on type 'typeof import("/app/node_modules/@cosmos-client/core/cjs/module")'.
#11 2.913 src/wallets/myFile.ts(125,37): error TS2339: Property 'packAny' does not exist on type 'typeof import("/app/node_modules/@cosmos-client/core/cjs/types/codec/module")'.
#11 2.913 src/wallets/myFile.ts(127,53): error TS2339: Property 'Long' does not exist on type 'typeof import("/app/node_modules/@cosmos-client/core/cjs/module")'.
#11 2.913 src/wallets/myFile.ts(149,34): error TS2339: Property 'packAny' does not exist on type 'typeof import("/app/node_modules/@cosmos-client/core/cjs/types/codec/module")'.
#11 2.913 src/wallets/myFile.ts(166,26): error TS2694: Namespace '"/app/node_modules/@cosmos-client/core/cjs/module"' has no exported member 'Long'.
#11 2.913 src/wallets/myFile.ts(167,27): error TS2694: Namespace '"/app/node_modules/@cosmos-client/core/cjs/module"' has no exported member 'Long'.

Using Node 16 and TS 4.5.2.

Docker version

Client:
 Cloud integration: v1.0.22
 Version:           20.10.12
 API version:       1.41
 Go version:        go1.16.12
 Git commit:        e91ed57
 Built:             Mon Dec 13 11:46:56 2021
 OS/Arch:           darwin/arm64
 Context:           default
 Experimental:      true

Server: Docker Desktop 4.5.0 (74594)
 Engine:
  Version:          20.10.12
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.16.12
  Git commit:       459d0df
  Built:            Mon Dec 13 11:43:07 2021
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.4.12
  GitCommit:        7b11cfaabd73bb80907dd23182b9347b4245eb5d
 runc:
  Version:          1.0.2
  GitCommit:        v1.0.2-0-g52b36a2
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

Transpiling the project outside docker works like a charm. If I found a solution, I will post it here.

trying to upgrade from 0.39.4 -> 04.14

hi having a hard time trying to upgrade from 0.39->0.42.
it looks like StdTx has been entirely removed from your lib

async transfer({
    privkey,
    from,
    to,
    amount,
    asset,
    memo = '',
    fee = {
      amount: [],
      gas: '200000',
    },
  }: TransferParams): Promise<BroadcastTxCommitResult> {
    this.setPrefix()

    const msg: Msg = [
      MsgSend.fromJSON({
        from_address: from,
        to_address: to,
        amount: [
          {
            amount: amount.toString(),
            denom: asset,
          },
        ],
      }),
    ]
    const signatures: StdTxSignature[] = []

    const unsignedStdTx = StdTx.fromJSON({
      msg,
      fee,
      signatures,
      memo,
    })

    return this.signAndBroadcast(unsignedStdTx, privkey, AccAddress.fromBech32(from))
  }

  async signAndBroadcast(unsignedStdTx: StdTx, privkey: PrivKey, signer: AccAddress): Promise<BroadcastTxCommitResult> {
    this.setPrefix()

    let account: BaseAccount = (await auth.accountsAddressGet(this.sdk, signer)).data.result
    if (account.account_number === undefined) {
      account = BaseAccount.fromJSON((account as BaseAccountResponse).value)
    }

    const signedStdTx = auth.signStdTx(
      this.sdk,
      privkey,
      unsignedStdTx,
      account.account_number.toString(),
      account.sequence.toString(),
    )

    return (await auth.txsPost(this.sdk, signedStdTx, 'block')).data
  }

it looks like the txPostist still around, but not sure how to sign the message anymore

const api: TransactionsApi = new TransactionsApi()
    const response = await api.txsPost({
      tx: {
        msg: ['string'],
        fee: {
          gas: 'string',
          amount: [
            {
              denom: 'stake',
              amount: '50',
            },
          ],
        },
        memo: 'string',
        signature: {
          signature: 'MEUCIQD02fsDPra8MtbRsyB1w7bqTM55Wu138zQbFcWx4+CFyAIge5WNPfKIuvzBZ69MyqHsqD8S1IwiEp+iUb6VSdtlpgY=',
          pub_key: {
            type: 'tendermint/PubKeySecp256k1',
            value: 'Avz04VhtKJh8ACCVzlI8aTosGy0ikFXKIVHQ3jKMrosH',
          },
          account_number: '0',
          sequence: '0',
        },
      },
      mode: 'block',
    })

The Bug of google.protobuf.Timestamp (MsgPlaceBid) when simulating Tx

When simulating MsgPlaceBid, the backend return 400 error.
A marshal problem when transforming google.protobuf.Timestamp in Msg.

  • This problem only occurs with MsgPlaceBid.
  • This problem does not occur when sending MsgPlaceBid through Keplr.

____________________________2023-02-14_161314_360

{
  "code": 3,
  "message": "can't unmarshal Any nested proto *types.MsgPlaceBid: json: cannot unmarshal object into Go value of type string",
  "details": [
  ]
}

sr25519

シュノア署名実装。

Where is openapi.yaml source file ?

Can any one tell me where is openapi.yaml source file ? In case I want to modify it to re-generate src folder's code, Thank you very much

npmへのpublish

npm run build
npm run publish

これでpublishできますが、npm run buildにて同時にrustコンパイルできるようにしたいです。
package.json編集必要。
やっぱこれも任せたいです。

Expected Private

I have a problem with PrivKeySecp256k1()

import { CosmosSDK, AccAddress, PrivKeySecp256k1 } from "cosmos-client";
const privKey = new PrivKeySecp256k1(new Buffer("my mneminic"));

ERROR: Expected Private
    at Object.pointFromScalar
    at new PrivKeySecp256k1

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.