Git Product home page Git Product logo

js-stellar-sdk's Introduction

Stellar
Creating equitable access to the global financial system

js-stellar-sdk

npm version Weekly Downloads Test Status

js-stellar-sdk is a JavaScript library for communicating with a Stellar Horizon server and Soroban RPC. It is used for building Stellar apps either on Node.js or in the browser, though it can be used in other environments with some tinkering.

It provides:

  • a networking layer API for Horizon endpoints (REST-based),
  • a networking layer for Soroban RPC (JSONRPC-based).
  • facilities for building and signing transactions, for communicating with a Stellar Horizon instance, and for submitting transactions or querying network history.

Jump to:

Installation

Using npm or yarn to include stellar-sdk in your own project:

npm install --save @stellar/stellar-sdk
# or
yarn add @stellar/stellar-sdk

Then, require or import it in your JavaScript code:

var StellarSdk = require('@stellar/stellar-sdk');
// or
import * as StellarSdk from '@stellar/stellar-sdk';

(Preferably, you would only import the pieces you need to enable tree-shaking and lower your final bundle sizes.)

Browsers

You can use a CDN:

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

Note that this method relies using a third party to host the JS library. This may not be entirely secure. You can self-host it via Bower:

bower install @stellar/stellar-sdk

and include it in the browser:

<script src="./bower_components/stellar-sdk/stellar-sdk.js"></script>
<script>
  console.log(StellarSdk);
</script>

If you don't want to use or install Bower, you can copy the packaged JS files from the Bower repo, or just build the package yourself locally (see Developing ➡️ Building) and copy the bundle.

Always make sure that you are using the latest version number. They can be found on the releases page in GitHub.

Usage

The usage documentation for this library lives in a handful of places:

You can also refer to:

  • the documentation for the Horizon REST API (if using the Horizon module) and
  • the documentation for Soroban RPC's API (if using the rpc module)

Usage with React-Native

  1. Install yarn add --dev rn-nodeify
  2. Add the following postinstall script:
yarn rn-nodeify --install url,events,https,http,util,stream,crypto,vm,buffer --hack --yarn
  1. Uncomment require('crypto') on shim.js
  2. react-native link react-native-randombytes
  3. Create file rn-cli.config.js
module.exports = {
  resolver: {
    extraNodeModules: require("node-libs-react-native"),
  },
};
  1. Add import "./shim"; to the top of index.js
  2. yarn add @stellar/stellar-sdk

There is also a sample that you can follow.

Note: Only the V8 compiler (on Android) and JSC (on iOS) have proper support for Buffer and Uint8Array as is needed by this library. Otherwise, you may see bizarre errors when doing XDR encoding/decoding such as source not specified.

Usage with Expo managed workflows

  1. Install yarn add --dev rn-nodeify
  2. Add the following postinstall script:
yarn rn-nodeify --install process,url,events,https,http,util,stream,crypto,vm,buffer --hack --yarn
  1. Add import "./shim"; to the your app's entry point (by default ./App.js)
  2. yarn add @stellar/stellar-sdk
  3. expo install expo-random

At this point, the Stellar SDK will work, except that StellarSdk.Keypair.random() will throw an error. To work around this, you can create your own method to generate a random keypair like this:

import * as Random from 'expo-random';
import { Keypair } from '@stellar/stellar-sdk';

const generateRandomKeypair = () => {
  const randomBytes = Random.getRandomBytes(32);
  return Keypair.fromRawEd25519Seed(Buffer.from(randomBytes));
};

Usage with CloudFlare Workers

Both eventsource (needed for streaming) and axios (needed for making HTTP requests) are problematic dependencies in the CFW environment. The experimental branch make-eventsource-optional is an attempt to resolve these issues.

It requires the following additional tweaks to your project:

  • the axios-fetch-adapter lets you use axios with fetch as a backend, which is available to CF workers
  • it only works with axios@"<= 1.0.0" versions, so we need to force an override into the underlying dependency
  • and this can be problematic with newer yarn versions, so we need to force the environment to use Yarn 1

