New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

stellar-sdk

Package Overview
Dependencies
Maintainers
1
Versions
166
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

stellar-sdk - npm Package Compare versions

Comparing version 0.2.5 to 0.2.6

docs/accounts.md

378

docs/readme.md

@@ -7,113 +7,101 @@ ---

js-stellar-sdk facilitates Stellar transaction submission and client integration
with the [Stellar Horizon API Server](https://github.com/stellar/horizon).
with the [Stellar Horizon API Server](https://github.com/stellar/horizon). It has two main uses, [querying Horizon](#querying-horizon) and [building, signing, and submitting transactions](#building-transactions) to the Stellar network.
- [Building and Installing]()
- [Using JS-Stellar-SDK]()
- [Transactions](#transactions)
- [Sequence Numbers](#sequence-numbers)
- [Multisig](#multisig)
- [Examples](#examples)
- [Creating a simple payment transaction](#creating-a-simple-payment-transaction)
- [Loading an account's transaction history](#loading-an-account-transaction-history)
- [Streaming an accounts transaction history](#streaming-an-accounts-transaction-history)
- [Creating a multi-signature account](#creating-a-multi-signature-account)
[Building and installing js-stellar-sdk](../README.md)<br>
[Examples of using js-stellar-sdk](./examples.md)
# Querying Horizon
js-stellar-sdk gives you access to all the endpoints exposed by Horizon.
## Building and Installing
## Building the Requests
js-stellar-sdk uses the [Builder Pattern](https://en.wikipedia.org/wiki/Builder_pattern) to create the requests to send
to Horizon. Starting with a [server](./server.md) object, you can chain methods together to generate a query.
See the reference documentation for what methods are possible.
```js
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'horizon-testnet.stellar.org', secure: true, port: 443});
// get a list of transactions that occurred in ledger 1400
server.transactions()
.forLedger(1400)
.call().then(function(r){ console.log(r); });
Please refer to the project-level [README](../README.md) for information on how to build and install JS-Stellar-SDK.
// get a list of transactions submitted by a particular account
server.transactions()
.forAccount('GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW')
.call().then(function(r){ console.log(r); });
```
## Using js-stellar-sdk
Once the request is built, it can be invoked with `.call()` or with `.stream()`. `call()` will return a
[promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to the response given by Horizon.
### Transactions
## Streaming Request
Many requests can be invoked with `stream()`. Instead of returning a promise like `call()` does, `.stream()` will return an `EventSource`.
Horizon will start sending responses from either the beginning of time or from the point specified with `.cursor()`.
See the [Horizon reference guide](https://stellar.org/developers/horizon/reference/) for which endpoints support streaming.
For example, to log anytime a particular account makes a transaction:
[Transactions](https://github.com/stellar/docs/blob/master/concepts/transactions.md) are the commands that modify the network. They include sending payments, making account configuration changes, etc.
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'horizon-testnet.stellar.org', secure: true, port: 443});
var lastCursor=0; // or load where you left off
Transactions are made up of one or more operations. In js-stellar-sdk, operations are added chronologically and applied in that order. Each operation is described below:
var txHandler = function (txResponse) {
console.log(txResponse);
};
* **Create Account** - Create an account with a given starting balance.
* **Payment** - Send an payment of a given currency to an existing destination account, optionally through a path.
* **Path Payment** - Sends a currency to a destination with using a different source currency.
* **Create Offer** - Creates, updates, or deletes an offer for the account.
* **Set Options** - Set or clear Account flags, set inflation destination, or add new signers.
* **Change Trust** - Add or remove a trust line from one account to another.
* **Allow Trust** - Authorize another account to hold your credits.
* **Account Merge** - Merge your account's balance into another account, deleting it.
var es = server.transactions()
.forAccount(accountAddress)
.cursor(lastCursor)
.stream({
onmessage: txHandler
})
```
For more, please refer to the [operations documentation](https://github.com/stellar/docs/blob/master/concepts/operations.md).
## Handling Responses
Transactions are performed by source accounts that will use up a sequence number and be charged a fee for the transaction. Each operation also has a source account, which defaults to the transaction's source account.
### XDR
The transaction endpoints will return some fields in raw [XDR](https://stellar.org/developers/horizon/guides/xdr/)
form. You can convert this XDR to JSON using the `.fromXDR()` method.
For a transaction to be valid, it must be signed by at least one public key -- generally, the source account's public key. That key must meet the thresholds for the operations in the transaction. For more on signatures and thresholds, please see the [multi-sig documentation](https://github.com/stellar/docs/blob/master/concepts/multi-sig.md).
Here is an example re-writing the txHandler from above to print the XDR fields as JSON.
```javascript
var txHandler = function (txResponse) {
console.log( JSON.stringify(StellarSdk.xdr.TransactionEnvelope.fromXDR(txResponse.envelope_xdr, 'base64')) );
console.log( JSON.stringify(StellarSdk.xdr.TransactionResult.fromXDR(txResponse.result_xdr, 'base64')) );
console.log( JSON.stringify(StellarSdk.xdr.TransactionMeta.fromXDR(txResponse.result_meta_xdr, 'base64')) );
};
### Sequence Numbers
```
There are strict rules governing a transaction's sequence number. That sequence number has to match the sequence number stored by the source account or else the transaction is invalid. After the transaction is submitted and applied to the ledger, the source account's sequence number increases by 1.
There are two ways to ensure correct sequence numbers:
### Following links
The links returned with the Horizon response are converted into functions you can call on the returned object.
This is allows you to just use `.next()` to page through results. It also makes fetching additional info like in the following example easy:
1. Read the source account's sequence number before submitting a transaction
2. Manage the sequence number locally
```js
server.payments()
.limit(1)
.call()
.then(function(response){
// will follow the transactions link returned by Horizon
response.records[0].transaction().then(function(txs){
console.log(txs);
});
});
```
Robust applications should use the second method. During periods of high transaction throughput, fetching a source account's sequence number from the network may not return the correct value. So, if you're submitting many transactions quickly, you will want to keep track of the sequence number locally.
# Building Transactions
### Multi-sig
[Transactions](https://stellar.org/developers/learn/concepts/transactions/) are the commands that modify the state of the ledger.
They include sending payments, creating offers, making account configuration changes, etc.
Transactions require signatures for authorization, and generally they only require one. However, you can exercise more control over authorization and set up complex schemes by increasing the number of signatures a transaction requires. For more, please consult the [multi-sig documentation](https://github.com/stellar/docs/blob/master/concepts/multi-sig.md). A summary of the documentation follows:
Transactions are made up of one or more [operations](https://stellar.org/developers/learn/concepts/operations/). When building a
transaction you add operations sequentially. All operations either succeed or they all fail when the transaction is applied.
Every operation has a threshold level of either low, medium, or high. Let's say that you want to send a payment, a medium threshold operation. You can set, using the operation `setOptions`, the exact threshold value every medium operation stemming from your account will have. For example, if your medium threshold level is 3, the payment you send to your friend Zoe will have a threshold level of 3. The weights of every key that signs the transaction must add up to at least 3. So, if your signing key only has a weight of 2, you need an additional signer to authorize the payment.
## Examples
### Creating a simple payment transaction
js-stellar-sdk exposes the [`TransactionBuilder`](https://github.com/stellar/js-stellar-base/blob/master/src/transaction_builder.js) class from js-stellar-base. This class allows you to add operations to a transaction via chaining. You can construct a new `TransactionBuilder`, call `addOperation`, call `addSigner`, and `build()` yourself transaction. Below are two examples, reflecting the two ways of dealing with the [sequence number](#sequence-number).
```javascript
/**
* In this example, we'll create and a submit a payment. We'll use a
* locally managed sequence number.
*/
var StellarSdk = require('js-stellar-sdk')
// create the server connection object
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
// create Account object using locally tracked sequence number
var an_account = new StellarSdk.Account("GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ", localSequence);
var transaction = new StellarSdk.TransactionBuilder(an_account)
.addOperation(StellarSdk.Operation.payment({
destination: "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW",
asset: StellarSdk.Asset.native(),
amount: "20000000"
}))
.addSigner(StellarSdk.Keypair.fromSeed(seedString)) // sign the transaction
.build();
server.submitTransaction(transaction)
.catch(function (err){
console.log(err);
});
```
```javascript
/**
* In this example, we'll create and submit a payment, but we'll read the
* sequence number from the server.
*/
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
server.loadAccount("GCEZWKCA5VLDNRLN3RPRJMRZOX3Z6G5CHCGSNFHEYVXM3XOJMDS674JZ")
.then(function (account) {
// build the transaction
var transaction = new StellarSdk.TransactionBuilder(account)
// this operation funds the new account with XLM
.addOperation(StellarSdk.Operation.payment({
```js
var transaction = new StellarSdk.TransactionBuilder(account)
// add a payment operation to the transaction
.addOperation(StellarSdk.Operation.payment({
destination: "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW",

@@ -123,114 +111,60 @@ asset: StellarSdk.Asset.native(),

}))
.addSigner(StellarSdk.Keypair.fromSeed(seedString)) // sign the transaction
.build();
return server.submitTransaction(transaction);
})
.then(function (transactionResult) {
console.log(transactionResult);
})
.catch(function (err) {
console.error(err);
});
// add a set options operation to the transaction
.addOperation(StellarSdk.Operation.setOptions({
signer: {
address: secondAccountAddress,
weight: 1
}
}))
```
### Loading an account transaction history
Every transactions has a source [account](https://stellar.org/developers/learn/concepts/accounts/). This is the account
that pays the [fee](https://stellar.org/developers/learn/concepts/fees/) and uses up a sequence number for the transaction.
Each operation also has a source account, which defaults to the transaction's source account.
Let's say you want to look at an account's transaction history. You can use the `transactions()` command and pass in the account address to `forAccount` as the resource you're interested in.
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
## Sequence Numbers
server.transactions()
.forAccount(accountAddress)
.call()
.then(function (page) {
// page 1
console.log(page.records);
return page.next();
})
.then(function (page) {
// page 2
console.log(page.records);
})
.catch(function (err) {
console.log(err);
});
```
### Streaming an accounts transaction history
There are strict rules governing a transaction's sequence number. That sequence number has to match the sequence number
stored by the source account or else the transaction is invalid. After the transaction is submitted and applied to the
ledger, the source account's sequence number increases by 1.
js-stellar-sdk provides streaming support for Horizon endpoints using `EventSource`. For example, pass a streaming `onmessage` handler to an account's transaction call:
There are two ways to ensure correct sequence numbers:
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
1. Read the source account's sequence number before submitting a transaction
2. Manage the sequence number locally
var streamingMessageHandler = function (message) {
console.log(message);
};
During periods of high transaction throughput, fetching a source account's sequence number from the network may not return
the correct value. So, if you're submitting many transactions quickly, you will want to keep track of the sequence number locally.
var es = server.transactions()
.forAccount(accountAddress)
.stream({
onmessage: streamingMessageHandler
})
```
## Adding Memos
For more on streaming events, please check out [our guide](https://github.com/stellar/horizon/blob/master/docs/guide/responses.md) and this [guide to server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
Transactions can contain a "memo" field to attach additional information to the transaction. You set this as one of the
options to the [TransactionBuilder](https://github.com/stellar/js-stellar-base/blob/master/src/transaction_builder.js).
### Creating a multi-signature account
## Signing and Multi-sig
Transactions require signatures for authorization, and generally they only require one. However, you can exercise more
control over authorization and set up complex schemes by increasing the number of signatures a transaction requires. For
more, please consult the [multi-sig documentation](https://stellar.org/developers/learn/concepts/multi-sig/).
In this example, we will:
* Add a second signer to an account
* Set the account's masterkey weight and threshold levels
* Create a multi signature transaction that sends a payment
You add signatures to a transaction with the `addSigner()` function. You can chain multiple `addSigner()` calls together.
#### Add a secondary key to the account
```javascript
## Submitting
Once you have built your transaction you can submit it to the Stellar network with `Server.submitTransaction()`.
```js
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
var server = new StellarSdk.Server({hostname:'horizon-testnet.stellar.org', secure: true, port: 443});
server.loadAccount(firstAccountAddress)
.then(function (account) {
// build the transaction
var transaction = new StellarSdk.TransactionBuilder(account)
.addOperation(StellarSdk.Operation.setOptions({
signer: {
address: secondAccountAddress,
weight: 1
}
}))
.addSigner(StellarSdk.Keypair.fromSeed(firstAccountSeedString))
.build();
return server.submitTransaction(transaction);
})
.then(function (transactionResult) {
console.log(transactionResult);
})
.catch(function (err) {
console.log(err);
});
```
var transaction = new StellarSdk.TransactionBuilder(account)
// this operation funds the new account with XLM
.addOperation(StellarSdk.Operation.payment({
destination: "GASOCNHNNLYFNMDJYQ3XFMI7BYHIOCFW3GJEOWRPEGK2TDPGTG2E5EDW",
asset: StellarSdk.Asset.native(),
amount: "20000000"
}))
.addSigner(StellarSdk.Keypair.fromSeed(seedString)) // sign the transaction
.build();
#### Set Master key weight and threshold weights
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
server.loadAccount(firstAccountAddress)
.then(function (account) {
// build the transaction
var transaction = new StellarSdk.TransactionBuilder(account)
// this operation funds the new account with XLM
.addOperation(StellarSdk.Operation.setOptions({
masterWeight : 1,
lowThreshold: 1,
medThreshold: 2,
highThreshold: 1
}))
.addSigner(StellarSdk.Keypair.fromSeed(firstAccountSeedString))
.build();
return server.submitTransaction(transaction);
})
server.submitTransaction(transaction)
.then(function (transactionResult) {

@@ -240,85 +174,9 @@ console.log(transactionResult);

.catch(function (err) {
console.log(err);
});
```
#### Create a multi-sig payment transaction
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
server.loadAccount(firstAccountAddress)
.then(function (account) {
// build the transaction
var transaction = new StellarSdk.TransactionBuilder(account)
// this operation funds the new account with XLM
.addOperation(StellarSdk.Operation.payment({
destination: destinationAccount, // can be any destination account
asset: StellarSdk.Asset.native(),
amount: "20000000"
}))
.addSigner(StellarSdk.Keypair.fromSeed(firstAccountSeedString))
.addSigner(StellarSdk.Keypair.fromSeed(secondAccountSeedString))
.build();
return server.submitTransaction(transaction);
})
.then(function (transactionResult) {
console.log(transactionResult);
})
.catch(function (err) {
console.error(err);
});
```
#### Multi-sig RPC
Let's say you are a second signer on an account and don't want to share your keypair with the source account. Instead, you want to control your keypair on a remote server or separate process. If the source account can send you the envelope of the transaction it wants to submit, you can sign the envelope remotely like so:
```javascript
var StellarSdk = require('js-stellar-sdk')
var server = new StellarSdk.Server({hostname:'example-horizon-server.com', secure: true, port: 443});
// Let's say this function exists on the remote server
var fakeRPCSigner = function(transactionEnvelope) {
var RPCKeypair = StellarSdk.Keypair.fromSeed(secondAccountSeedString);
var transaction = new StellarSdk.Transaction(transactionEnvelope);
// If needed, the remote server can check the transaction
// for whatever requirements before signing. For example,
// let's check to make sure the transaction is only submitting one operation
if (transaction.operations.length > 1) {
throw new Error("Only can sign one payment operation");
}
// Now let's check to make sure the operation is a low-enough payment
var operation = transaction.operations[0];
if (operation.type != "payment" || operation.amount > 1000000) {
throw new Error("Payment type not payment or amount too high");
}
// All the above is optional. This function only needs to sign
transaction.sign({RPCKeypair});
return transaction.toEnvelope();
};
// Build the transation on the local server
var transaction = new StellarSdk.TransactionBuilder(rootAccount)
// this operation funds the new account with XLM
.addOperation(StellarSdk.Operation.payment({
destination: destAccountAddress,
asset: StellarSdk.Asset.native(),
amount: "20000000"
}))
.addSigner(StellarSdk.Keypair.fromSeed(rootAccountSeedString))
.build();
try {
var RPCSignedTransactionEnvelope = fakeRPCSigner(transaction.toEnvelope());
server.submitTransaction(new StellarSdk.Transaction(RPCSignedTransactionEnvelope))
.catch(function (err) {
console.log(err);
});
} catch (err) {
throw new Error("Unable to authorize transaction");
}
```

@@ -143,3 +143,2 @@ "use strict";

next: function () {
console.log(_this);
return _this._sendNormalRequest(URI(json._links.next.href)).then(function (r) {

@@ -146,0 +145,0 @@ return _this._toCollectionPage(r);

@@ -37,2 +37,4 @@ "use strict";

var FriendbotBuilder = require("./friendbot_builder").FriendbotBuilder;
var _stellarBase = require("stellar-base");

@@ -121,3 +123,3 @@

* Should be
* offers('accounts', accountID) or
* offers('accounts', accountID)
*/

@@ -153,2 +155,7 @@

},
friendbot: {
value: function friendbot(address) {
return new FriendbotBuilder(URI(this.serverURL), address);
}
},
loadAccount: {

@@ -170,18 +177,2 @@

}
},
friendbot: {
value: function friendbot(address) {
var url = URI(this.serverURL).path("friendbot").addQuery("addr", address);
return this._sendNormalRequest(url);
}
},
_sendNormalRequest: {
value: function _sendNormalRequest(url) {
// To fix: #15 Connection Stalled when making multiple requests to the same resource
url.addQuery("c", Math.random());
var promise = axios.get(url.toString()).then(function (response) {
return response.data;
})["catch"](this._handleNetworkError);
return toBluebird(promise);
}
}

@@ -188,0 +179,0 @@ });

{
"name": "stellar-sdk",
"version": "0.2.5",
"version": "0.2.6",
"description": "stellar-sdk is a library for working with the Stellar Horizon server.",

@@ -19,3 +19,3 @@ "main": "lib/index.js",

},
"author": "Andrew Rogers <andrew@stellar.org>",
"author": "Stellar Development Foundation <hello@stellar.org>",
"license": "Apache 2.0",

@@ -27,5 +27,5 @@ "bugs": {

"devDependencies": {
"babel": "^4.7.16",
"babel-core": "^4.7.16",
"babel-loader": "^4.3.0",
"babel": "~5.8.23",
"babel-core": "~5.8.25",
"babel-loader": "~5.3.2",
"body-parser": "^1.12.2",

@@ -50,3 +50,3 @@ "chai": "^2.2.0",

"jshint-stylish": "^1.0.1",
"karma": "^0.12.31",
"karma": "^0.13.2",
"karma-chrome-launcher": "^0.1.7",

@@ -57,3 +57,3 @@ "karma-firefox-launcher": "^0.1.4",

"karma-sinon-chai": "^0.3.0",
"karma-webpack": "^1.5.0",
"karma-webpack": "^1.7.0",
"mocha": "~1.17.1",

@@ -60,0 +60,0 @@ "run-sequence": "^1.0.2",

@@ -106,3 +106,2 @@ import {NotFoundError, NetworkError, BadRequestError} from "./errors";

next: () => {
console.log(this);
return this._sendNormalRequest(URI(json._links.next.href))

@@ -109,0 +108,0 @@ .then(r => this._toCollectionPage(r));

@@ -12,2 +12,3 @@ import {TransactionResult} from "./transaction_result";

import {EffectCallBuilder} from "./effect_call_builder";
import {FriendbotBuilder} from "./friendbot_builder";
import {xdr, Account} from "stellar-base";

@@ -81,3 +82,3 @@

* Should be
* offers('accounts', accountID) or
* offers('accounts', accountID)
*/

@@ -104,2 +105,6 @@ offers(resource, ...resourceParams) {

friendbot(address) {
return new FriendbotBuilder(URI(this.serverURL), address);
}
/**

@@ -122,17 +127,4 @@ * Fetches an account's most current state in the ledger and then creates and returns

friendbot(address) {
var url = URI(this.serverURL).path("friendbot").addQuery("addr", address);
return this._sendNormalRequest(url);
}
_sendNormalRequest(url) {
// To fix: #15 Connection Stalled when making multiple requests to the same resource
url.addQuery('c', Math.random());
var promise = axios.get(url.toString())
.then(response => response.data)
.catch(this._handleNetworkError);
return toBluebird(promise);
}
}

@@ -1,2 +0,2 @@

global.StellarSdk = require('../../src/index');
global.StellarSdk = require('../../lib/index'); // Use compiled code because it will be used by node
global.chai = require('chai');

@@ -3,0 +3,0 @@ global.sinon = require('sinon');

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc