Giter Club home page Giter Club logo

js-soroban-client's Introduction

Stellar
Creating equitable access to the global financial system

js-soroban-client

npm version Test Status Coverage Status

Deprecation Notice

This repository has been deprecated in favor of the stellar-sdk package. Please read the migration guide for how to upgrade to that package. Future changes will only be made there.


js-soroban-client is a JavaScript library for communicating with a Soroban RPC server and building Stellar apps. It provides:

  • a networking layer API for soroban-rpc methods.
  • facilities for building and signing transactions, for communicating with a soroban-rpc instance, and for submitting transactions or querying network state.

soroban-client vs stellar-base

soroban-client is a high-level library that serves as client-side API for Horizon. stellar-base is lower-level library for creating Stellar primitive constructs via XDR helpers and wrappers.

Most people will want soroban-client instead of stellar-base. You should only use stellar-base if you know what you're doing!

If you add soroban-client to a project, do not add stellar-base! Mis-matching versions could cause weird, hard-to-find bugs. soroban-client automatically installs stellar-base and exposes all of its exports in case you need them.

Important! The Node.js version of the stellar-base (soroban-client dependency) package uses the sodium-native package as an optional dependency. sodium-native is a low level binding to libsodium, (an implementation of Ed25519 signatures). If installation of sodium-native fails, or it is unavailable, stellar-base (and soroban-client) will fallback to using the tweetnacl package implementation.

If you are using soroban-client/stellar-base in a browser you can ignore this. However, for production backend deployments you should be using sodium-native. If sodium-native is successfully installed and working the SorobanClient.FastSigning variable will return true.

Quick start

Using npm to include js-soroban-client in your own project:

npm install --save soroban-client

Alternatively, you can use cdnjs in a browser:

<script src="https://cdnjs.cloudflare.com/ajax/libs/soroban-client/{version}/soroban-client.js"></script>

Install

To use as a module in a Node.js project

  1. Install it using npm:
npm install --save soroban-client
  1. require/import it in your JavaScript:
var SorobanClient = require('soroban-client');

To self host for use in the browser

  1. Install it using bower:
bower install soroban-client
  1. Include it in the browser:
<script src="./bower_components/soroban-client/soroban-client.js"></script>
<script>
  console.log(SorobanClient);
</script>

If you don't want to use or install Bower, you can copy built JS files from the bower-js-soroban-client repo.

To use the cdnjs hosted script in the browser

  1. Instruct the browser to fetch the library from cdnjs, a 3rd party service that hosts js libraries:
<script src="https://cdnjs.cloudflare.com/ajax/libs/soroban-client/{version}/soroban-client.js"></script>
<script>
  console.log(SorobanClient);
</script>

Note that this method relies using a third party to host the JS library. This may not be entirely secure.

Make sure that you are using the latest version number. They can be found on the releases page in Github.

To develop and test js-soroban-client itself

  1. Clone the repo:
git clone https://github.com/stellar/js-soroban-client.git
  1. Install dependencies inside js-soroban-client folder:
cd js-soroban-client
yarn install
  1. Install Node 16

Because we support the latest maintenance version of Node, please install and develop on Node 16 so you don't get surprised when your code works locally but breaks in CI.

Here's how to install nvm if you haven't: https://github.com/creationix/nvm

nvm install

# if you've never installed 16 before you'll want to re-install yarn
yarn install -g yarn

If you work on several projects that use different Node versions, you might it helpful to install this automatic version manager: https://github.com/wbyoung/avn

  1. Observe the project's code style

While you're making changes, make sure to run the linter-watcher to catch any linting errors (in addition to making sure your text editor supports ESLint)

node_modules/.bin/gulp watch

Usage

For information on how to use js-soroban-client, take a look at the documentation, or the examples.

Testing

To run all tests:

gulp test

To run a specific set of tests:

gulp test:node
gulp test:browser

To generate and check the documentation site:

# install the `serve` command if you don't have it already
yarn install -g serve

# generate the docs files
yarn docs

# get these files working in a browser
cd jsdoc && serve .

# you'll be able to browse the docs at http://localhost:5000

Documentation

Documentation for this repo lives in Developers site.

Contributing

For information on how to contribute, please refer to our contribution guide.

Publishing to npm

See CONTRIBUTING.md for the detailed release process. Once a new release is published and CI passes, a new package will be published to npm by GitHub actions.

License

js-soroban-client is licensed under an Apache-2.0 license. See the LICENSE file for details.

js-soroban-client's People

Contributors

abuiles avatar andywer avatar bartekn avatar brianebert avatar challet avatar dependabot[bot] avatar dydt avatar fnando avatar fracek avatar grempe avatar irisli avatar jakeurban avatar jedmccaleb avatar kalepail avatar leighmcculloch avatar marcelosalloum avatar morleyzhi avatar msfeldstein avatar nullstyle avatar overcat avatar poliha avatar pselden avatar ryanleecode avatar shaptic avatar sreuland avatar tamirms avatar thejollyrogers avatar tomerweller avatar vcarl avatar willemneal 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

Watchers

 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

js-soroban-client's Issues

docs: Emit SorobanRpc.*Response types into jsdoc

Currently the comments there get stripped out by the typescript compilation step, so they are not included in the jsdoc.
We should emit them so we can link to them from the server.ts docs.

Follow-up from #27

[Question] JS - Enum/struct as parameter to function

In the Browser (not Node.js) I'm trying to invoke a contract function but one of parameters is a Enum in Rust.
How do I build and pass an instance of MyEnum to the function?

I'm using this to import the JS SDK:

<script src="https://cdnjs.cloudflare.com/ajax/libs/soroban-client/0.8.0/soroban-client.js"></script>

This is the the code I'm trying to fix:

let transaction = new SorobanClient.TransactionBuilder(account, {
  fee: config.fee,
  networkPassphrase: config.networkPassphrase,
})
  .addOperation(
    contract.call(
      "myfunc",
      SorobanClient.xdr.ScVal.scvU32(param1),
      SorobanClient.xdr.ScVal.scvSymbol(param2),
      // <- how to pass an MyEnum instance here?
    )
  )
  .setTimeout(30)
  .build();

In the above code, the function myfunc receives two parameters, the first one is of type u32, and second one is of type Symbol.
But in my contract, there's a third parameter of type MyEnum, which is an Enum:

#[derive(Clone, PartialEq, Debug)]
#[contracttype]
pub enum MyEnum {
    Identifier(Symbol),
    Count(u32),
}

...

fn myfunc(env: Env, param1: u32, param2: Symbol, param3: MyEnum) -> Option<u32>;

Also, if param3 was struct instead of Enum, how would I build and pass the struct to the function?

Server class on jsdocs doesn't include docs on methods

Describe the bug
the generated jsdocs for Server class only defines the constructor method, it doesn't include docs on the methods of Server class.

What version are you on?
0.6.1

To Reproduce
Steps to reproduce the behavior:
$ yarn install
$ yarn docs

open ./jsdoc/index.html from browser and then go to the Server class from left hand side menu.

https://stellar.github.io/js-soroban-client/Server.html is an example of what docs look like, shows just the constructor method.

Expected behavior
the Server class would show docs for methods like prepareTransaction

Additional context

Example in docs doesn't quite work

I'm trying to get the counter example working locally but hit a few bugs in the docs (and maybe elsewhere).

Setup:

const SorobanClient = require('soroban-client');

// XXX need http to not crash with unsecure connection error
const server = new SorobanClient.Server('http://localhost:8000/soroban/rpc', { allowHttp: true });
const secretKey = 'SBKROBEITSLZJDTK6W5A7OMDAO6X47Q2E4B4FS5ST5NCJ2USDCBJNOTK';
const keypair = SorobanClient.Keypair.fromSecret(secretKey);
const publicKey = keypair.publicKey();
const contractId = '74aeaf0a3d4a4c3419af98b51cce1fb3e8d01b7fdaa60f8b17c080d0a613f232';

(async function main() {
  // // XXX getAccount (as used in readme.md) doesn't return an Account so build will fail
  const _account = await server.getAccount(publicKey);
  const account = new SorobanClient.Account(_account.id, _account.sequence);
  /// XXX: loadAccount (as used https://github.com/stellar/js-soroban-client/blob/main/docs/reference/examples.md) is not a method on server 

  // Right now, this is just the default fee for this example.
  const fee = 100;

  const contract = new SorobanClient.Contract(contractId);

  const transaction = new SorobanClient.TransactionBuilder(account, {
    fee,
    // XXX I think this should be STANDALONE not TESTNET to work with 
    // local network as described <https://soroban.stellar.org/docs/tutorials/deploy-to-local-network>
    networkPassphrase: SorobanClient.Networks.STANDALONE
  })
  // Add a contract.increment soroban contract invocation operation
    .addOperation(contract.call("increment"))
  // Make this transaction valid for the next 30 seconds only
    .setTimeout(30)
  // Uncomment to add a memo (https://developers.stellar.org/docs/glossary/transactions/)
  // .addMemo(SorobanClient.Memo.text('Hello world!'))
    .build();

  // Sign this transaction with the secret key
  // NOTE: signing is transaction is network specific. Test network transactions
  // won't work in the public network. To switch networks, use the Network object
  // as explained above (look for SorobanClient.Network).
  transaction.sign(keypair);

  // Let's see the XDR (encoded in base64) of the transaction we just built
  console.log(transaction.toEnvelope().toXDR('base64'));

  // Submit the transaction to the Soroban-RPC server. The Soroban-RPC server
  // will then submit the transaction into the network for us. Then we will have
  // to wait, polling getTransactionStatus until the transaction completes.
  try {
    // XXX few syntax errors in the try block (log + used reponse and result)
    let response = await server.sendTransaction(transaction);
    console.log(`Sent! Transaction ID: ${response.id}`);
    // Poll this until the status is not "pending"
    while (response.status === "pending") {
      // See if the transaction is complete
      response = await server.getTransactionStatus(response.id);
      // Wait a second
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
    console.log('Transaction status:', response.status);
    console.log(JSON.stringify(response));
  } catch (e) {
    console.log('An error has occured:');
    console.log(e);
  }
})()

I'm happy to create PRs to both docs, but thought I'd try to get the example working first. Right now it fails with:

AAAAAgAAAAAmrenqTlRrocs+vVlfX/sGNaDI4LdA4IaRVIhtrsEo2AAAAGQAAAAwAAAAGQAAAAEAAAAAAAAAAAAAAABjy3s0AAAAAAAAAAEAAAAAAAAAGAAAAAAAAAACAAAABAAAAAEAAAAGAAAAIHSurwo9Skw0Ga+YtRzOH7Po0Bt/2qYPixfAgNCmE/IyAAAABQAAAAlpbmNyZW1lbnQAAAAAAAABAAAABnSurwo9Skw0Ga+YtRzOH7Po0Bt/2qYPixfAgNCmE/IyAAAAAwAAAAMAAAAAAAAAAAAAAAGuwSjYAAAAQGkBCtJSATALyyYUOwIj/4NU6gXUjbzvbyZ9PHD61VLtKcRaMt0oTxivN0Ow452wx5CiQiH4rvWnvwQAHlsoiQ8=
Sent! Transaction ID: a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5
Transaction status: error
{"id":"a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5","status":"error","error":{"code":"tx_failed","message":"transaction included in ledger but failed","data":{"transaction":{"_links":{"self":{"href":"http://localhost:8001/transactions/a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5"},"account":{"href":"http://localhost:8001/accounts/GATK32PKJZKGXIOLH26VSX277MDDLIGI4C3UBYEGSFKIQ3NOYEUNQUEI"},"ledger":{"href":"http://localhost:8001/ledgers/1300"},"operations":{"href":"http://localhost:8001/transactions/a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5/operations{?cursor,limit,order}","templated":true},"effects":{"href":"http://localhost:8001/transactions/a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5/effects{?cursor,limit,order}","templated":true},"precedes":{"href":"http://localhost:8001/transactions?order=asc&cursor=5583457488896"},"succeeds":{"href":"http://localhost:8001/transactions?order=desc&cursor=5583457488896"},"transaction":{"href":"http://localhost:8001/transactions/a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5"}},"id":"a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5","paging_token":"5583457488896","successful":false,"hash":"a0d59d370c05b0986a9f27473a5cb02cc96789498adb07d7482eb5dc2699f6e5","ledger":1300,"created_at":"2023-01-21T05:41:46Z","source_account":"GATK32PKJZKGXIOLH26VSX277MDDLIGI4C3UBYEGSFKIQ3NOYEUNQUEI","source_account_sequence":"206158430233","fee_account":"GATK32PKJZKGXIOLH26VSX277MDDLIGI4C3UBYEGSFKIQ3NOYEUNQUEI","fee_charged":"100","max_fee":"100","operation_count":1,"envelope_xdr":"AAAAAgAAAAAmrenqTlRrocs+vVlfX/sGNaDI4LdA4IaRVIhtrsEo2AAAAGQAAAAwAAAAGQAAAAEAAAAAAAAAAAAAAABjy3s0AAAAAAAAAAEAAAAAAAAAGAAAAAAAAAACAAAABAAAAAEAAAAGAAAAIHSurwo9Skw0Ga+YtRzOH7Po0Bt/2qYPixfAgNCmE/IyAAAABQAAAAlpbmNyZW1lbnQAAAAAAAABAAAABnSurwo9Skw0Ga+YtRzOH7Po0Bt/2qYPixfAgNCmE/IyAAAAAwAAAAMAAAAAAAAAAAAAAAGuwSjYAAAAQGkBCtJSATALyyYUOwIj/4NU6gXUjbzvbyZ9PHD61VLtKcRaMt0oTxivN0Ow452wx5CiQiH4rvWnvwQAHlsoiQ8=","result_xdr":"AAAAAAAAAGT/////AAAAAQAAAAAAAAAY/////gA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Jn08cPrVUu0pxFoy3ShPGK83Q7DjnbDHkKJCIfiu9ae/BAAeWyiJDw=="],"valid_after":"1970-01-01T00:00:00Z","valid_before":"2023-01-21T05:42:12Z","preconditions":{"timebounds":{"min_time":"0","max_time":"1674279732"}}}}}}

I'll dig through this to see what's going on (or ask on discord), but one thing that seems pretty bizarre is the URL port in the response is 8001 not 8000; afaict the code in this repo is just passing the URL down so this might be an issue somewhere else.

getEvents params causes rpc server error response

Describe the bug
unexepcted error response from rpc server when using server.getEvents():

{
  code: -32602,
  message: 'invalid parameters: [-32602] invalid parameters'
}

the rpc server jsonrpc handler expects startLedger and endLedger in params to be integers expressed as string types, also passing the js object in an array for params:[jsObj] causes same error response, needed to be params:jsObj

What version are you on?
0.3.0

To Reproduce
this is the same json request that the server.getEvents() emits, rpc server will respond with error

curl --location --request POST 'http://localhost:8000/soroban/rpc' \
--header 'Content-Type: application/json' \
--data-raw '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getEvents",
    "params": [
        {
            "startLedger": 457,
            "endLedger": 459,
            "filters": [{
                "type": "contract"
            }
            ]
        }
    ]
}'

after some trial and error, discovered this format of the request which removes array from params and uses string values for ledgers, will work against rpc server:

curl --location --request POST 'http://localhost:8000/soroban/rpc' \
--header 'Content-Type: application/json' \
--data-raw '{
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getEvents",
    "params": 
        {
            "startLedger": "457",
            "endLedger": "459",
            "filters": [{
                "type": "contract"
            }
            ]
        }
}'

Expected behavior
json payload of events

Additional context

Could not unmarshal transaction

Describe the bug
When trying to simulate a transaction with server.simulateTransaction(), getting error "Could not unmarshal transaction"

What version are you on?
js-soroban-client 0.6.1 soroban-tools 0.7.0

To Reproduce
Steps to reproduce the behavior:

  1. Go to github.com/blocktimefinancial/option/pxpump
  2. Open pxpump.js
  3. Scroll down to line 135
  4. See error message below from the execution results.

Expected behavior
.simulateTransaction should return cost, results, error, and latestLedger

Additional context
Output from pxpump.js application
Creating contract transaction for cd0ca2f721d91df334b79fb1e043920919ed0c6b09f930af5048a50930fb7f44
Tx XDR: AAAAAgAAAADzwQ11keCAXiGbzzenrJCF67uR4i8TRh6rq10fRyygkwAAAGQAACitAAAQOQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGAAAAAEAAAAAAAAABgAAAA0AAAAgzQyi9yHZHfM0t5+x4EOSCRntDGsJ+TCvUEilCTD7f0QAAAAPAAAABnVwZGF0ZQAAAAAACgAAAAAAAAAAAAAAAAAAAAEAAAAKAAAAAAAAAAAAAAAAAACjaAAAAAoAAAAAAAAAAAAAAYg1aIvAAAAACgAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAA=
Simulating transaction for cd0ca2f721d91df334b79fb1e043920919ed0c6b09f930af5048a50930fb7f44
Signing with secret: SCIGOGUPFOZSEBVZBEF3BJL6SZGVSFYANQ6BZE6PTTQ7S4YXYDPY4JHL
cost: { cpuInsns: '0', memBytes: '0' }
results: undefined
error: Could not unmarshal transaction
latestLedger: 0
Preparing transaction for cd0ca2f721d91df334b79fb1e043920919ed0c6b09f930af5048a50930fb7f44
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^

[UnhandledPromiseRejection: 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(). The promise rejected with the reason "Could not unmarshal transaction".] {
code: 'ERR_UNHANDLED_REJECTION'
}

js-soroban-sdk: Fee stats

Add a method to let us fetch fee stats about the network. We also need to update the api docs & implementation here to support this.

js-soroban-sdk: Add jsdocs, and get github pages building

It would be nice to have some jsdocs, and build github pages for this.

There is already a github workflow to build the pages, but it's probably broken because there are no jsdocs. We should add some. We'll also need to update terraform to add github-pages to this repo.

Support for RN 0.72.4

Is your feature request related to a problem? Please describe.
Might be, but probably not

Describe the solution you'd like
Support for using the SDK in RN. Should be fairly straight forward.

Describe alternatives you've considered
None

Additional context
To get it up and running in RN run the following:
Install "Nodify" to hack the RN installation

yarn add rn-nodeify
yarn add react-native-crypto

Hack the installation

yarn rn-nodeify --install url,events,https,http,util,stream,crypto,vm,buffer --hack --yarn
  1. Uncomment require('crypto') on shim.js (root of your project)
  2. Install pods for iOS cd ios && pod install && cd ../
  3. Create rn-cli.config.js
module.exports = {
  resolver: {
    extraNodeModules: require("node-libs-react-native"),
  },
}
  1. If you get issues with stream, install readable-stream and rebuild the project

Working example
Check out this GitHub repo

XdrWriterError [TypeError]: XDR Write Error: 0 is not a Hyper

Describe the bug
XdrWriterError [TypeError]: XDR Write Error: 0 is not a Hyper

We're getting this when trying to call .prepareTransaction or when calling .toXDR() on a transaction for soroban. This call works with soroban-client 0.5.0.

What version are you on?
soroban-client 0.6.1

To Reproduce
Steps to reproduce the behavior:

  1. github.com/blocktimefinancial/option
  2. See the opxpump.js code.
  3. Scroll down to line 128
  4. See error

Expected behavior
Print .toXDR() for the transaction and call .prepareTransaction

Additional context
Dump from pxpump.js which shows the parameter array is valid ScVal I128's
Converted quote:

[
  ChildUnion {
    _switch: ChildEnum { name: 'scvI128', value: 10 },
    _arm: 'i128',
    _armType: [class ChildStruct extends Struct] {
      structName: 'Int128Parts',
      _fields: [
        [
          'hi',
          [class Hyper extends XdrPrimitiveType] {
            MAX_VALUE: [Hyper],
            MIN_VALUE: [Hyper]
          }
        ],
        [
          'lo',
          [class UnsignedHyper extends XdrPrimitiveType] {
            MAX_VALUE: [UnsignedHyper],
            MIN_VALUE: [UnsignedHyper]
          }
        ]
      ]
    },
    _value: ChildStruct {
      _attributes: {
        lo: UnsignedHyper { _value: 1n },
        hi: UnsignedHyper { _value: 0n }
      }
    }
  },
  ChildUnion {
    _switch: ChildEnum { name: 'scvI128', value: 10 },
    _arm: 'i128',
    _armType: [class ChildStruct extends Struct] {
      structName: 'Int128Parts',
      _fields: [
        [
          'hi',
          [class Hyper extends XdrPrimitiveType] {
            MAX_VALUE: [Hyper],
            MIN_VALUE: [Hyper]
          }
        ],
        [
          'lo',
          [class UnsignedHyper extends XdrPrimitiveType] {
            MAX_VALUE: [UnsignedHyper],
            MIN_VALUE: [UnsignedHyper]
          }
        ]
      ]
    },
    _value: ChildStruct {
      _attributes: {
        lo: UnsignedHyper { _value: 42035n },
        hi: UnsignedHyper { _value: 0n }
      }
    }
  },
  ChildUnion {
    _switch: ChildEnum { name: 'scvI128', value: 10 },
    _arm: 'i128',
    _armType: [class ChildStruct extends Struct] {
      structName: 'Int128Parts',
      _fields: [
        [
          'hi',
          [class Hyper extends XdrPrimitiveType] {
            MAX_VALUE: [Hyper],
            MIN_VALUE: [Hyper]
          }
        ],
        [
          'lo',
          [class UnsignedHyper extends XdrPrimitiveType] {
            MAX_VALUE: [UnsignedHyper],
            MIN_VALUE: [UnsignedHyper]
          }
        ]
      ]
    },
    _value: ChildStruct {
      _attributes: {
        lo: UnsignedHyper { _value: 1684508428000n },
        hi: UnsignedHyper { _value: 0n }
      }
    }
  },
  ChildUnion {
    _switch: ChildEnum { name: 'scvI128', value: 10 },
    _arm: 'i128',
    _armType: [class ChildStruct extends Struct] {
      structName: 'Int128Parts',
      _fields: [
        [
          'hi',
          [class Hyper extends XdrPrimitiveType] {
            MAX_VALUE: [Hyper],
            MIN_VALUE: [Hyper]
          }
        ],
        [
          'lo',
          [class UnsignedHyper extends XdrPrimitiveType] {
            MAX_VALUE: [UnsignedHyper],
            MIN_VALUE: [UnsignedHyper]
          }
        ]
      ]
    },
    _value: ChildStruct {
      _attributes: {
        lo: UnsignedHyper { _value: 4n },
        hi: UnsignedHyper { _value: 0n }
      }
    }
  }
]
Creating contract transaction for cd0ca2f721d91df334b79fb1e043920919ed0c6b09f930af5048a50930fb7f44
Preparing transaction for cd0ca2f721d91df334b79fb1e043920919ed0c6b09f930af5048a50930fb7f44
/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:611
    if (!(value instanceof this)) throw new _errors__WEBPACK_IMPORTED_MODULE_1__.XdrWriterError(`${value} is not a Hyper`);                                        ^

XdrWriterError [TypeError]: XDR Write Error: 0 is not a Hyper
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:611:41)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1349:12)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1547:21)
    at VarArray.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1800:23)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1547:21)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1349:12)
    at VarArray.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1800:23)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1349:12)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1547:21)
    at Function.write (/home/lj/src/soroban/soroban-examples/option/pxpump/node_modules/stellar-base/node_modules/js-xdr/lib/xdr.js:1349:12)

XDR Read Error: Unknown OperationType member for value 24

I'm using the Typescript client and facing an issue on React side when invoking the write function of the contract.

Error:

Error: XDR Read Error: Unknown OperationType member for value 24
    at h (contentScript.min.js:1:13535)
(anonymous) @ contentScript.min.js:1

Code:

import * as SorobanClient from "soroban-client";
import * as exampleProject from "ExampleProject";
 let data = await exampleProject.setName(
       {
         value:  "John",
       }
     );

TypeError: XDR Read Error: invalid XDR contract typecast - source buffer not entirely consumed