In summary, the package.json tweaks look something like this:

"dependencies": {
  // ...
  "@stellar/stellar-sdk": "git+https://github.com/stellar/js-stellar-sdk#make-eventsource-optional",
  "@vespaiach/axios-fetch-adapter": "^0.3.1",
  "axios": "^0.26.1"
},
"overrides": {
  "@stellar/stellar-sdk": {
    "axios": "$axios"
  }
},
"packageManager": "[email protected]"

Then, you need to override the adapter in your codebase:

import { Horizon } from '@stellar/stellar-sdk';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

Horizon.AxiosClient.defaults.adapter = fetchAdapter as any;

// then, the rest of your code...

All HTTP calls will use fetch, now, meaning it should work in the CloudFlare Worker environment.

Developing

So you want to contribute to the library: welcome! Whether you're working on a fork or want to make an upstream request, the dev-test loop is pretty straightforward.

  1. Clone the repo:
git clone https://github.com/stellar/js-stellar-sdk.git
  1. Install dependencies inside js-stellar-sdk folder:
cd js-stellar-sdk
yarn
  1. Install Node 18

Because we support the oldest maintenance version of Node, please install and develop on Node 18 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 18

# if you've never installed 18 before you'll want to re-install yarn
npm 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 to catch any linting errors (in addition to making sure your text editor supports ESLint) and conform to the project's code style.

yarn fmt

Building

You can build the developer version (unoptimized, commented, with source maps, etc.) or the production bundles:

yarn build
# or
yarn build:prod

Testing

To run all tests:

yarn test

To run a specific set of tests:

yarn test:node
yarn test:browser
yarn test:integration

In order to have a faster test loop, these suite-specific commands do not build the bundles first (unlike yarn test). If you make code changes, you will need to run yarn build (or a subset like yarn build:node corresponding to the test suite) before running the tests again to see your changes.

To generate and check the documentation site:

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

# clone the base library for complete docs
git clone https://github.com/stellar/js-stellar-base

# 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

Publishing

For information on how to contribute or publish new versions of this software to npm, please refer to our contribution guide.

Miscellaneous

stellar-sdk vs stellar-base

