0

The following code creates an account, except for the part where I try to add a trust line to an asset. It returns a code 400. What am I writing incorrectly regarding the add trust operation?

const express = require('express')
const app = express()
const StellarSdk = require('stellar-sdk');
StellarSdk.Network.useTestNetwork();
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

const source = StellarSdk.Keypair.fromSecret('SK0x0...')
const counterAsset = new StellarSdk.Asset('XAG', 'PK0x0...')

app.get("/wallet", (req, res) => {

  const keyPair = StellarSdk.Keypair.random();

  console.log(keyPair.publicKey())
  console.log(keyPair.secret())

  server.accounts()
  .accountId(source.publicKey())
  .call()
  .then(({ sequence }) => {
    const account = new StellarSdk.Account(source.publicKey(), sequence)

    const builder = new StellarSdk.TransactionBuilder(account, {
      fee: 300
    })
      builder.addOperation(StellarSdk.Operation.createAccount({
        destination: keyPair.publicKey(),
        startingBalance: '3.4'
      }))
      

***THIS CHANGE TRUST OPERATION CAUSES REQUEST TO FAIL.

      builder.addOperation(StellarSdk.Operation.changeTrust({ 
        asset: counterAsset,
        amount: '1000000000000',
        source: keyPair.publicKey()
    }))

      const transaction = builder.build()
      transaction.sign(source)
    return server.submitTransaction(transaction)
  })

  .then(results => {
    console.log('Transaction', results._links.transaction.href)
    console.log('success')
          res.send({
            publicKey: keyPair.publicKey(),
            secretKey: keyPair.secret(),
          })
  })
  .catch(err => {
    console.log('error', err);
  })

})

app.listen(3003, () => {
  console.log('Server is up and running on port 3003')
})

I am getting a bad request error as follows:

error { Error: Request failed with status code 400
    at createError (/Users/Hello/Desktop/Projects/exchangeServer/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/Users/Hello/Desktop/Projects/exchangeServer/node_modules/axios/lib/core/settle.js:18:12)
    at IncomingMessage.handleStreamEnd (/Users/Hello/Desktop/Projects/exchangeServer/node_modules/axios/lib/adapters/http.js:201:11)
    at IncomingMessage.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1129:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 60000,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'axios/0.18.0',
        'Content-Length': 423 },
     method: 'post',
     url: 'https://horizon-testnet.stellar.org/transactions',
     data:
      'tx=AAAAAHiP6SBnr%2Bbs42ylxwXgQIS8ho0DW7JmOe91vOoBCYSbAAACWAAA9%2BoAAAC1AAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAIGnU6XXtq40HilhyeegzAmJYKEh7wISVMx7QzyltaWcAAAAAAgbMgAAAAAEAAAAAIGnU6XXtq40HilhyeegzAmJYKEh7wISVMx7QzyltaWcAAAAGAAAAAVhBRwAAAAAAz8%2FKnYpsj5whk1w6te4Zz7avOTzHNlgEfnJDgGER4sJ%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwAAAAAAAAABAQmEmwAAAECMNzY%2BA1UK%2FFkBVN9%2FnD8DyA5IpLL4xAVbsq%2BqrcNSa%2FCyB6Rl5N57XtaAy3KMFc1BU5SDCNewdtYwhLVJpGYH' },
  request:
   ClientRequest {
     _events:
      [Object: null prototype] {
        socket: [Function],
        abort: [Function],
        aborted: [Function],
        error: [Function],
        timeout: [Function],
        prefinish: [Function: requestOnPrefinish] },
     _eventsCount: 6,
     _maxListeners: undefined,
     output: [],
     outputEncodings: [],
     outputCallbacks: [],
     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: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: [TLSWrap],
        _parent: null,
        _host: 'horizon-testnet.stellar.org',
        _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)]: 208,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: 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: false,
        alpnProtocol: false,
        authorized: true,
        authorizationError: null,
        encrypted: true,
        _events: [Object],
        _eventsCount: 8,
        connecting: false,
        _hadError: false,
        _handle: [TLSWrap],
        _parent: null,
        _host: 'horizon-testnet.stellar.org',
        _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)]: 208,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0,
        [Symbol(connect-options)]: [Object] },
     _header:
      'POST /transactions HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/x-www-form-urlencoded\r\nUser-Agent: axios/0.18.0\r\nContent-Length: 423\r\nHost: horizon-testnet.stellar.org\r\nConnection: close\r\n\r\n',
     _onPendingData: [Function: noopPendingOutput],
     agent:
      Agent {
        _events: [Object],
        _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,
     timeout: undefined,
     method: 'POST',
     path: '/transactions',
     _ended: true,
     res:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: false,
        _events: [Object],
        _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://horizon-testnet.stellar.org/transactions',
        redirects: [] },
     aborted: undefined,
     timeoutCb: null,
     upgradeOrConnect: false,
     parser: null,
     maxHeadersCount: null,
     _redirectable:
      Writable {
        _writableState: [WritableState],
        writable: true,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _options: [Object],
        _redirectCount: 0,
        _redirects: [],
        _requestBodyLength: 423,
        _requestBodyBuffers: [],
        _onNativeResponse: [Function],
        _currentRequest: [Circular],
        _currentUrl: 'https://horizon-testnet.stellar.org/transactions' },
     [Symbol(isCorked)]: false,
     [Symbol(outHeadersKey)]:
      [Object: null prototype] {
        accept: [Array],
        'content-type': [Array],
        'user-agent': [Array],
        'content-length': [Array],
        host: [Array] } },

And lastly, how can I handle the error, so the request isn't sent over and over? Regards

1

Since changeTrust affects your newly created account, source is not allowed to do changeTrust operations on behalf of keyPair. However keyPair may allow it by co-signing the transaction => adding transaction.sign(keyPair) should do the trick.

Besides you can get more meaningful errors => Can't see the error code in the error object

1
  • Thank you. I was signing with the wrong secret key.
    – p3scobar
    Jun 7 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.