Given this RPC Success response

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "status": "SUCCESS",
        "latestLedger": "693",
        "latestLedgerCloseTime": "1697055104",
        "oldestLedger": "8",
        "oldestLedgerCloseTime": "1697054415",
        "applicationOrder": 1,
        "envelopeXdr": "AAAAAgAAAABM/sh/7MYdZX9I0kK+VhhJCI08/3+br7+bnQTJloun1AAWz0YAAACKAAAALQAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGAAAAAAAAAABSmgtC9yp8u8OFpLCO1387pjYQMSE4QqM0zkuGahOgDoAAAAKZ2x5cGhfbWludAAAAAAABAAAABIAAAAAAAAAAEz+yH/sxh1lf0jSQr5WGEkIjTz/f5uvv5udBMmWi6fUAAAAAQAAABEAAAABAAAAAQAAABIAAAAAAAAAAEz+yH/sxh1lf0jSQr5WGEkIjTz/f5uvv5udBMmWi6fUAAAAEQAAAAEAAAACAAAAAwAAAAEAAAAQAAAAAQAAAAIAAAADAAAAAAAAAAMAAAACAAAAAwAAAAIAAAAQAAAAAQAAAAIAAAADAAAAAQAAAAMAAAADAAAAAwAAAAIAAAABAAAAAAAAAAAAAAABSmgtC9yp8u8OFpLCO1387pjYQMSE4QqM0zkuGahOgDoAAAAKZ2x5cGhfbWludAAAAAAABAAAABIAAAAAAAAAAEz+yH/sxh1lf0jSQr5WGEkIjTz/f5uvv5udBMmWi6fUAAAAAQAAABEAAAABAAAAAQAAABIAAAAAAAAAAEz+yH/sxh1lf0jSQr5WGEkIjTz/f5uvv5udBMmWi6fUAAAAEQAAAAEAAAACAAAAAwAAAAEAAAAQAAAAAQAAAAIAAAADAAAAAAAAAAMAAAACAAAAAwAAAAIAAAAQAAAAAQAAAAIAAAADAAAAAQAAAAMAAAADAAAAAwAAAAIAAAAAAAAAAQAAAAAAAAACAAAABgAAAAFKaC0L3Kny7w4WksI7XfzumNhAxIThCozTOS4ZqE6AOgAAABQAAAABAAAABwm4QqnhhER7LHwAF7mPfxQgpNvBS50I6/qsdaFm3RbQAAAABgAAAAYAAAABSmgtC9yp8u8OFpLCO1387pjYQMSE4QqM0zkuGahOgDoAAAAQAAAAAQ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jNM5LhmoToA6AAAAAQAAAAAAAAAEAAAADwAAAAljb2xvcl9vdXQAAAAAAAASAAAAAAAAAABM/sh/7MYdZX9I0kK+VhhJCI08/3+br7+bnQTJloun1AAAABIAAAAAAAAAAEz+yH/sxh1lf0jSQr5WGEkIjTz/f5uvv5udBMmWi6fUAAAAAwAAAAEAAAAQAAAAAQAAAAIAAAADAAAAAAAAAAMAAAACAAAAAAAAAAFKaC0L3Kny7w4WksI7XfzumNhAxIThCozTOS4ZqE6AOgAAAAEAAAAAAAAABAAAAA8AAAAJY29sb3Jfb3V0AAAAAAAAEgAAAAAAAAAATP7If+zGHWV/SNJCvlYYSQiNPP9/m6+/m50EyZaLp9QAAAASAAAAAAAAAABM/sh/7MYdZX9I0kK+VhhJCI08/3+br7+bnQTJloun1AAAAAMAAAACAAAAEAAAAAEAAAACAAAAAwAAAAEAAAADAAAAAwAAAAAAAAABSmgtC9yp8u8OFpLCO1387pjYQMSE4QqM0zkuGahOgDoAAAABAAAAAAAAAAMAAAAPAAAABm1pbnRlZAAAAAAAEgAAAAAAAAAATP7If+zGHWV/SNJCvlYYSQiNPP9/m6+/m50EyZaLp9QAAAABAAAADQAAACCmixjNV7Ls2GZnjueuZ5PLQAsaDXJ/tg3SfdICMuKTlgAAAA0AAAAgposYzVey7NhmZ47nrmeTy0ALGg1yf7YN0n3SAjLik5YAAAAA",
        "ledger": "693",
        "createdAt": "1697055104"
    }
}

I'm getting this error when using the built-in TS bindings for the contract trying to unwrap the response

soroban-client.js:236 Uncaught (in promise) TypeError: XDR Read Error: invalid XDR contract typecast - source buffer not entirely consumed
    at u2.ensureInputConsumed (soroban-client.js:236:57)
    at Function.fromXDR (soroban-client.js:375:26)
    at ContractSpec2.funcResToNative (soroban-client.js:13256:105)
    at parseResultXdr (index.js:152:34)
    at invoke (invoke.js:87:16)
    at async Contract.glyphMint (index.js:146:16)
    at async glyph_mint (+page.svelte:182:7)

Happy to provide additional code as/if needed. Just not sure what else may be helpful

1.0.0-beta.2 [AxiosError: Request failed with status code 405]

Describe the bug
Trying to pull account data using server.getAccount() returns an 405 Axios error

What version are you on?
"soroban-client": "^1.0.0-beta.2"

To Reproduce

  1. Create a new Node (or similar) project.
  2. Install the client
  3. Import the libraries and try to pull account data

Expected behavior
Returns: [AxiosError: Request failed with status code 405]

Additional context
Tried with the account: GDIZOAHWITGPTOCKF3S6TPFVSEEBTH32MAN3JYOYXDZLLS5K6IGYMRQ7 and the server URL: https://horizon-futurenet.stellar.org

Full test code*

const SorobanClient = require('soroban-client')
const server = new SorobanClient.Server('https://horizon-futurenet.stellar.org')

server.getAccount(account).then((data) => { 
     return data
})
 .catch(error => {
     return error
})

Potentially mishandling expired entries in pre-flight

Describe the bug
I'm trying to simulate a tx with the following envelope -

AAAAAgAAAACM6IR9GHiRoVVAO78JJNksy2fKDQNs2jBn8bacsRLcrAAAAGQAALDTAAAAQAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAGAAAAAAAAAAKAAAAEgAAAAEA1OFYsQR9ohuN4/lO01H0QR1gs0ydtgleqtNpia/V2AAAAA8AAAAEc3dhcAAAABIAAAAAAAAAAIzohH0YeJGhVUA7vwkk2SzLZ8oNA2zaMGfxtpyxEtysAAAAEgAAAAAAAAAA6BZdgAk/R2ZGwnrmk/TACHUraXX+fMDNz9uJ5e9/AJ0AAAASAAAAAfqr9cWsTR0VECjHorwcNTdllgfWPl95BDxSVggu+Z6lAAAAEgAAAAEN+Pv7pUMOoJ6rFclWu0CY3+3qzX6/IrjFY1zyC+VitQAAAAoAAAAAAAAAAAAAAAAAAAABAAAACgAAAAAAAAAAAAAAAAAAAAUAAAAKAAAAAAAAAAAAAAAAAAAABQAAAAoAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAA

and assembleTransaction throws the following error

which I think is from this line, because the preflight for this request returns no result key at all. Here is what I get from the simulate call -

{
    "error": "HostError: Error(Storage, MissingValue)\nDebugInfo not available\n",
    "transactionData": "",
    "events": null,
    "minResourceFee": "0",
    "cost": {
        "cpuInsns": "0",
        "memBytes": "0"
    },
    "latestLedger": "163263"
}

What version are you on?
0.9.2

To Reproduce
You can run this dapp or just the code that from the buildSwap call.
stellar/soroban-react-atomic-swap#4

Expected behavior
This was expired contract code. I'm not sure what the behavior should be, maybe if no results we can throw an error that lets the user know that they should restore the contract code.

Additional context
Slack thread about it - https://stellarfoundation.slack.com/archives/C030Z9EHVQE/p1690827512838819

Protocol 21 SDK Support

Protocol 21 SDK Support

Once voted in, the release of Protocol 21 will introduce following new CAPs:

  • CAP-51: Smart Contract Host Functionality
  • CAP-53: Separate host functions to extend the TTL for contract instance and contract code
  • CAP-54: Soroban refined VM instantiation cost model
  • CAP-55 : Soroban streamlined linking
  • CAP-56: Soroban intra-transaction module caching

XDR changes:

XDR update issue details - stellar/stellar-xdr@1a04392

Reference Implementations:
js-sdk - stellar/js-stellar-base#738

Soroban API Changes:

Breaking Changes:

Non Breaking changes:

New optional field in SimulateTransactionResponse which indicates how the state (ledger entries) will change as a result of the transaction execution.

StateDiff       []LedgerEntryDiff            `json:"stateDiff,omitempty"`   

type LedgerEntryDiff struct {
	Before string `json:"before,omitempty"` // LedgerEntry XDR in base64
	After  string `json:"after,omitempty"`  // LedgerEntry XDR in base64
}

New Ledger Range and Ledger Retention Window in getHealth Response


type HealthCheckResult struct {
	Status                string `json:"status"`
	LatestLedger          uint32 `json:"latestLedger"` // New
	OldestLedger          uint32 `json:"oldestLedger"` // New
	LedgerRetentionWindow uint32 `json:"ledgerRetentionWindow"` // New
}

Horizon API Changes:

  • There are no changes to Horizon APIs

Reference Implementations

Reference implementation authored by SDF:

You can follow each respective issue to its implementation PRs.

test issue

Describe the bug
A clear and concise description of what the bug is.

What version are you on?
Check yarn.lock or package-lock.json to find out precisely what version of the SDK you're running.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Additional context
Add any other context about the problem here.

js-soroban-sdk: Write docs, and get them building for this repo.

It would be good to have js-docs written/building/published for this client library. @tomerweller did some work on getting them building, but afaik none are written so far.

Primarily https://github.com/stellar/js-soroban-client/blob/main/src/server.ts, would be good to have some docs. Could be based on the soroban-rpc api docs.

Acceptance Criteria:
Document all the source code in js-soroban-client/src, and add auto-generating documentation from source code.

server.getAccount returns error: Cannot unmarshal key value

Describe the bug
Trying to fetch account ledger returns error.

What version are you on?
0.8.1

To Reproduce
Steps to reproduce the behavior:

  1. Start a node/expo/RN project
  2. Install Soroban Client
  3. Add shim
  4. Import shim.js

Example

const SorobanClient = require('soroban-client');
const server = new SorobanClient.Server('https://rpc-futurenet.stellar.org', { allowHttp: true })

// This works 
const keypair = SorobanClient.Keypair.fromSecret("SB42OYSI5NRMACBT6U3A6E2ZAIHXGK7433RVFIJXDY6CLJJAA6E56PYT");

//This fails
const account = await server.getAccount("GCDU6USHPKLZGIBYNLCZM7KRUVWLCUUHTTAS7YJWJ5MXFVWZNKTNH3WX");

Expected behavior
Calling the Soroban RPC (connecting) seems to work, but any interaction with the RPC (using ex getAccount) returns an error like this:

{"code":-32602,"message":"cannot unmarshal key value 0,0,0,0,0,0,0,0,135,79,82,71,122,151,147,32,56,106,197,150,125,81,165,108,177,82,135,156,193,47,225,54,79,89,114,214,217,106,166,211 at index 0"}

Additional context
Tried using RN/Expo & NodeJS using the official public SDF RPC

Server constructor error in browser v0.7.0

Describe the bug

  • soroban-client does not works with browser / Client Components
  • it did work in v0.5.1

So. I did two experiments:

  1. A brand new create-react-app
  2. A brand new create-next-app

In both I installed soroban-client 0.7.0. Without installing @soroban-react.

The code added is very simple:

import SorobanClient from "soroban-client";
const myServer = new SorobanClient.Server('https://soroban-rpc.stellar.org');
console.log(myServer)

With create-react-app: https://github.com/esteblock/create-react-app-soroban-client/tree/soroban-client%400.7.0
With next: https://github.com/esteblock/my-next-app-soroban-client/tree/soroban-client-0.7.0

With both of them I encounter the same error.

  1. With create-react-app I got:
Uncaught TypeError: soroban_client__WEBPACK_IMPORTED_MODULE_2___default(...).Server is not a constructor
    at ./src/App.js (App.js:5:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:62:1)
    at ./src/index.js (App.js:29:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at startup:7:1
    at startup:7:1
  1. With Next:
    At the begginig I was not having any problem. But I was not having any console.log in the browser either (Console.log in the console was working fine)
    This is because by default, Next.js uses Server Components.
    After I added "use client" at the top, to make it a Client Component I got the same problem:
Unhandled Runtime Error

TypeError: soroban_client__WEBPACK_IMPORTED_MODULE_1___default().Server is not a constructor
Source

src/app/page.tsx (6:17) @ <unknown>

  4 | import styles from './page.module.css'
  5 | 
> 6 | const myServer = new SorobanClient.Server('https://soroban-rpc.stellar.org');
    |                 ^
  7 | console.log(myServer)

So this enforces my theory about webpack changes introduced in v0.5.1...v0.6.0

Should we move to an issue in js-soroban-client?


When I install [email protected] works OK, both with create-react-app and next

https://github.com/esteblock/create-react-app-soroban-client/tree/soroban-client%400.5.1
https://github.com/esteblock/my-next-app-soroban-client/tree/soroban-client%400.5.1


Additional context
bug reported: paltalabs/soroban-react#30 and paltalabs/soroban-react#28 (comment)

Add ability to get expiration information

Is your feature request related to a problem? Please describe.
There's no obvious way to get the expiration ledger anymore.

Describe the solution you'd like
Server.getLedgerEntries et al. should allow a fetchExpiration parameter that will automatically include a fetch for the corresponding expiration ledger entry.

Describe alternatives you've considered
You can do this manually, but you need to know oddly-specific internals about Stellar to achieve it.

This could be done on the RPC side, but it may take longer and this can be a stop-gap.

Additional context
Workaround explanation.
Discord context.

XDR Read Error: Unknown OperationType member for value 24

I'm using the Typescript client and facing an issue on React side when invoking the write function of the contract.

Error:

Error: XDR Read Error: Unknown OperationType member for value 24
    at h (contentScript.min.js:1:13535)
(anonymous) @ contentScript.min.js:1

Code:

 let data = await exampleProject.setName(
       {
         value:  "John",
       }
     );

Decode XDR structures wherever possible.

Is your feature request related to a problem? Please describe.
It's annoying to decode base64-encoded XDR that comes from the raw JSON responses because:

(a) you don't necessarily know what the type is without referencing the documentation
(b) you need to actually write the decoding code and error-check it

Describe the solution you'd like
This should be part of Servers request methods: they should wrap and decode the raw responses wherever possible:

  • simulateTransaction
  • getTransaction
  • sendTransaction
  • getLedgerEntries
  • getLatestLedger
  • getEvents

Additional context
The work for this has been started in #127 and #129.

Please ๐Ÿ‘ or ๐Ÿ‘Ž as feedback for continuing this feature!

Error referencing 'FUTURENET' and 'SANDBOX' in SorobanClient.Networks

Describe the bug
I'm working on documentation for a project that uses soroban-client and I've encountered a problem with references to FUTURENET and SANDBOX in SorobanClient.Networks. When trying to reference these networks I get the following errors:

Property 'FUTURENET' does not exist on type 'typeof Networks'
Property 'SANDBOX' does not exist on type 'typeof Networks'

I've searched the documentation and repository but haven't found any mention of FUTURENET or SANDBOX that can help me solve this problem.

Have these constants been replaced or removed in a recent version? If so, what are the alternatives I should use instead? I would appreciate any help to resolve this issue.

What version are you on?
"0.8.0"

To Reproduce
Steps to reproduce the behavior:
This occurs even after successfully installing all the dependencies specified in the package.json of the packages and the root directory of the project.

Expected behavior
not having the error and successful reference

Additional context
"My dev environment includes Node.js v16.18.0, npm v8.19.2, on a MacOS Ventura. I'm using VSC as text editor."

Could not find a declaration file (TypeScript)

Hello.

I just upgraded to v0.6.0 and I encountered an issue regarding the absence of a TypeScript declaration file (.d.ts) for the module.

I get the error:

Could not find a declaration file for module 'soroban-client'. '/path/to/soroban-client/lib/index.js' implicitly has an 'any' type." 

Or, where can I find this declaration file?
Thanks!

TS Errors while requesting a contract's wasm code

Describe the bug
I'm trying to generate a contract's Wasm Code following the official docs. The problem I have is that TS is complaining about different issues specifically in this function:

function getLedgerKeyWasmId(contractCodeLedgerEntryData: string) {
  const entry = xdr.LedgerEntryData.fromXDR(
    contractCodeLedgerEntryData,
    'base64',
  );

  const instance = new xdr.ScContractInstance({
    executable: entry.contractData().val(),
  });

  const ledgerKey = xdr.LedgerKey.contractCode(
    new xdr.LedgerKeyContractCode({
      hash: xdr.ContractExecutable.contractExecutableWasm(instance.executable())
        .wasmHash()
        .instance()
        .executable()
        .wasmHash(),
    }),
  );

  return ledgerKey;
}

I receive 2 errors when creating the instance:

  • Property 'wasmHash' is missing in type 'ScVal' but required in type 'ContractExecutable'.
  • Even if I ignore or cast the executable as any I see the following error. Any idea what storage is in this case?
    • Property 'storage' is missing in type '{ executable: any; }' but required in type '{ executable: ContractExecutable; storage: ScMapEntry[]; }'

When getting the wasm hash I get 2 more errors:

  • First one is happening specifically here instance.executable()
    • Argument of type 'ContractExecutable' is not assignable to parameter of type 'Buffer'. Type 'ContractExecutable' is missing the following properties from type 'Buffer': write, toJSON, equals, compare, and 97 more.ts(2345)
  • Second one is happening when trying to call instace()
    • Property 'instance' does not exist on type 'Buffer'

In JS files the function is working properly so I'm not sure how should I procede using TypeScript.

What version are you on?

  • ^1.0.0-beta.3

To Reproduce
Steps to reproduce the behavior:

  1. Setup a TS project
  2. Follow the official docs to get the ledger key wasm id
  3. Your IDE should throw the errors mentioned above

Expected behavior

  • Shouldn't receive any errors because the JS version is working properly.

Happy to provide additional code or information if needed!

Importing this library from a plain javascript project depends on `tslib`

@accordeiro created a new javascript project from scratch. He installed soroban-client, and did npm install.

His index.js was:

var SorobanClient = require('soroban-client');
var server = new SorobanClient.Server('http://localhost:8000/soroban/rpc');

// get the sequence number for an account
server.getAccount(
  'GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW'
).then(function(r){ console.log(r); });

But when trying to run it, the error was:

> [email protected] start
> node index.js

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'tslib'
...

npm install tslib resolved the issue, but this shouldn't be a requirement for users.

From a quick google it looks like we should set importHelpers: false in this library's tsconfig.

Note: This might also affect js-stellar-sdk?

`prepareTransaction` requires networkPassphrase on Futurenet

Describe the bug
On Futurenet, when calling server.prepareTransaction, the second param of networkPassphrase is optional, but we've observed that it is required: https://github.com/stellar/js-soroban-client/blob/main/src/server.ts#L406

Callng server.prepareTransaction without the second param of networkPassphrase results in an error: {code: -32602, message: 'invalid parameters: [-32602] invalid parameters'}

Adding the networkPassphrase param appears to fix the issue.

This example also describes the second param as optional: https://github.com/stellar/js-soroban-client/blob/main/docs/reference/examples.md

What version are you on?
v0.4.0

To Reproduce
On Futurenet (https://horizon-futurenet.stellar.org/) and using the RPC Server URL `https://stellar-futurenet.4d63.com/soroban/rpc:

Try to build a tx similar to the example above. Observe that calling server.prepareTransaction with only the required param results in an error

Expected behavior
server.prepareTransaction should only require the transaction as a param

Feature Request: Add simulateTransaction and sendTransaction helper methods

It would be nice to abstract the simulateTransaction and sendTransaction workflows to simplify the dev experience. There is a nice attempt at this in the soroban-react repo (https://github.com/esteblock/soroban-react/tree/main/packages/contracts/src), but in my opinion, these helpers would be more useful separated from React concerns and handled by this library.

Engineers looking to add to existing Stellar projects as well as those starting from scratch will likely want access to these helper methods while not being strictly tied to the design patterns offered by soroban-react

js-soroban-sdk: transaction simulation failed

Describe the bug
I get an error transaction simulation failed when I simulate a transaction with one of operations restoreFootprint or bumpFootprintExpiration by method prepareTransaction. However, the simulation works correctly directly using fetch

What version are you on?
"soroban-client": "1.0.0-beta.3",

Creating a transaction:

getRestoreContractTx(publicKey: string, contract: Contract) {
      return this.server
            .getAccount(publicKey)
            .then((acc) => {
                return new SorobanClient.TransactionBuilder(acc, {
                    fee: BASE_FEE,
                    networkPassphrase: SorobanClient.Networks.TESTNET,
                })
                    .addOperation(SorobanClient.Operation.restoreFootprint({}))
                    .setSorobanData(
                        new SorobanClient.SorobanDataBuilder()
                            .setReadWrite([contact.getFootprint()[1]])
                            .build(),
                    )
                    .setTimeout(SorobanClient.TimeoutInfinite)
                    .build();
            })
    }

If I call the prepareTransaction from sdk I get an error transaction simulation failed

But if I do this, everything works:

prepareByFetch(tx): Promise<SorobanClient.Transaction> {
        const xdr = tx.toXDR();

        const requestObject = {
            jsonrpc: '2.0',
            method: 'simulateTransaction',
            id: 0,
            params: {
                transaction: xdr,
            },
        };

        return fetch(SOROBAN_SERVER, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestObject),
        })
            .then((res) => res.json())
            .then(({ result }) => {
                return assembleTransaction(tx, SorobanClient.Networks.TESTNET, result).build();
            });
    }

Map key `.get` doesn't match when the key is a complex type

Probably "because JavaScript" but when using the TS bindings when the return type contains a Map where the key is something like an Address providing that key in a .get method it won't return that value for that key.

Map keys likely need to be converted to strings or something other than a complex type where .get requests can fail when the underlying object is actually identical.

XDR Write Error: [object Object] is not a ScVal

I'm using the Typescript client and facing an issue on React side when invoking the write function of the contract.

Error:

caught (in promise) TypeError: XDR Write Error: [object Object] is not a ScVal
    at Function.value (soroban-client.min.js:2:1)
    at r.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at r.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at Function.value (soroban-client.min.js:2:1)
    at r.value (soroban-client.min.js:2:1)

Code Snippet:

import * as SorobanClient from "soroban-client";
import * as exampleProject from "ExampleProject"; // Typescript client

await exampleProject.invoke({
        method: "set_name",
        args: [
          SorobanClient.xdr.ScVal.scvString("Rust")
        ],
        fee: 100000,
      });

Contract Function:

 pub fn set_name(env: Env, value: String) {
        env.storage().instance().set(&NAME, &value);
    }

Map keys should be sorted alphabetically as Rust expects

When an argument is or contains a Map Rust expects the keys to be alphabetically ordered but JS doesn't enforce that. This will cause unclear errors right now. Soroban client likely should perform a key sort behind the scenes in order to avoid this issue.

js-soroban-sdk: getEvents method support

With the decision in stellar/go#4676 to not do push streaming, there is a risk that people will implement their own polling in the clients. This would likely be done in a rudimentary way, which would be unreliable, and cause us excessive load on soroban-rpc. We could add a streamEvents method in the js sdk, which would show a better way to do the polling (predict next block, and try w backoff/jitter, etc). If people use this ๐Ÿคž , it could reduce load on soroban-rpc.

scValToNative not working

Currently, I am trying to decode scVal to its native format, but it is not working. I followed these steps:

  1. I have a value scVal encoded as AAAADwAAAAdkZXBvc2l0AA== of type Sym.
  2. I attempted to change it to type SorobanClient.xdr.ScVal using the following code:
const svcValue = SorobanClient.xdr.ScVal.scvSymbol(
      "AAAADwAAAAdkZXBvc2l0AA==",
);

The result is as follows:

ChildUnion {
  _switch: ChildEnum { name: 'scvString', value: 14 },
  _arm: 'str',
  _armType: String { _maxLength: 4294967295 },
  _value: 'AAAADwAAAAdkZXBvc2l0AA=='
}
  1. However, when I use it with scValToNative, it returns the same old variable:
const scValDecode = await SorobanClient.scValToNative(svcValue);
console.log(scValDecode);

The result is AAAADwAAAAdkZXBvc2l0AA==. I attempted to decode it on website laboratory stellar, and the result was different: ZGVwb3NpdA==

Feature Request: Helper method to support for all Smart Contract data types

In trying to build a Transaction with a Contract operation with params, I found it difficult to convert JS primitives to certain data types (for ex: u64). We will need to support all possible data types used in smart contracts

Additionally, I found the existing pattern of creating SC Values to be a bit hard to follow and I suspect other FE eng's will have a similar issue. For ex: xdr.ScVal.scvObject( xdr.ScObject.scoVec([xdr.ScVal.scvSymbol('Invoker')]) )

We will ideally have helpers akin to numberToU64, etc. I see similar helper are found in @soroban-react/utils but this should be provided natively by this lib.

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.