stellar-sdk is a high-level library that serves as client-side API for Horizon and Soroban RPC, while `stellar-base is lower-level library for creating Stellar primitive constructs via XDR helpers and wrappers.

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

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

Important! The Node.js version of the stellar-base (stellar-sdk 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 stellar-sdk) will fallback to using the tweetnacl package implementation. If you are using them 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 StellarSdk.FastSigning variable will return true.

License

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

js-stellar-sdk's People

Contributors

abuiles avatar akuukis avatar andywer avatar bartekn avatar blaineheffron avatar brianebert avatar chadoh 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 thejollyrogers avatar tomerweller avatar vcarl avatar

Stargazers

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

Watchers

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

js-stellar-sdk's Issues

Problem access account information

I ran this code:

var StellarLib = require('./js-stellar-lib')

var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org/', secure:true, port: 3000});

server.accounts("gspbxqXqEUZkiCCEFFCN9Vu4FLucdjLLdLcsV6E82Qc1T7ehsTC")
    .then(function (accountResult) {
        console.log(accountResult);
    })
    .catch(function (err) {
        console.error(err.stack);
    })

which should have returned successfully because
curl -X GET 'https://horizon-testnet.stellar.org/accounts/gspbxqXqEUZkiCCEFFCN9Vu4FLucdjLLdLcsV6E82Qc1T7ehsTC' did so. Instead, I got

{ [NotFoundError: [object Object]]
  name: 'NotFoundError',
  message: 
   { type: 'not_found',
     title: 'Resource Missing',
     status: 404,
     detail: 'The resource at the url requested was not found.  This is usually occurs for one of two reasons:  The url requested is not valid, or no data in our database could be found with the parameters provided.',
     instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/hCYL7oezXs-581889' },
  data: 
   { data: 
      { type: 'not_found',
        title: 'Resource Missing',
        status: 404,
        detail: 'The resource at the url requested was not found.  This is usually occurs for one of two reasons:  The url requested is not valid, or no data in our database could be found with the parameters provided.',
        instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/hCYL7oezXs-581889' },
     status: 404,
     statusText: undefined,
     headers: 
      { 'content-type': 'application/problem+json',
        'x-ratelimit-limit': '3600',
        'x-ratelimit-remaining': '3590',
        'x-ratelimit-reset': '2877',
        date: 'Wed, 22 Jul 2015 00:29:51 GMT',
        'content-length': '385' },
     config: 
      { method: 'get',
        headers: {},
        transformRequest: [Object],
        transformResponse: [Object],
        url: 'https://horizon-testnet.stellar.org/:3000/ledgers',
        withCredentials: undefined } } }
undefined

As we discussed, this indicates two issues

  1. Hostname/URL/port handling not going well
  2. _parseResponse not error handling as intended

add a simple StellarSdk.resolveAddress(string)

This function should take in what a user would type into a send form for example a stellar address(ex. [email protected] ) or an accountID(ex. GCFRSK5SBUWDUUDZ7UPWD2WB5HZ7GLZSCQ2HTB3BMXSQ5VGB5PYRTRZP)
and spit out the accountID and memo resolved by federation or the given accountID or an error.

Simplified API for creating transactions

I propose to add a simplified API for creating a single operation transactions. New methods will be added to Server class and names representing operations that will be created:

var StellarSdk = require('stellar-sdk');
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.payment({
    source: 'SCZZ5GHGUAY4OVME5G5FRQEF5XWBWMAIISB3GXPU24F3VHLMU75NAM4S',
    destination: 'GC3FALN2RUQIYG2T4I5JIMSFQO6ZAVSRBC22E5TS3Q7Y7MUDIHM5X5M6',
    amount: '10',
    asset: StellarSdk.Asset.native()
  }).then(result => {
    console.log(result);
  });

is equivalent of the following code built using current API:

var StellarSdk = require('stellar-sdk');

var keypair = StellarSdk.Keypair.fromSeed('SCZZ5GHGUAY4OVME5G5FRQEF5XWBWMAIISB3GXPU24F3VHLMU75NAM4S');
var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

server.loadAccount(keypair.accountId())
  .then(function(source) {
    var transaction = new StellarSdk.TransactionBuilder(source)
      .addOperation(StellarSdk.Operation.payment({
        destination: 'GD6WU64OEP5C4LRBH6NK3MHYIA2ADN6K6II6EXPNVUR3ERBXT4AN4ACD',
        amount: "10",
        asset: StellarSdk.Asset.native()
      }))
      .build();

    transaction.sign(keypair);

    server.submitTransaction(transaction)
      .then(function(result) {
        console.log(result);
      });
  });

Ledger function overrrides ledger property of a transaction

Horizon response for transaction contains ledger property but _requestFnForLink function overrrides this with a function to call ledger endpoint.

var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');

server
  .transactions()
  .transaction('d03abccc9acd75a8c4ba16a6b31af1e81e4d5432c8a4f801f0ca87a8a35ea8df')
  .call()
  .then(function(transaction) {
    console.log(typeof transaction.ledger); // function
  })

Link helpers not working recursively

Steps to reproduce:

  1. Listen to effects for account stream
  2. in the effect handler use effect.operation() to navigate to the operation
  3. in the operation handler watch the operation. It does not contain a link helper to navigate to the transaction.

It appears that this is not a general issue of navigation from operation to transaction but rather using a linkhelper on a linkhelper.

It has already been analyzed by Scott:

[from slack] Looks like a bug to me. https://github.com/stellar/js-stellar-sdk/blob/master/src/call_builder.js#L69 should be followed by a call to _parseResponse to populate the link helpers on the result <<

Refactor `_parseRecord`

_parseRecord(json) {
        if (!json._links) {
            return json;
        }
        var self = this;
        var linkFn = function (link) {
            return function (opts) {
                if (link.template) {
                    let template = URITemplate(link.href);
                    return self._sendNormalRequest(URI(template.expand(opts)));
                } else {
                    return self._sendNormalRequest(URI(link.href));
                }
            };
        };
        Object.keys(json._links).map(function(value, index) {
            var link = json._links[value];
            json[value] = linkFn(link);
        });
        return json;
    }

would benefit from

  1. breaking out linkFn into something like
_requestFnForLink(link) {
  return opts => {
    ...just use this like normal in here...
  }
}
  1. getting rid of var self = this
  2. using lodash to map the values

Can't run node and browser tests independently

In order to just run the node tests, I have to run gulp clean test:run-server test:node
manually. After the tests are run, I have to kill the server too.

As the code says,

gulp.task('test', function(done) {
  runSequence('clean', 'test:run-server', 'test:node', 'test:browser', function (err) {
    server.kill();
    done();
  });
});

If I just run gulp test:node by itself, the server isn't created.

Weird transaction asset code

can someone research this transaction 2051301d6d63edb7e62890f81a01c92260e1066596d42281d8fb1ba5b1d5e4b3

assetCode: �����b�B�x�?#р���?�o� ������؀ d�������EURR�.���.[��Jw��[L�D��Vj�����=�waE�Hv��'����؀ @�kT�}�o��n��i�^i5[����z�]Y6@��{ae�Y?9�fA�T��<ύ�Z�Q4�H���c�� rO�

i get this javascript Error: Asset code must be 12 characters at max

Add "not found" errors to server.js

For requests for ledgers, transactions, and accounts that don't exist, we should return an error object that rather than the http response.

Bug in streaming -- no method "then"

In the /docs/README, there is an example of how to stream an account's transaction history. I tried the code below, basically copy-and-pasted from the example:

var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});

var streamingMessageHandler = function (message) {
    console.log(message);
};

server.accounts("gcEuhxySh58bKtCY3UPaWQDR7a1BzGB3ePdxc4UrinkBJyxESe", "transactions",
    {
        streaming: {
            onmessage: streamingMessageHandler
        }
    })
    .then(function (es) {
        console.log(es)
    })
    .catch(function (err) {
        console.log(err);
    });

and I get the error

/Users/diyang/workspace/client_endpoints_examples.js:89
    .then(function (es) {
     ^
TypeError: Object #<EventSource> has no method 'then'
    at Object.<anonymous> (/Users/diyang/workspace/client_endpoints_examples.js:89:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3

installation stellar-sdk failure

Trying to install stellar-sdk on a ubuntu 16.04 server the below error is displayed. I've installed stellar and horizon from source code. All other packages was installed using apt command.

thanks
Christian

npm install --save stellar-sdk

[email protected] install /home/stellar/test/node_modules/stellar-base/node_modules/ed25519
node-gyp rebuild

/bin/sh: 1: node: not found
gyp: Call to 'node -e "require('nan')"' returned exit status 127 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: gyp failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (/usr/share/node-gyp/lib/configure.js:354:16)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 4.4.0-22-generic
gyp ERR! command "/usr/bin/nodejs" "/usr/bin/node-gyp" "rebuild"
gyp ERR! cwd /home/stellar/test/node_modules/stellar-base/node_modules/ed25519
gyp ERR! node -v v4.2.6
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
[email protected] /home/stellar/test
└── (empty)

npm WARN [email protected] No repository field.
npm ERR! Linux 4.4.0-22-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "--save" "stellar-sdk"
npm ERR! node v4.2.6
npm ERR! npm v3.5.2
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-gyp rebuild
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ed25519 package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs ed25519
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls ed25519
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /home/stellar/test/npm-debug.log
npm ERR! code 1

Coveralls

  • Integrate Coveralls
  • Publish to npm
  • Travis Build
  • Slack github integration
  • jsdoc generation

Bug in .next() for js-stellar-lib

When I try to run code such as

server.ledgers()
  .then(function (page) {
    // page 1
    console.log(page.records)
    return page.next()
  })
  .then(function (page) {
    console.log(page.records)
  })
  .catch(function(err) {
    console.log(err)
  })

I get an error
[TypeError: Object #<Server> has no method '_sendLinkRequest']
instead of the next page of results.

Transactions not submitting in Node v0.10.35

When I try to submit a transaction using my system Node (v0.10.35), I get the error

{ type: 'https://stellar.org/horizon-errors/transaction_malformed',
  title: 'Transaction Malformed',
  status: 400,
  detail: 'TODO',
  instance: 'horizon-testnet-001.prd.stellar001.internal.stellar-ops.com/dZf7zwqQ7x-000442',
  extras: { envelope_xdr: '' } }

which is an error that's supposed to not happen in stellar-sdk 0.2.10+ (https://stellar-public.slack.com/archives/dev/p1443625140002129).

The transaction I was trying to submit worked for both Bartek and Iris.

When I switched to v0.10.40 on Iris's deduction, this problem disappears. We say that stellar-sdk should work as expected on Node v0.10+

LedgerCallBuilder#ledger should accept a Number type

LedgerCallBuilder#ledger currently requires its argument to be a string, but the JSON data for a ledger sequence is of type Number. To allow using the value from a response, match the API docs for Horizon, and just for least surprise, it would be nice if it accepted a number instead of just a string.

The actual error is when calling url.segment() in CallBuilder. It could most easily be solved by calling url.segmentCoded() instead. If that’s too permissive or broad, though, LedgerCallBuilder#ledger explicitly convert the input to a string.

should be able to pass an int to Memo.id()

quote from slack:
" However as you require the memoType id I have some trouble building the memo out of the federation response. StellarSdk.Memo.id(federationRecord.memo) throws error Expects a int64 as a string. Got 100001(edited)
ah ok it wants a string."

Eventsources and event replaying

Copy+paste from Slack

"OK, so I think the problem is in the eventsource polyfiller stellar-sdk is using. It reconnects every 45s, but the url isn’t updated with the new cursor information"
"the polyfiller updates a lastEventId query parameter, that is the same as what the cursor should have been but horizon only looks at cursor, so it resends all the previous events"

use full url in server constructor

Would it be possible to create a server with a full url like this:

let url = "https://horizon-testnet.stellar.org"
let server = new StellarSdk.Server(url);

By the way, the default port is no longer 3000 but 8000.
Thanks.

TypeError: msecs must be a number

From the doc, a mocha test case has been added to send a transaction:
https://github.com/FredericHeem/js-stellar-sdk/blob/master/test/functional/transaction_send.js

Here is the error:

  1) transactions end to end send transaction to itself, Invalid sequence number:
     Uncaught TypeError: msecs must be a number
      at TLSSocket.Socket.setTimeout (net.js:306:12)
      at ClientRequest.<anonymous> (_http_client.js:558:10)
      at tickOnSocket (_http_client.js:484:7)
      at onSocketNT (_http_client.js:496:5)

node version: v4.1.1

API TODO

  • Transaction/Transaction Builder/Operations
    • Operations
      • Payment Operation
        • Tests
      • Change Trust Operation
        • Tests
      • Allow Trust Operation
        • Tests
      • Set Option Operation
        • Inflation
        • AUTH flag
        • Add signers
        • Thresholds
        • Tests
      • Create Offer Operation [blocked on horizon]
        • Add offer
        • Update offer
        • Delete offer
        • Continuous fraction for exchange rate
        • Tests
    • Adding signatures
      • Tests
  • Accounts
    • Increment sequence number locally
    • Signing with master keypair
    • Multiple keypairs in an account
    • Thresholds
    • Tests
  • Currency
    • Support native currency
    • Support ISO currency
    • Tests
  • Server API
    • Ledgers
      • /ledgers
      • /ledgers/:id
      • /ledgers/:id/transactions
      • /ledgers/:id/operations
      • /ledgers/:id/effects not implemented on horizon
      • /ledgers/:id/payments not implemented on horizon
    • Accounts
      • /Accounts
      • /Accounts/:id
      • /Accounts/:id/transactions
      • /Accounts/:id/effects not implemented on horizon
      • /Accounts/:id/operations not implemented on horizon
    • Transactions
      • /Transactions
      • /Transactions/:id
      • /Transactions/:id/effects not implemented on horizon
      • /Transactions/:id/operations not implemented on horizon
    • Operations
      • /operations
      • /operations/:id not implemented on horizon
      • /operations/:id/effects not implemented on horizon
    • Payments
      • /payments not implemented on horizon
    • Submit Transaction
    • Streaming requests
    • Streaming tests working in browser
    • HAL links as functions
    • change max min to time bounds

Getting the next page of payments does not work as expected

Getting the next page of accounts works as expected, but not payments.

var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});

server.accounts()
  .then(function (accountResults) {
    //page 1
    console.log(accountResults.records)
    return accountResults.next()
  })
  .then(function (accountResults) {
    //page 2
    console.log(accountResults.records)
  })
  .catch(function (err) {
    console.log(err)
  })

works, but not

var StellarLib = require('./js-stellar-lib')
var server = new StellarLib.Server({hostname:'horizon-testnet.stellar.org', secure:true, port:443});

server.payments()
  .then(function (paymentResults) {
    //page 1
    console.log(paymentResults.records)
    return paymentResults.next()
  })
  .then(function (paymentResults) {
    //page 2
    console.log(paymentResults.records)
  })
  .catch(function (err) {
    console.log(err)
  })

returns the error

[TypeError: Cannot read property 'records' of undefined]

Streaming: surface `err` events as errors?

This one’s a bit interesting. If you stream payments from a non-existent account, like so:

var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
var paymentStream = server
  .payments()
  .forAccount('GAA2LEFZVJU63SP5B7C77AJXT5PRYDVCWGLFKNVMJTLZU4IXAMXGAATZ')
  .stream({
    onmessage: function(payment) { /* handle payment */ },
    onerror: function(error) {
      console.log('Error:', error);
    }
  });

You'll just get a message like Error: Event { type: 'error' } over and over again. There’s more useful info in the response, though:

retry: 1000
event: open
data: "hello"

event: err
data: sql: no rows in result set

…but to get it, you'd also have to listen for the err event:

var paymentStream = [payments query].stream({
    onmessage: function(payment) { /* handle payment */ },
    onerror: function(error) {}
  });
paymentStream.addEventListener('err', function(event) {
  console.log('Error:', event.data);
});

…which is both a little inconvenient and hard to discover (no docs). It might be nice if the onerror handler was called when err events occur (even though EventSource.onerror is generally intended for network errors). Barring that, this should at least be documented—and perhaps the object passed to CallBuilder.stream() could take a handler for it.

Additionally, the server closes the connection after this error, but that just causes the event stream to attempt to reconnect and you get the same error over and over again (the basic idea of the EventSource API is that any kind disconnect not explicitly requested by the client was a network interruption of some sort and a reconnect should be attempted).

I imagine there could be some rare scenario where Horizon might send an error in the middle of the stream and keep going, but maybe if an err event is immediately followed by a disconnect, the client should hang up? Or Horizon could perhaps send some kind of "end of stream" event to indicate that the client should hang up/not retry.

It would be really helpful if `Server.loadAccount()` should return all account data

A new user would [probably quite reasonably] assume calling the following would get them an object with all the data about an account (e.g. balances, signers, flags, inflation destination, etc):

var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server.loadAccount(sourcePublicKey).then(function(account) { ... });

But while it does retrieve all that info from the server, most of it (excepting the sequence number) gets thrown out. To get that info, a user is forced to go through a rather obtuse call:

var server = new StellarSdk.Server('https://horizon-testnet.stellar.org');
server
  .accounts()
  .accountId(id)
  .call()
  .then(function(rawAccountData) { ... });

I’m pretty sure the above is only documented in one spot (https://www.stellar.org/developers/horizon/reference/accounts-single.html, then switch to the JS example), while the rest of the less hidden JS documentation never describes doing anything even along these lines to get account data.

The new getting started docs will demonstrate the above, but it sure would be simpler to suggest simply calling Server.loadAccount(accountId)!

(As a bonus, it’d be great if the balance objects had Asset instances. Not sure there are any other types it would make sense to instantiate, though.)

Feature parity with Horizon

Implement features in js-stellar-lib until parity is reached.

  • submit transaction
  • receive transaction
  • balance inquiry
  • transaction history
  • establish trust line

stellarSdk.Server internal `this` usage is not compatible with promises

Looks like stellarSdk.Server internal this usage is not compatible with promises, because if server object is passed to promises it doesn't recognize its internal properties. Example below.

I suppose it is low priority, because it is easy work around that. But it took a long time to figure out what exactly caused the error because those two versions looks like and imo should be identical.

var horizon = new stellarSdk.Server('https://horizon-testnet.stellar.org');

/* ... */

horizon.loadAccount(myAccountId)
    .then(function(myAccount){
        te = new stellarSdk.TransactionBuilder(myAccount)
            /* ... add operatins ... */
            .build();
        te.sign(stellarSdk.Keypair.fromSeed(mySeed));
        return te;
    })
    /* ... do other stuff on te ... */
    .then(function(te){ return horizon.submitTransaction(te); })  // <--- This workaround works
    // .then(horizon.submitTransaction)  // <--- This instead would throw error as below
    .then( /* handle response */ )
    .catch( /* handle error */ );
Cannot read property &#39;serverURL&#39; of undefined
    at submitTransaction ($PATH/node_modules/stellar-sdk/lib/server.js:91:50)
    at tryCatcher ($PATH/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler ($PATH/node_modules/bluebird/js/release/promise.js:504:31)
    at Promise._settlePromise ($PATH/node_modules/bluebird/js/release/promise.js:561:18)
    at Promise._settlePromise0 ($PATH/node_modules/bluebird/js/release/promise.js:606:10)
    at Promise._settlePromises ($PATH/node_modules/bluebird/js/release/promise.js:685:18)
    at Async._drainQueue ($PATH/node_modules/bluebird/js/release/async.js:138:16)
    at Async._drainQueues ($PATH/node_modules/bluebird/js/release/async.js:148:10)
    at Immediate.Async.drainQueues [as _onImmediate] ($PATH/node_modules/bluebird/js/release/async.js:17:14)
    at tryOnImmediate (timers.js:534:15)
    at processImmediate [as _immediateCallback] (timers.js:514:5)

Line 91 in server.js

var promise = axios.post(URI(this.serverURL).path("transactions").toString(), "tx=" + tx, { timeout: SUBMIT_TRANSACTION_TIMEOUT }).then(function (response) {

Integrate URI.js

http://medialize.github.io/URI.js/

Instead of manually construction urls (such as _buildEndpointPath), we should use a helper library, such as uri.js.

It's brittle and potentially insecure to modify urls as strings, and so we should avoid it if possible

Add default export

In Node.js, I can't do this:

import StellarSdk from 'stellar-sdk';

Instead, I have to do this (which is annoying):

import {Account, TransactionBuilder, Memo} from 'stellar-sdk';

Helper for resolving federated names to plain address

Support for clients to resolve federated names according to the federation concept.
For my needs the following setup would be sufficient:

  • one string as input parameter (which could be any arbitrary string)
  • if input has fedaration format (detect by * or @) -> lookup (type=name)
  • if lookup succeeded return the lookup result. Otherwise return the input

As a general library, a more general approach might be reasonable however:

  • support id and txid types as well
  • some return value (resolved, not in federation format, lookup did not find the entry, ...)

Not parsing links from streaming messages

The code for stream() in call_builder.js is such:

    stream(options) {
        this.checkFilter();
        var es = new EventSource(this.url.toString());
        es.onmessage = function (message) {
            var result = message.data ? JSON.parse(message.data) : message;
            options.onmessage(result);
        };
        es.onerror = options.onerror;
        return es;
    }

It parses the message from the stream as JSON, but doesn't run parseRecord on it to get the links. This means that there's no way to follow the links when streaming.

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.