cosmos-client / cosmos-client-ts

Apache License 2.0
36 stars 17 forks source link

trying to upgrade from 0.39.4 -> 04.14 #48

Open mikewyszinski opened 3 years ago

mikewyszinski commented 3 years ago

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',
    })
kimurayu45z commented 3 years ago

Hi Many breaking changes are due to breaking changes of cosmos-sdk.

How to announce transaction with cosmos-client v0.42 is written in README.

https://github.com/cosmos-client/cosmos-client-ts/blob/main/README.md

Please refer to it.

import { cosmosclient, rest, proto } from 'cosmos-client';

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

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

    const privKey = new 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 rest.cosmos.auth
      .account(sdk, fromAddress)
      .then((res) => res.data.account && cosmosclient.codec.unpackCosmosAny(res.data.account))
      .catch((_) => undefined);

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

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

    const txBody = new proto.cosmos.tx.v1beta1.TxBody({
      messages: [cosmosclient.codec.packAny(msgSend)],
    });
    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: account.sequence,
        },
      ],
      fee: {
        gas_limit: cosmosclient.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 rest.cosmos.tx.broadcastTx(sdk, {
      tx_bytes: txBuilder.txBytes(),
      mode: rest.cosmos.tx.BroadcastTxMode.Block,
    });
    console.log(res);

    expect(res.data.tx_response?.raw_log?.match('failed')).toBeFalsy();
  });
});
kimurayu45z commented 3 years ago

Version of Cosmos SDK in backend is less or equal than 0.39…plz use v0.39 of this library Version of Cosmos SDK in backend is greater or equal than 0.40…plz use latest version of this library

mikewyszinski commented 3 years ago

hey thanks forthe reply!

so i am trying to hit a cosmos project (thornode) which is using 0.42.1- > https://gitlab.com/thorchain/thornode/-/blob/develop/go.mod#L14

I did refactor the code according to the readme. (see my branch here https://github.com/xchainjs/xchainjs-lib/blob/70de241c892d2f5645ed480892c572f293d1a16d/packages/xchain-cosmos/src/cosmos/sdk-client.ts#L197)

However, i am getting an error when posting to /cosmos/tx/v1beta1/txs

request

 url: 'https://testnet.thornode.thorchain.info/cosmos/tx/v1beta1/txs',
          method: 'post',
          data: '"{\\"tx_bytes\\":\\"ClMKGgoUdGhvcmNoYWluL01zZ0RlcG9zaXQSAhIAEjU9OkJOQi5CTkI6dGJuYjFrbXUwbjZzNDRjejVqeGR2a3ZzdnJ6Z3I1N25kZzZhdHc1enJ5cxJYClAKRgofL2Nvc21vcy5jcnlwdG8uc2VjcDI1NmsxLlB1YktleRIjCiEDiNf6aunnRDzRn/FP2IVIBpjQ+noauhFnzkJE3UjpB6oSBAoCCAEYJxIEEICJehpA7grQwhk4N8V3FDw3oEHRY0iOzol3rDKyAliZRYZtJ8QKJG841E8V192bfmAs14clIts6EO9oOX9KLXZf0czi5w==\\",\\"mode\\":\\"BROADCAST_MODE_BLOCK\\"}"'

response

response: {
        status: 400,
        statusText: 'Bad Request',
        data: {
          code: 3,
          message: 'json: cannot unmarshal string into Go value of type map[string]json.RawMessage',
          details: []
        }
      }

the current code is calling POST /txs, which still exists in 0.41.x+(https://v1.cosmos.network/rpc/v0.42.6) , so i am thinking i maybe should still be hitting /txs and NOT /cosmos/tx/v1beta1/txs. not sure what the difference is between them....

is there any sample code about building and signing txs Using cosmos-client/cjs/openapi/api/TransactionsAPI? Since it's still supported?

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',
    })

again, thanks for the help!, i'm just really confused at this point....

kimurayu45z commented 3 years ago

The api POST /txs is the api of Cosmos SDK v0.39. S o it is an old version of the api for announcing transactions.

The breaking changes between Cosmos SDK v0.39 and v0.40 also includes the change of schema of transaction JSON object. If the blockchain which you want to use is v0.4x, please use POST /cosmos/tx/v1beta/txs.

In the point of view where I saw your request data, I think it is suspicious that the escape sequence \\" continues twice. How about \"?

mikewyszinski commented 3 years ago

I think theres a bug in the current version 0.42.14. i am testing against testnet using a seed with this address --> https://api.testnet.cosmos.network/cosmos/bank/v1beta1/balances/cosmos15yuxxfwzu5y5tvhrl4lws6hh925pgul025myjl

import { cosmosclient, proto, rest } from 'cosmos-client'

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

    const sdk = new cosmosclient.CosmosSDK('https://api.testnet.cosmos.network', 'cosmoshub-testnet')

    const privKey = new proto.cosmos.crypto.secp256k1.PrivKey({
      key: await cosmosclient.generatePrivKeyFromMnemonic(process.env.PHRASE || ''),
    })
    const pubKey = privKey.pubKey()
    const address = cosmosclient.AccAddress.fromPublicKey(pubKey)

    expect(address.toString()).toStrictEqual('cosmos15yuxxfwzu5y5tvhrl4lws6hh925pgul025myjl')

    const fromAddress = address
    const toAddress = address

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

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

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

    const txBody = new proto.cosmos.tx.v1beta1.TxBody({
      messages: [cosmosclient.codec.packAny(msgSend)],
    })
    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: account.sequence,
        },
      ],
      fee: {
        gas_limit: cosmosclient.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
    try {
      const res = await rest.cosmos.tx.broadcastTx(sdk, {
        tx_bytes: txBuilder.txBytes(),
        mode: rest.cosmos.tx.BroadcastTxMode.Block,
      })
      console.log(res)
      expect(res.data.tx_response?.raw_log?.match('failed')).toBeFalsy()
    } catch (error) {
      console.log(error)
    }
  })
})

i get the exact same error with this code, whic is exactly the code in the readme 'json: cannot unmarshal string into Go value of type map[string]json.RawMessage'

details


Error: Request failed with status code 400
          at createError (/Users/mike/mike/xchainjs/repo/xchainjs-lib/node_modules/axios/lib/core/createError.js:16:15)
          at settle (/Users/mike/mike/xchainjs/repo/xchainjs-lib/node_modules/axios/lib/core/settle.js:17:12)
          at IncomingMessage.handleStreamEnd (/Users/mike/mike/xchainjs/repo/xchainjs-lib/node_modules/axios/lib/adapters/http.js:269:11)
          at IncomingMessage.emit (events.js:215:7)
          at endReadableNT (_stream_readable.js:1184:12)
          at processTicksAndRejections (internal/process/task_queues.js:80:21) {
        config: {
          url: 'https://api.testnet.cosmos.network/cosmos/tx/v1beta1/txs',
          method: 'post',
          data: '"{\\"tx_bytes\\":\\"CpIBCo8BChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEm8KLWNvc21vczE1eXV4eGZ3enU1eTV0dmhybDRsd3M2aGg5MjVwZ3VsMDI1bXlqbBItY29zbW9zMTV5dXh4Znd6dTV5NXR2aHJsNGx3czZoaDkyNXBndWwwMjVteWpsGg8KB3VwaG90b24SBDEwMDASWApQCkYKHy9jb3Ntb3MuY3J5cHRvLnNlY3AyNTZrMS5QdWJLZXkSIwohAj67jT56d5py32zCQqvh7t5TAzS/MeKPeE2wiznDlJsGEgQKAggBGAASBBDAmgwaQBKmuE+O4TODUioWbG5SZ5Z1ZNB29/weDVhJzT9fopHSRzZVgOlU9GOO+5U0tORFIFV3qkYFypzK05YXpDMD0+Q=\\",\\"mode\\":\\"BROADCAST_MODE_BLOCK\\"}"',
          headers: {
            Accept: 'application/json, text/plain, */*',
            'Content-Type': 'application/json',
            'User-Agent': 'axios/0.21.3',
            'Content-Length': 463
          },
          transformRequest: [ [Function: transformRequest] ],
          transformResponse: [ [Function: transformResponse] ],
          timeout: 0,
          adapter: [Function: httpAdapter],
          xsrfCookieName: 'XSRF-TOKEN',
          xsrfHeaderName: 'X-XSRF-TOKEN',
          maxContentLength: -1,
          maxBodyLength: -1,
          validateStatus: [Function: validateStatus],
          transitional: {
            silentJSONParsing: true,
            forcedJSONParsing: true,
            clarifyTimeoutError: false
          }
        },
        request: ClientRequest {
          _events: [Object: null prototype] {
            socket: [Function],
            abort: [Function],
            aborted: [Function],
            connect: [Function],
            error: [Function],
            timeout: [Function],
            prefinish: [Function: requestOnPrefinish]
          },
          _eventsCount: 7,
          _maxListeners: undefined,
          outputData: [],
          outputSize: 0,
          writable: true,
          _last: true,
          chunkedEncoding: false,
          shouldKeepAlive: false,
          useChunkedEncodingByDefault: true,
          sendDate: false,
          _removedConnection: false,
          _removedContLen: false,
          _removedTE: false,
          _contentLength: null,
          _hasBody: true,
          _trailer: '',
          finished: true,
          _headerSent: true,
          socket: TLSSocket {
            _tlsOptions: [Object],
            _secureEstablished: true,
            _securePending: false,
            _newSessionPending: false,
            _controlReleased: true,
            _SNICallback: null,
            servername: 'api.testnet.cosmos.network',
            alpnProtocol: false,
            authorized: true,
            authorizationError: null,
            encrypted: true,
            _events: [Object: null prototype],
            _eventsCount: 9,
            connecting: false,
            _hadError: false,
            _parent: null,
            _host: 'api.testnet.cosmos.network',
            _readableState: [ReadableState],
            readable: true,
            _maxListeners: undefined,
            _writableState: [WritableState],
            writable: false,
            allowHalfOpen: false,
            _sockname: null,
            _pendingData: null,
            _pendingEncoding: '',
            server: undefined,
            _server: null,
            ssl: [TLSWrap],
            _requestCert: true,
            _rejectUnauthorized: true,
            parser: null,
            _httpMessage: [Circular],
            [Symbol(res)]: [TLSWrap],
            [Symbol(asyncId)]: 32,
            [Symbol(kHandle)]: [TLSWrap],
            [Symbol(lastWriteQueueSize)]: 0,
            [Symbol(timeout)]: null,
            [Symbol(kBuffer)]: null,
            [Symbol(kBufferCb)]: null,
            [Symbol(kBufferGen)]: null,
            [Symbol(kBytesRead)]: 0,
            [Symbol(kBytesWritten)]: 0,
            [Symbol(connect-options)]: [Object]
          },
          connection: TLSSocket {
            _tlsOptions: [Object],
            _secureEstablished: true,
            _securePending: false,
            _newSessionPending: false,
            _controlReleased: true,
            _SNICallback: null,
            servername: 'api.testnet.cosmos.network',
            alpnProtocol: false,
            authorized: true,
            authorizationError: null,
            encrypted: true,
            _events: [Object: null prototype],
            _eventsCount: 9,
            connecting: false,
            _hadError: false,
            _parent: null,
            _host: 'api.testnet.cosmos.network',
            _readableState: [ReadableState],
            readable: true,
            _maxListeners: undefined,
            _writableState: [WritableState],
            writable: false,
            allowHalfOpen: false,
            _sockname: null,
            _pendingData: null,
            _pendingEncoding: '',
            server: undefined,
            _server: null,
            ssl: [TLSWrap],
            _requestCert: true,
            _rejectUnauthorized: true,
            parser: null,
            _httpMessage: [Circular],
            [Symbol(res)]: [TLSWrap],
            [Symbol(asyncId)]: 32,
            [Symbol(kHandle)]: [TLSWrap],
            [Symbol(lastWriteQueueSize)]: 0,
            [Symbol(timeout)]: null,
            [Symbol(kBuffer)]: null,
            [Symbol(kBufferCb)]: null,
            [Symbol(kBufferGen)]: null,
            [Symbol(kBytesRead)]: 0,
            [Symbol(kBytesWritten)]: 0,
            [Symbol(connect-options)]: [Object]
          },
          _header: 'POST /cosmos/tx/v1beta1/txs HTTP/1.1\r\n' +
            'Accept: application/json, text/plain, */*\r\n' +
            'Content-Type: application/json\r\n' +
            'User-Agent: axios/0.21.3\r\n' +
            'Content-Length: 463\r\n' +
            'Host: api.testnet.cosmos.network\r\n' +
            'Connection: close\r\n' +
            '\r\n',
          _onPendingData: [Function: noopPendingOutput],
          agent: Agent {
            _events: [Object: null prototype],
            _eventsCount: 1,
            _maxListeners: undefined,
            defaultPort: 443,
            protocol: 'https:',
            options: [Object],
            requests: {},
            sockets: [Object],
            freeSockets: {},
            keepAliveMsecs: 1000,
            keepAlive: false,
            maxSockets: Infinity,
            maxFreeSockets: 256,
            maxCachedSessions: 100,
            _sessionCache: [Object]
          },
          socketPath: undefined,
          method: 'POST',
          path: '/cosmos/tx/v1beta1/txs',
          _ended: true,
          res: IncomingMessage {
            _readableState: [ReadableState],
            readable: false,
            _events: [Object: null prototype],
            _eventsCount: 3,
            _maxListeners: undefined,
            socket: [TLSSocket],
            connection: [TLSSocket],
            httpVersionMajor: 1,
            httpVersionMinor: 1,
            httpVersion: '1.1',
            complete: true,
            headers: [Object],
            rawHeaders: [Array],
            trailers: {},
            rawTrailers: [],
            aborted: false,
            upgrade: false,
            url: '',
            method: null,
            statusCode: 400,
            statusMessage: 'Bad Request',
            client: [TLSSocket],
            _consuming: false,
            _dumped: false,
            req: [Circular],
            responseUrl: 'https://api.testnet.cosmos.network/cosmos/tx/v1beta1/txs',
            redirects: []
          },
          aborted: false,
          timeoutCb: null,
          upgradeOrConnect: false,
          parser: null,
          maxHeadersCount: null,
          _redirectable: Writable {
            _writableState: [WritableState],
            writable: true,
            _events: [Object: null prototype],
            _eventsCount: 2,
            _maxListeners: undefined,
            _options: [Object],
            _ended: true,
            _ending: true,
            _redirectCount: 0,
            _redirects: [],
            _requestBodyLength: 463,
            _requestBodyBuffers: [],
            _onNativeResponse: [Function],
            _currentRequest: [Circular],
            _currentUrl: 'https://api.testnet.cosmos.network/cosmos/tx/v1beta1/txs'
          },
          [Symbol(kNeedDrain)]: false,
          [Symbol(isCorked)]: false,
          [Symbol(kOutHeaders)]: [Object: null prototype] {
            accept: [Array],
            'content-type': [Array],
            'user-agent': [Array],
            'content-length': [Array],
            host: [Array]
          }
        },
        response: {
          status: 400,
          statusText: 'Bad Request',
          headers: {
            date: 'Wed, 22 Sep 2021 03:02:41 GMT',
            'content-type': 'application/json',
            'content-length': '130',
            connection: 'close',
            'x-server-time': '1632279761',
            'strict-transport-security': 'max-age=15724800; includeSubDomains'
          },
          config: {
            url: 'https://api.testnet.cosmos.network/cosmos/tx/v1beta1/txs',
            method: 'post',
            data: '"{\\"tx_bytes\\":\\"CpIBCo8BChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEm8KLWNvc21vczE1eXV4eGZ3enU1eTV0dmhybDRsd3M2aGg5MjVwZ3VsMDI1bXlqbBItY29zbW9zMTV5dXh4Znd6dTV5NXR2aHJsNGx3czZoaDkyNXBndWwwMjVteWpsGg8KB3VwaG90b24SBDEwMDASWApQCkYKHy9jb3Ntb3MuY3J5cHRvLnNlY3AyNTZrMS5QdWJLZXkSIwohAj67jT56d5py32zCQqvh7t5TAzS/MeKPeE2wiznDlJsGEgQKAggBGAASBBDAmgwaQBKmuE+O4TODUioWbG5SZ5Z1ZNB29/weDVhJzT9fopHSRzZVgOlU9GOO+5U0tORFIFV3qkYFypzK05YXpDMD0+Q=\\",\\"mode\\":\\"BROADCAST_MODE_BLOCK\\"}"',
            headers: [Object],
            transformRequest: [Array],
            transformResponse: [Array],
            timeout: 0,
            adapter: [Function: httpAdapter],
            xsrfCookieName: 'XSRF-TOKEN',
            xsrfHeaderName: 'X-XSRF-TOKEN',
            maxContentLength: -1,
            maxBodyLength: -1,
            validateStatus: [Function: validateStatus],
            transitional: [Object]
          },
          request: ClientRequest {
            _events: [Object: null prototype],
            _eventsCount: 7,
            _maxListeners: undefined,
            outputData: [],
            outputSize: 0,
            writable: true,
            _last: true,
            chunkedEncoding: false,
            shouldKeepAlive: false,
            useChunkedEncodingByDefault: true,
            sendDate: false,
            _removedConnection: false,
            _removedContLen: false,
            _removedTE: false,
            _contentLength: null,
            _hasBody: true,
            _trailer: '',
            finished: true,
            _headerSent: true,
            socket: [TLSSocket],
            connection: [TLSSocket],
            _header: 'POST /cosmos/tx/v1beta1/txs HTTP/1.1\r\n' +
              'Accept: application/json, text/plain, */*\r\n' +
              'Content-Type: application/json\r\n' +
              'User-Agent: axios/0.21.3\r\n' +
              'Content-Length: 463\r\n' +
              'Host: api.testnet.cosmos.network\r\n' +
              'Connection: close\r\n' +
              '\r\n',
            _onPendingData: [Function: noopPendingOutput],
            agent: [Agent],
            socketPath: undefined,
            method: 'POST',
            path: '/cosmos/tx/v1beta1/txs',
            _ended: true,
            res: [IncomingMessage],
            aborted: false,
            timeoutCb: null,
            upgradeOrConnect: false,
            parser: null,
            maxHeadersCount: null,
            _redirectable: [Writable],
            [Symbol(kNeedDrain)]: false,
            [Symbol(isCorked)]: false,
            [Symbol(kOutHeaders)]: [Object: null prototype]
          },
          data: {
            code: 3,
            message: 'json: cannot unmarshal string into Go value of type map[string]json.RawMessage',
            details: []
          }
        },
        isAxiosError: true,
        toJSON: [Function: toJSON]
      }```
kimurayu45z commented 3 years ago

Please tell me the content of go.mod of the blockchain you are testing.

mikewyszinski commented 3 years ago

https://api.testnet.cosmos.network/node_info

Screen Shot 2021-09-21 at 9 22 58 PM

kimurayu45z commented 3 years ago

Thank you.

I confirmed that tx announce is succeeded when both the blockchain is v0.41.0 and v0.42.9.

I created the blockchain with starport. https://github.com/tendermint/starport

v0.41.0

 PASS  src/rest/cosmos/bank/bank.spec.ts
  bank
    ✓ send (914 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.983 s
Ran all test suites matching /bank/i.
  console.log
    {
      data: {
        tx_response: {
          height: '24',
          txhash: '6AEF2D2A26BAFAD048998CCAB4128B685D9595E0ADF3DDE63CCA8BB12FDCD166',
          codespace: '',
          code: 0,
          data: '0A060A0473656E64',
          raw_log: '[{"events":[{"type":"message","attributes":[{"key":"action","value":"send"},{"key":"sender","value":"cosmos18j8jjel0deh2t5yamxy6tnafd6dng36mddhy39"},{"key":"module","value":"bank"}]},{"type":"transfer","attributes":[{"key":"recipient","value":"cosmos18j8jjel0deh2t5yamxy6tnafd6dng36mddhy39"},{"key":"sender","value":"cosmos18j8jjel0deh2t5yamxy6tnafd6dng36mddhy39"},{"key":"amount","value":"1token"}]}]}]',
          logs: [Array],
          info: '',
          gas_wanted: '200000',
          gas_used: '50126',
          tx: null,
          timestamp: ''
        }
      },
      status: 200,
      statusText: 'OK',
      headers: { 'content-type': 'application/json' },
      config: {
        url: 'http://localhost:1317/cosmos/tx/v1beta1/txs',
        method: 'post',
        data: '{"tx_bytes":"Co0BCooBChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEmoKLWNvc21vczE4ajhqamVsMGRlaDJ0NXlhbXh5NnRuYWZkNmRuZzM2bWRkaHkzORItY29zbW9zMThqOGpqZWwwZGVoMnQ1eWFteHk2dG5hZmQ2ZG5nMzZtZGRoeTM5GgoKBXRva2VuEgExElgKUApGCh8vY29zbW9zLmNyeXB0by5zZWNwMjU2azEuUHViS2V5EiMKIQPXxcc5qLLxXq+3gWDdnT6uTxADXOcyrADAKy5BXEC2nBIECgIIARgBEgQQwJoMGkA0kQmEgbEhtjPwPbv90H2JgNXcpRipAQ6Wz8HWUdguyA951Qhg2Y8MvzY3UGQ31xmrz2qCUW+FC9NJ6F0S0e/b","mode":"BROADCAST_MODE_BLOCK"}',
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        adapter: [Function: xhrAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        maxBodyLength: -1,
        validateStatus: [Function: validateStatus]
      },
      request: XMLHttpRequest {}
    }

      at src/rest/cosmos/bank/bank.spec.ts:70:13

v0.42.9

 PASS  src/rest/cosmos/bank/bank.spec.ts
  bank
    ✓ send (916 ms)

  console.log
    {
      data: {
        tx_response: {
          height: '17',
          txhash: 'D54777514171BA337D547DCAD8F952421F5659539947B179622158216AC1572A',
          codespace: '',
          code: 0,
          data: '0A060A0473656E64',
          raw_log: '[{"events":[{"type":"message","attributes":[{"key":"action","value":"send"},{"key":"sender","value":"cosmos1vd3qe4rk3ygkeftuk90t6m4f5plfgtfs7023lw"},{"key":"module","value":"bank"}]},{"type":"transfer","attributes":[{"key":"recipient","value":"cosmos1vd3qe4rk3ygkeftuk90t6m4f5plfgtfs7023lw"},{"key":"sender","value":"cosmos1vd3qe4rk3ygkeftuk90t6m4f5plfgtfs7023lw"},{"key":"amount","value":"1token"}]}]}]',
          logs: [Array],
          info: '',
          gas_wanted: '200000',
          gas_used: '50126',
          tx: null,
          timestamp: ''
        }
      },
      status: 200,
      statusText: 'OK',
      headers: { 'content-type': 'application/json' },
      config: {
        url: 'http://localhost:1317/cosmos/tx/v1beta1/txs',
        method: 'post',
        data: '{"tx_bytes":"Co0BCooBChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEmoKLWNvc21vczF2ZDNxZTRyazN5Z2tlZnR1azkwdDZtNGY1cGxmZ3RmczcwMjNsdxItY29zbW9zMXZkM3FlNHJrM3lna2VmdHVrOTB0Nm00ZjVwbGZndGZzNzAyM2x3GgoKBXRva2VuEgExElgKUApGCh8vY29zbW9zLmNyeXB0by5zZWNwMjU2azEuUHViS2V5EiMKIQNzZuRnB6ccTvdufpQsoe7rvxKUqgPelicwLjhp0H3zvRIECgIIARgBEgQQwJoMGkA9q8LTcLlcTlRhxy1CboI+LobkiH+3GhCEmWaGJpvcQVJ2hdjk2vwLkrNvu525PuRAQmZRb3RKvHX2ueZwaM8Y","mode":"BROADCAST_MODE_BLOCK"}',
        headers: {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json'
        },
        transformRequest: [ [Function: transformRequest] ],
        transformResponse: [ [Function: transformResponse] ],
        timeout: 0,
        adapter: [Function: xhrAdapter],
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        maxBodyLength: -1,
        validateStatus: [Function: validateStatus]
      },
      request: XMLHttpRequest {}
    }

      at src/rest/cosmos/bank/bank.spec.ts:70:13

The difference between my log and yours is that there are many suspicious \\ like \\"tx_bytes\\":.

mikewyszinski commented 3 years ago

hey thanks for looking into this again. i couldn't find the root cause, so ended up with this workaround

    //  this broadcast finction does not work!!
    // const res = await rest.cosmos.tx.broadcastTx(this.sdk, {
    //   tx_bytes: txBuilder.txBytes(),
    //   mode: rest.cosmos.tx.BroadcastTxMode.Sync,
    // })
    const res = await axios.post(`${this.server}/cosmos/tx/v1beta1/txs`, {
      tx_bytes: txBuilder.txBytes(),
      mode: rest.cosmos.tx.BroadcastTxMode.Block,
    })
kimurayu45z commented 3 years ago

Oh I know that you are using the axios post method directly instead of using the tx post method in this library. I think it is the cause. Json marshalling is suspicious. \\ may be the cause of failure in JSON unmarshalling in go backend.

mikewyszinski commented 3 years ago

yeah that was definitely the cause. but not sure why

{
  tx_bytes: txBuilder.txBytes(),
  mode: rest.cosmos.tx.BroadcastTxMode.Block,
}

ends up being encoded as an escaped string....

kimurayu45z commented 3 years ago

How about checking the configurations of Axios?

kimurayu45z commented 3 years ago

I found a good thread. Plz refer to it.

https://stackoverflow.com/questions/66268561/axios-adds-extra-trailing-slash-in-body-values

https://github.com/axios/axios/issues/738

kimurayu45z commented 3 years ago

@mikewyszinski

you may need set AxiosConfig

headers: {
  "Content-Type": "application/json",
},
responseType: "json",