mirror of
https://github.com/Xahau/xahau.js.git
synced 2025-11-05 21:35:49 +00:00
Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc24f6afe0 | ||
|
|
f7dac6ab25 | ||
|
|
4b4fc36ebd | ||
|
|
7626ea5ed8 | ||
|
|
7061e9afe4 | ||
|
|
a124635c2c | ||
|
|
c9704137b7 | ||
|
|
ab8d75d3cc | ||
|
|
5e720891f5 |
@@ -1,3 +1,12 @@
|
||||
##0.15.0
|
||||
**Breaking Changes**
|
||||
+ ["servers" parameter changed to single "server"](https://github.com/ripple/ripple-lib/commit/7061e9afe46f0682254d098adeff3dd7157521a1)
|
||||
|
||||
**Changes**
|
||||
+ [fix handling memos in prepareSettings](https://github.com/ripple/ripple-lib/commit/c9704137b7b538e8dbf31c483bcdcf2dcfd7cd75)
|
||||
+ [Docs: SusPay warnings, offline mode, and other tweaks](https://github.com/ripple/ripple-lib/commit/4b4fc36ebd93f1360781a65f2869bd2c4f0a5093)
|
||||
+ [Fix prepareOrderCancellation documentation](https://github.com/ripple/ripple-lib/commit/5e720891f579fd73d43c64e5ec519d9121023c10)
|
||||
|
||||
##0.14.0
|
||||
**Breaking Changes**
|
||||
+ [prepareOrderCancellation now takes orderCancellation specification](https://github.com/ripple/ripple-lib/commit/7f33d8a71e56289e5a5e0ead1c74f75ebcde72bc)
|
||||
|
||||
122
docs/index.md
122
docs/index.md
@@ -4,6 +4,7 @@
|
||||
|
||||
- [Introduction](#introduction)
|
||||
- [Boilerplate](#boilerplate)
|
||||
- [Offline functionality](#offline-functionality)
|
||||
- [Basic Types](#basic-types)
|
||||
- [Ripple Address](#ripple-address)
|
||||
- [Account Sequence Number](#account-sequence-number)
|
||||
@@ -83,7 +84,7 @@ Use the following [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_c
|
||||
const {RippleAPI} = require('ripple-lib');
|
||||
|
||||
const api = new RippleAPI({
|
||||
servers: ['wss://s1.ripple.com'] //Public rippled server hosted by Ripple, Inc.
|
||||
server: 'wss://s1.ripple.com' // Public rippled server hosted by Ripple, Inc.
|
||||
});
|
||||
api.connect().then(() => {
|
||||
/* insert code here */
|
||||
@@ -94,7 +95,7 @@ api.connect().then(() => {
|
||||
|
||||
RippleAPI is designed to work in [NodeJS](https://nodejs.org) (version `0.12.0` or greater) using [Babel](https://babeljs.io/) for [ECMAScript 6](https://babeljs.io/docs/learn-es2015/) support.
|
||||
|
||||
The code samples in this documentation are written in ES6, but `RippleAPI` will work with ES5 also. Regardless of whether you use ES5 or ES6, the methods that return promises will return [ES6-style promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise_).
|
||||
The code samples in this documentation are written in ES6, but `RippleAPI` will work with ES5 also. Regardless of whether you use ES5 or ES6, the methods that return promises will return [ES6-style promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
|
||||
|
||||
<aside class="notice">
|
||||
All the code snippets in this documentation assume that you have surrounded them with this boilerplate.
|
||||
@@ -106,17 +107,21 @@ If you omit the "catch" section, errors may not be visible.
|
||||
|
||||
### Parameters
|
||||
|
||||
The RippleAPI constructor optionally takes one argument, an object with the following options:
|
||||
|
||||
Name | Type | Description
|
||||
---- | ---- | -----------
|
||||
authorization | string | *Optional* Username and password for HTTP basic authentication to the rippled server in the format **username:password**.
|
||||
feeCushion | number | *Optional* Factor to multiply estimated fee by to provide a cushion in case the required fee rises during submission of a transaction. Defaults to `1.2`.
|
||||
proxy | uri string | *Optional* URI for HTTP/HTTPS proxy to use to connect to the rippled server.
|
||||
proxyAuthorization | string | *Optional* Username and password for HTTP basic authentication to the proxy in the format **username:password**.
|
||||
servers | array\<uri string\> | *Optional* Array of rippled servers to connect to. Currently only one server is supported.
|
||||
server | uri string | *Optional* URI for rippled websocket port to connect to. Must start with `wss://` or `ws://`.
|
||||
timeout | integer | *Optional* Timeout in milliseconds before considering a request to have failed.
|
||||
trace | boolean | *Optional* If true, log rippled requests and responses to stdout.
|
||||
trustedCertificates | array\<string\> | *Optional* Array of PEM-formatted SSL certificates to trust when connecting to a proxy. This is useful if you want to use a self-signed certificate on the proxy server. Note: Each element must contain a single certificate; concatenated certificates are not valid.
|
||||
|
||||
If you omit the `server` parameter, RippleAPI operates [offline](#offline-functionality).
|
||||
|
||||
|
||||
### Installation ###
|
||||
|
||||
@@ -134,6 +139,34 @@ Instead of using babel-node in production, we recommend using Babel to transpile
|
||||
</aside>
|
||||
|
||||
|
||||
## Offline functionality
|
||||
|
||||
RippleAPI can also function without internet connectivity. This can be useful in order to generate secrets and sign transactions from a secure, isolated machine.
|
||||
|
||||
To instantiate RippleAPI in offline mode, use the following boilerplate code:
|
||||
|
||||
```javascript
|
||||
const {RippleAPI} = require('ripple-lib');
|
||||
|
||||
const api = new RippleAPI();
|
||||
/* insert code here */
|
||||
```
|
||||
|
||||
Methods that depend on the state of the Ripple Consensus Ledger are unavailable in offline mode. To prepare transactions offline, you **must** specify the `fee`, `sequence`, and `maxLedgerVersion` parameters in the [transaction instructions](#transaction-instructions). The following methods should work offline:
|
||||
|
||||
* [preparePayment](#preparepayment)
|
||||
* [prepareTrustline](#preparetrustline)
|
||||
* [prepareOrder](#prepareorder)
|
||||
* [prepareOrderCancellation](#prepareordercancellation)
|
||||
* [prepareSettings](#preparesettings)
|
||||
* [prepareSuspendedPaymentCreation](#preparesuspendedpaymentcreation)
|
||||
* [prepareSuspendedPaymentCancellation](#preparesuspendedpaymentcancellation)
|
||||
* [prepareSuspendedPaymentExecution](#preparesuspendedpaymentexecution)
|
||||
* [sign](#sign)
|
||||
* [generateAddress](#generateaddress)
|
||||
* [computeLedgerHash](#computeledgerhash)
|
||||
|
||||
|
||||
# Basic Types
|
||||
|
||||
## Ripple Address
|
||||
@@ -211,6 +244,8 @@ Type | Description
|
||||
[suspendedPaymentCancellation](#suspended-payment-cancellation) | A `suspendedPaymentCancellation` transaction unlocks the funds in a suspended payment and sends them back to the creator of the suspended payment, but it will only work after the suspended payment expires.
|
||||
[suspendedPaymentExecution](#suspended-payment-execution) | A `suspendedPaymentExecution` transaction unlocks the funds in a suspended payment and sends them to the destination of the suspended payment, but it will only work if the cryptographic condition is provided.
|
||||
|
||||
The three "suspended payment" transaction types are not supported by the production Ripple peer-to-peer network at this time. They are available for testing purposes if you [configure RippleAPI](#boilerplate) to connect to the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) instead.
|
||||
|
||||
## Transaction Flow
|
||||
|
||||
Executing a transaction with `RippleAPI` requires the following four steps:
|
||||
@@ -246,7 +281,7 @@ maxLedgerVersion | integer | *Optional* The highest ledger version that the tran
|
||||
maxLedgerVersionOffset | integer | *Optional* Offset from current legder version to highest ledger version that the transaction can be included in.
|
||||
sequence | [sequence](#account-sequence-number) | *Optional* The initiating account's sequence number for this transaction.
|
||||
|
||||
We recommended that you specify a `maxLedgerVersion` because without it there is no way to know that a failed transaction will never succeeed in the future. It is impossible for a transaction to succeed after the network ledger version exceeds the transaction's `maxLedgerVersion`.
|
||||
We recommended that you specify a `maxLedgerVersion` so that you can quickly determine that a failed transaction will never succeeed in the future. It is impossible for a transaction to succeed after the network ledger version exceeds the transaction's `maxLedgerVersion`. If you omit `maxLedgerVersion`, the "prepare*" method automatically supplies a `maxLedgerVersion` equal to the current ledger plus 3, which it includes in the return value from the "prepare*" method.
|
||||
|
||||
## Transaction ID
|
||||
|
||||
@@ -281,12 +316,12 @@ Name | Type | Description
|
||||
source | object | The source of the funds to be sent.
|
||||
*source.* address | [address](#ripple-address) | The address to send from.
|
||||
*source.* amount | [laxAmount](#amount) | An exact amount to send. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with source.maxAmount)
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
*source.* maxAmount | [laxAmount](#amount) | The maximum amount to send. (This field is exclusive with source.amount)
|
||||
destination | object | The destination of the funds to be sent.
|
||||
*destination.* address | [address](#ripple-address) | The address to receive at.
|
||||
*destination.* amount | [laxAmount](#amount) | An exact amount to deliver to the recipient. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with destination.minAmount).
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
*destination.* address | [address](#ripple-address) | The address to send to.
|
||||
*destination.* minAmount | [laxAmount](#amount) | The minimum amount to be delivered. (This field is exclusive with destination.amount)
|
||||
allowPartialPayment | boolean | *Optional* A boolean that, if set to true, indicates that this payment should go through even if the whole amount cannot be delivered because of a lack of liquidity or funds in the source account account
|
||||
@@ -348,7 +383,14 @@ ripplingDisabled | boolean | *Optional* If true, payments cannot ripple through
|
||||
"qualityIn": 0.91,
|
||||
"qualityOut": 0.87,
|
||||
"ripplingDisabled": true,
|
||||
"frozen": false
|
||||
"frozen": false,
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -435,7 +477,14 @@ transferRate | number,null | *Optional* The fee to charge when users transfer t
|
||||
|
||||
```json
|
||||
{
|
||||
"domain": "ripple.com"
|
||||
"domain": "ripple.com",
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -449,11 +498,11 @@ Name | Type | Description
|
||||
source | object | Fields pertaining to the source of the payment.
|
||||
*source.* address | [address](#ripple-address) | The address to send from.
|
||||
*source.* maxAmount | [laxAmount](#amount) | The maximum amount to send. (This field is exclusive with source.amount)
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
destination | object | Fields pertaining to the destination of the payment.
|
||||
*destination.* address | [address](#ripple-address) | The address to receive at.
|
||||
*destination.* amount | [laxAmount](#amount) | An exact amount to deliver to the recipient. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with destination.minAmount).
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
allowCancelAfter | date-time string | *Optional* If present, the suspended payment may be cancelled after this time.
|
||||
allowExecuteAfter | date-time string | *Optional* If present, the suspended payment can not be executed before this time.
|
||||
digest | string | *Optional* If present, proof is required upon execution.
|
||||
@@ -539,7 +588,7 @@ proof | string | *Optional* A value that produces the digest when hashed. It mus
|
||||
|
||||
`connect(): Promise<void>`
|
||||
|
||||
Tells the RippleAPI instance to connect to its server(s).
|
||||
Tells the RippleAPI instance to connect to its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
@@ -557,7 +606,7 @@ See [Boilerplate](#boilerplate) for code sample.
|
||||
|
||||
`disconnect(): Promise<void>`
|
||||
|
||||
Tells the RippleAPI instance to disconnect from its server(s).
|
||||
Tells the RippleAPI instance to disconnect from its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
@@ -575,7 +624,7 @@ See [Boilerplate](#boilerplate) for code sample
|
||||
|
||||
`isConnected(): boolean`
|
||||
|
||||
Checks if the RippleAPI instance is connected to its server(s).
|
||||
Checks if the RippleAPI instance is connected to its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
@@ -673,7 +722,7 @@ return api.getServerInfo().then(info => {/* ... */});
|
||||
|
||||
`getFee(): Promise<number>`
|
||||
|
||||
Returns the estimated transaction fee for the server(s) the RippleAPI instance is connected to.
|
||||
Returns the estimated transaction fee for the rippled server the RippleAPI instance is connected to.
|
||||
|
||||
### Parameters
|
||||
|
||||
@@ -1527,12 +1576,12 @@ Name | Type | Description
|
||||
source | object | Properties of the source of the payment.
|
||||
*source.* address | [address](#ripple-address) | The address to send from.
|
||||
*source.* amount | [laxAmount](#amount) | An exact amount to send. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with source.maxAmount)
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*source.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
*source.* maxAmount | [laxAmount](#amount) | The maximum amount to send. (This field is exclusive with source.amount)
|
||||
destination | object | Properties of the destination of the payment.
|
||||
*destination.* address | [address](#ripple-address) | The address to receive at.
|
||||
*destination.* amount | [laxAmount](#amount) | An exact amount to deliver to the recipient. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with destination.minAmount).
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.
|
||||
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
|
||||
*destination.* address | [address](#ripple-address) | The address to send to.
|
||||
*destination.* minAmount | [laxAmount](#amount) | The minimum amount to be delivered. (This field is exclusive with destination.amount)
|
||||
paths | string | The paths of trustlines and orders to use in executing the payment.
|
||||
@@ -2826,7 +2875,14 @@ const trustline = {
|
||||
"qualityIn": 0.91,
|
||||
"qualityOut": 0.87,
|
||||
"ripplingDisabled": true,
|
||||
"frozen": false
|
||||
"frozen": false,
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
};
|
||||
return api.preparePayment(address, trustline).then(prepared =>
|
||||
{/* ... */});
|
||||
@@ -2835,7 +2891,7 @@ return api.preparePayment(address, trustline).then(prepared =>
|
||||
|
||||
```json
|
||||
{
|
||||
"txJSON": "{\"Flags\":2149711872,\"TransactionType\":\"TrustSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"LimitAmount\":{\"value\":\"10000\",\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\"},\"QualityIn\":910000000,\"QualityOut\":870000000,\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"txJSON": "{\"TransactionType\":\"TrustSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"LimitAmount\":{\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\",\"value\":\"10000\"},\"Flags\":2149711872,\"QualityIn\":910000000,\"QualityOut\":870000000,\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
@@ -2864,7 +2920,7 @@ instructions | [instructions](#transaction-instructions) | *Optional* Instructio
|
||||
This method returns a promise that resolves with an object with the following structure:
|
||||
|
||||
<aside class="notice">
|
||||
All "prepare" methods have the same return type.
|
||||
All "prepare*" methods have the same return type.
|
||||
</aside>
|
||||
|
||||
Name | Type | Description
|
||||
@@ -2912,7 +2968,7 @@ return api.prepareOrder(address, order)
|
||||
|
||||
## prepareOrderCancellation
|
||||
|
||||
`prepareOrderCancellation(address: string, sequence: number, instructions: Object): Promise<Object>`
|
||||
`prepareOrderCancellation(address: string, orderCancellation: Object, instructions: Object): Promise<Object>`
|
||||
|
||||
Prepare an order cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
@@ -2929,7 +2985,7 @@ instructions | [instructions](#transaction-instructions) | *Optional* Instructio
|
||||
This method returns a promise that resolves with an object with the following structure:
|
||||
|
||||
<aside class="notice">
|
||||
All "prepare" methods have the same return type.
|
||||
All "prepare*" methods have the same return type.
|
||||
</aside>
|
||||
|
||||
Name | Type | Description
|
||||
@@ -2997,7 +3053,14 @@ instructions | object | The instructions for how to execute the transaction afte
|
||||
```javascript
|
||||
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
|
||||
const settings = {
|
||||
"domain": "ripple.com"
|
||||
"domain": "ripple.com",
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
};
|
||||
return api.prepareSettings(address, settings)
|
||||
.then(prepared => {/* ... */});
|
||||
@@ -3006,7 +3069,14 @@ return api.prepareSettings(address, settings)
|
||||
|
||||
```json
|
||||
{
|
||||
"domain": "ripple.com"
|
||||
"domain": "ripple.com",
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -3017,6 +3087,8 @@ return api.prepareSettings(address, settings)
|
||||
|
||||
Prepare a suspended payment creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
Name | Type | Description
|
||||
@@ -3087,6 +3159,8 @@ return api.prepareSuspendedPaymentCreation(address, suspendedPaymentCreation).th
|
||||
|
||||
Prepare a suspended payment cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
Name | Type | Description
|
||||
@@ -3142,6 +3216,8 @@ return api.prepareSuspendedPaymentCancellation(address, suspendedPaymentCancella
|
||||
|
||||
Prepare a suspended payment execution transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
Name | Type | Description
|
||||
|
||||
@@ -6,7 +6,7 @@ Use the following [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_c
|
||||
const {RippleAPI} = require('ripple-lib');
|
||||
|
||||
const api = new RippleAPI({
|
||||
servers: ['wss://s1.ripple.com'] //Public rippled server hosted by Ripple, Inc.
|
||||
server: 'wss://s1.ripple.com' // Public rippled server hosted by Ripple, Inc.
|
||||
});
|
||||
api.connect().then(() => {
|
||||
/* insert code here */
|
||||
@@ -17,7 +17,7 @@ api.connect().then(() => {
|
||||
|
||||
RippleAPI is designed to work in [NodeJS](https://nodejs.org) (version `0.12.0` or greater) using [Babel](https://babeljs.io/) for [ECMAScript 6](https://babeljs.io/docs/learn-es2015/) support.
|
||||
|
||||
The code samples in this documentation are written in ES6, but `RippleAPI` will work with ES5 also. Regardless of whether you use ES5 or ES6, the methods that return promises will return [ES6-style promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise_).
|
||||
The code samples in this documentation are written in ES6, but `RippleAPI` will work with ES5 also. Regardless of whether you use ES5 or ES6, the methods that return promises will return [ES6-style promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
|
||||
|
||||
<aside class="notice">
|
||||
All the code snippets in this documentation assume that you have surrounded them with this boilerplate.
|
||||
@@ -29,8 +29,12 @@ If you omit the "catch" section, errors may not be visible.
|
||||
|
||||
### Parameters
|
||||
|
||||
The RippleAPI constructor optionally takes one argument, an object with the following options:
|
||||
|
||||
<%- renderSchema('input/api-options.json') %>
|
||||
|
||||
If you omit the `server` parameter, RippleAPI operates [offline](#offline-functionality).
|
||||
|
||||
|
||||
### Installation ###
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`connect(): Promise<void>`
|
||||
|
||||
Tells the RippleAPI instance to connect to its server(s).
|
||||
Tells the RippleAPI instance to connect to its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`disconnect(): Promise<void>`
|
||||
|
||||
Tells the RippleAPI instance to disconnect from its server(s).
|
||||
Tells the RippleAPI instance to disconnect from its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`getFee(): Promise<number>`
|
||||
|
||||
Returns the estimated transaction fee for the server(s) the RippleAPI instance is connected to.
|
||||
Returns the estimated transaction fee for the rippled server the RippleAPI instance is connected to.
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<% include introduction.md.ejs %>
|
||||
<% include boilerplate.md.ejs %>
|
||||
<% include offline.md.ejs %>
|
||||
<% include basictypes.md.ejs %>
|
||||
<% include transactions.md.ejs %>
|
||||
<% include specifications.md.ejs %>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`isConnected(): boolean`
|
||||
|
||||
Checks if the RippleAPI instance is connected to its server(s).
|
||||
Checks if the RippleAPI instance is connected to its rippled server.
|
||||
|
||||
### Parameters
|
||||
|
||||
|
||||
27
docs/src/offline.md.ejs
Normal file
27
docs/src/offline.md.ejs
Normal file
@@ -0,0 +1,27 @@
|
||||
## Offline functionality
|
||||
|
||||
RippleAPI can also function without internet connectivity. This can be useful in order to generate secrets and sign transactions from a secure, isolated machine.
|
||||
|
||||
To instantiate RippleAPI in offline mode, use the following boilerplate code:
|
||||
|
||||
```javascript
|
||||
const {RippleAPI} = require('ripple-lib');
|
||||
|
||||
const api = new RippleAPI();
|
||||
/* insert code here */
|
||||
```
|
||||
|
||||
Methods that depend on the state of the Ripple Consensus Ledger are unavailable in offline mode. To prepare transactions offline, you **must** specify the `fee`, `sequence`, and `maxLedgerVersion` parameters in the [transaction instructions](#transaction-instructions). The following methods should work offline:
|
||||
|
||||
* [preparePayment](#preparepayment)
|
||||
* [prepareTrustline](#preparetrustline)
|
||||
* [prepareOrder](#prepareorder)
|
||||
* [prepareOrderCancellation](#prepareordercancellation)
|
||||
* [prepareSettings](#preparesettings)
|
||||
* [prepareSuspendedPaymentCreation](#preparesuspendedpaymentcreation)
|
||||
* [prepareSuspendedPaymentCancellation](#preparesuspendedpaymentcancellation)
|
||||
* [prepareSuspendedPaymentExecution](#preparesuspendedpaymentexecution)
|
||||
* [sign](#sign)
|
||||
* [generateAddress](#generateaddress)
|
||||
* [computeLedgerHash](#computeledgerhash)
|
||||
|
||||
@@ -13,7 +13,7 @@ Prepare an order transaction. The prepared transaction must subsequently be [sig
|
||||
This method returns a promise that resolves with an object with the following structure:
|
||||
|
||||
<aside class="notice">
|
||||
All "prepare" methods have the same return type.
|
||||
All "prepare*" methods have the same return type.
|
||||
</aside>
|
||||
|
||||
<%- renderSchema('output/prepare.json') %>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## prepareOrderCancellation
|
||||
|
||||
`prepareOrderCancellation(address: string, sequence: number, instructions: Object): Promise<Object>`
|
||||
`prepareOrderCancellation(address: string, orderCancellation: Object, instructions: Object): Promise<Object>`
|
||||
|
||||
Prepare an order cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
@@ -13,7 +13,7 @@ Prepare an order cancellation transaction. The prepared transaction must subsequ
|
||||
This method returns a promise that resolves with an object with the following structure:
|
||||
|
||||
<aside class="notice">
|
||||
All "prepare" methods have the same return type.
|
||||
All "prepare*" methods have the same return type.
|
||||
</aside>
|
||||
|
||||
<%- renderSchema("output/prepare.json") %>
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
Prepare a suspended payment cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
<%- renderSchema('input/prepare-suspended-payment-cancellation.json') %>
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
Prepare a suspended payment creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
<%- renderSchema('input/prepare-suspended-payment-creation.json') %>
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
Prepare a suspended payment execution transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
|
||||
|
||||
**Caution:** Suspended Payments are currently available on the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) only.
|
||||
|
||||
### Parameters
|
||||
|
||||
<%- renderSchema('input/prepare-suspended-payment-execution.json') %>
|
||||
|
||||
@@ -15,6 +15,8 @@ Type | Description
|
||||
[suspendedPaymentCancellation](#suspended-payment-cancellation) | A `suspendedPaymentCancellation` transaction unlocks the funds in a suspended payment and sends them back to the creator of the suspended payment, but it will only work after the suspended payment expires.
|
||||
[suspendedPaymentExecution](#suspended-payment-execution) | A `suspendedPaymentExecution` transaction unlocks the funds in a suspended payment and sends them to the destination of the suspended payment, but it will only work if the cryptographic condition is provided.
|
||||
|
||||
The three "suspended payment" transaction types are not supported by the production Ripple peer-to-peer network at this time. They are available for testing purposes if you [configure RippleAPI](#boilerplate) to connect to the [Ripple Test Net](https://ripple.com/build/ripple-test-net/) instead.
|
||||
|
||||
## Transaction Flow
|
||||
|
||||
Executing a transaction with `RippleAPI` requires the following four steps:
|
||||
@@ -44,7 +46,7 @@ Transaction instructions indicate how to execute a transaction, complementary wi
|
||||
|
||||
<%- renderSchema("objects/instructions.json") %>
|
||||
|
||||
We recommended that you specify a `maxLedgerVersion` because without it there is no way to know that a failed transaction will never succeeed in the future. It is impossible for a transaction to succeed after the network ledger version exceeds the transaction's `maxLedgerVersion`.
|
||||
We recommended that you specify a `maxLedgerVersion` so that you can quickly determine that a failed transaction will never succeeed in the future. It is impossible for a transaction to succeed after the network ledger version exceeds the transaction's `maxLedgerVersion`. If you omit `maxLedgerVersion`, the "prepare*" method automatically supplies a `maxLedgerVersion` equal to the current ledger plus 3, which it includes in the return value from the "prepare*" method.
|
||||
|
||||
## Transaction ID
|
||||
|
||||
|
||||
2
npm-shrinkwrap.json
generated
2
npm-shrinkwrap.json
generated
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.14.0",
|
||||
"version": "0.15.0",
|
||||
"dependencies": {
|
||||
"ajv": {
|
||||
"version": "1.4.8",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ripple-lib",
|
||||
"version": "0.14.0",
|
||||
"version": "0.15.0",
|
||||
"license": "ISC",
|
||||
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
|
||||
"files": [
|
||||
|
||||
144
src/api.js
Normal file
144
src/api.js
Normal file
@@ -0,0 +1,144 @@
|
||||
/* @flow */
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable max-len */
|
||||
// Enable core-js polyfills. This allows use of ES6/7 extensions listed here:
|
||||
// https://github.com/zloirock/core-js/blob/fb0890f32dabe8d4d88a4350d1b268446127132e/shim.js#L1-L103
|
||||
/* eslint-enable max-len */
|
||||
|
||||
// In node.js env, polyfill might be already loaded (from any npm package),
|
||||
// that's why we do this check.
|
||||
if (!global._babelPolyfill) {
|
||||
require('babel-core/polyfill');
|
||||
}
|
||||
|
||||
const _ = require('lodash');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const common = require('./common');
|
||||
const server = require('./server/server');
|
||||
const connect = server.connect;
|
||||
const disconnect = server.disconnect;
|
||||
const getServerInfo = server.getServerInfo;
|
||||
const getFee = server.getFee;
|
||||
const isConnected = server.isConnected;
|
||||
const getLedgerVersion = server.getLedgerVersion;
|
||||
const getTransaction = require('./ledger/transaction');
|
||||
const getTransactions = require('./ledger/transactions');
|
||||
const getTrustlines = require('./ledger/trustlines');
|
||||
const getBalances = require('./ledger/balances');
|
||||
const getBalanceSheet = require('./ledger/balance-sheet');
|
||||
const getPaths = require('./ledger/pathfind');
|
||||
const getOrders = require('./ledger/orders');
|
||||
const getOrderbook = require('./ledger/orderbook');
|
||||
const getSettings = require('./ledger/settings');
|
||||
const getAccountInfo = require('./ledger/accountinfo');
|
||||
const preparePayment = require('./transaction/payment');
|
||||
const prepareTrustline = require('./transaction/trustline');
|
||||
const prepareOrder = require('./transaction/order');
|
||||
const prepareOrderCancellation = require('./transaction/ordercancellation');
|
||||
const prepareSuspendedPaymentCreation =
|
||||
require('./transaction/suspended-payment-creation');
|
||||
const prepareSuspendedPaymentExecution =
|
||||
require('./transaction/suspended-payment-execution');
|
||||
const prepareSuspendedPaymentCancellation =
|
||||
require('./transaction/suspended-payment-cancellation');
|
||||
const prepareSettings = require('./transaction/settings');
|
||||
const sign = require('./transaction/sign');
|
||||
const submit = require('./transaction/submit');
|
||||
const errors = require('./common').errors;
|
||||
const generateAddress = common.generateAddressAPI;
|
||||
const computeLedgerHash = require('./offline/ledgerhash');
|
||||
const getLedger = require('./ledger/ledger');
|
||||
|
||||
type APIOptions = {
|
||||
server?: string,
|
||||
feeCushion?: number,
|
||||
trace?: boolean,
|
||||
proxy?: string,
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
// prevent access to non-validated ledger versions
|
||||
class RestrictedConnection extends common.Connection {
|
||||
request(request, timeout) {
|
||||
const ledger_index = request.ledger_index;
|
||||
if (ledger_index !== undefined && ledger_index !== 'validated') {
|
||||
if (!_.isNumber(ledger_index) || ledger_index > this._ledgerVersion) {
|
||||
return Promise.reject(new errors.LedgerVersionError(
|
||||
`ledgerVersion ${ledger_index} is greater than server\'s ` +
|
||||
`most recent validated ledger: ${this._ledgerVersion}`));
|
||||
}
|
||||
}
|
||||
return super.request(request, timeout);
|
||||
}
|
||||
}
|
||||
|
||||
class RippleAPI extends EventEmitter {
|
||||
constructor(options: APIOptions = {}) {
|
||||
common.validate.apiOptions(options);
|
||||
super();
|
||||
this._feeCushion = options.feeCushion || 1.2;
|
||||
const serverURL = options.server;
|
||||
if (serverURL !== undefined) {
|
||||
this.connection = new RestrictedConnection(serverURL, options);
|
||||
this.connection.on('ledgerClosed', message => {
|
||||
this.emit('ledger', server.formatLedgerClose(message));
|
||||
});
|
||||
this.connection.on('error', (type, info) => {
|
||||
this.emit('error', type, info);
|
||||
});
|
||||
} else {
|
||||
// use null object pattern to provide better error message if user
|
||||
// tries to call a method that requires a connection
|
||||
this.connection = new RestrictedConnection(null, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_.assign(RippleAPI.prototype, {
|
||||
connect,
|
||||
disconnect,
|
||||
isConnected,
|
||||
getServerInfo,
|
||||
getFee,
|
||||
getLedgerVersion,
|
||||
|
||||
getTransaction,
|
||||
getTransactions,
|
||||
getTrustlines,
|
||||
getBalances,
|
||||
getBalanceSheet,
|
||||
getPaths,
|
||||
getOrders,
|
||||
getOrderbook,
|
||||
getSettings,
|
||||
getAccountInfo,
|
||||
getLedger,
|
||||
|
||||
preparePayment,
|
||||
prepareTrustline,
|
||||
prepareOrder,
|
||||
prepareOrderCancellation,
|
||||
prepareSuspendedPaymentCreation,
|
||||
prepareSuspendedPaymentExecution,
|
||||
prepareSuspendedPaymentCancellation,
|
||||
prepareSettings,
|
||||
sign,
|
||||
submit,
|
||||
|
||||
generateAddress,
|
||||
computeLedgerHash,
|
||||
errors
|
||||
});
|
||||
|
||||
// these are exposed only for use by unit tests; they are not part of the API
|
||||
RippleAPI._PRIVATE = {
|
||||
validate: common.validate,
|
||||
RangeSet: require('./common/rangeset').RangeSet,
|
||||
ledgerUtils: require('./ledger/utils'),
|
||||
schemaValidator: require('./common/schema-validator')
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
RippleAPI
|
||||
};
|
||||
66
src/broadcast.js
Normal file
66
src/broadcast.js
Normal file
@@ -0,0 +1,66 @@
|
||||
'use strict';
|
||||
const _ = require('lodash');
|
||||
const RippleAPI = require('./api').RippleAPI;
|
||||
|
||||
class RippleAPIBroadcast extends RippleAPI {
|
||||
constructor(servers, options) {
|
||||
super(options);
|
||||
this.ledgerVersion = 0;
|
||||
|
||||
const apis = servers.map(server => new RippleAPI(
|
||||
_.assign({}, options, {server})
|
||||
));
|
||||
|
||||
this.getMethodNames().forEach(name => {
|
||||
this[name] = function() { // eslint-disable-line no-loop-func
|
||||
return Promise.race(apis.map(api => api[name].apply(api, arguments)));
|
||||
};
|
||||
});
|
||||
|
||||
// connection methods must be overridden to apply to all api instances
|
||||
this.connect = function() {
|
||||
return Promise.all(apis.map(api => api.connect()));
|
||||
};
|
||||
this.disconnect = function() {
|
||||
return Promise.all(apis.map(api => api.disconnect()));
|
||||
};
|
||||
this.isConnected = function() {
|
||||
return _.every(apis.map(api => api.isConnected()));
|
||||
};
|
||||
|
||||
// synchronous methods are all passed directly to the first api instance
|
||||
const defaultAPI = apis[0];
|
||||
const syncMethods = ['sign', 'generateAddress', 'computeLedgerHash'];
|
||||
syncMethods.forEach(name => {
|
||||
this[name] = defaultAPI[name].bind(defaultAPI);
|
||||
});
|
||||
|
||||
apis.forEach(api => {
|
||||
api.on('ledger', this.onLedgerEvent.bind(this));
|
||||
api.on('error', (type, info) => this.emit('error', type, info));
|
||||
});
|
||||
}
|
||||
|
||||
onLedgerEvent(ledger) {
|
||||
if (ledger.ledgerVersion > this.ledgerVersion) {
|
||||
this.ledgerVersion = ledger.ledgerVersion;
|
||||
this.emit('ledger', ledger);
|
||||
}
|
||||
}
|
||||
|
||||
getMethodNames() {
|
||||
const methodNames = [];
|
||||
for (const name in RippleAPI.prototype) {
|
||||
if (RippleAPI.prototype.hasOwnProperty(name)) {
|
||||
if (typeof RippleAPI.prototype[name] === 'function') {
|
||||
methodNames.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return methodNames;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
RippleAPIBroadcast
|
||||
};
|
||||
@@ -17,6 +17,10 @@ class Connection extends EventEmitter {
|
||||
super();
|
||||
this._url = url;
|
||||
this._trace = options.trace;
|
||||
if (this._trace) {
|
||||
// for easier unit testing
|
||||
this._console = console;
|
||||
}
|
||||
this._proxyURL = options.proxy;
|
||||
this._proxyAuthorization = options.proxyAuthorization;
|
||||
this._authorization = options.authorization;
|
||||
@@ -54,7 +58,7 @@ class Connection extends EventEmitter {
|
||||
_onMessage(message) {
|
||||
let parameters;
|
||||
if (this._trace) {
|
||||
console.log(message);
|
||||
this._console.log(message);
|
||||
}
|
||||
try {
|
||||
parameters = this._parseMessage(message);
|
||||
@@ -198,7 +202,7 @@ class Connection extends EventEmitter {
|
||||
|
||||
_send(message) {
|
||||
if (this._trace) {
|
||||
console.log(message);
|
||||
this._console.log(message);
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
this._ws.send(message, undefined, (error, result) => {
|
||||
|
||||
@@ -12,15 +12,11 @@
|
||||
"minimum": 1,
|
||||
"description": "Factor to multiply estimated fee by to provide a cushion in case the required fee rises during submission of a transaction. Defaults to `1.2`."
|
||||
},
|
||||
"servers": {
|
||||
"type": "array",
|
||||
"description": "Array of rippled servers to connect to. Currently only one server is supported.",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"description": "URI for rippled websocket port. Must start with `wss://` or `ws://`.",
|
||||
"format": "uri",
|
||||
"pattern": "^wss?://"
|
||||
}
|
||||
"server": {
|
||||
"type": "string",
|
||||
"description": "URI for rippled websocket port to connect to. Must start with `wss://` or `ws://`.",
|
||||
"format": "uri",
|
||||
"pattern": "^wss?://"
|
||||
},
|
||||
"proxy": {
|
||||
"format": "uri",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-04/schema#",
|
||||
"title": "tag",
|
||||
"description": "An arbitrary unsigned 32-bit integer most commonly used to identify a non-Ripple account.",
|
||||
"description": "An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.",
|
||||
"type": "integer",
|
||||
"$ref": "uint32"
|
||||
}
|
||||
|
||||
146
src/index.js
146
src/index.js
@@ -1,146 +1,6 @@
|
||||
/* @flow */
|
||||
'use strict';
|
||||
|
||||
/* eslint-disable max-len */
|
||||
// Enable core-js polyfills. This allows use of ES6/7 extensions listed here:
|
||||
// https://github.com/zloirock/core-js/blob/fb0890f32dabe8d4d88a4350d1b268446127132e/shim.js#L1-L103
|
||||
/* eslint-enable max-len */
|
||||
|
||||
// In node.js env, polyfill might be already loaded (from any npm package),
|
||||
// that's why we do this check.
|
||||
if (!global._babelPolyfill) {
|
||||
require('babel-core/polyfill');
|
||||
}
|
||||
|
||||
const _ = require('lodash');
|
||||
const EventEmitter = require('events').EventEmitter;
|
||||
const common = require('./common');
|
||||
const server = require('./server/server');
|
||||
const connect = server.connect;
|
||||
const disconnect = server.disconnect;
|
||||
const getServerInfo = server.getServerInfo;
|
||||
const getFee = server.getFee;
|
||||
const isConnected = server.isConnected;
|
||||
const getLedgerVersion = server.getLedgerVersion;
|
||||
const getTransaction = require('./ledger/transaction');
|
||||
const getTransactions = require('./ledger/transactions');
|
||||
const getTrustlines = require('./ledger/trustlines');
|
||||
const getBalances = require('./ledger/balances');
|
||||
const getBalanceSheet = require('./ledger/balance-sheet');
|
||||
const getPaths = require('./ledger/pathfind');
|
||||
const getOrders = require('./ledger/orders');
|
||||
const getOrderbook = require('./ledger/orderbook');
|
||||
const getSettings = require('./ledger/settings');
|
||||
const getAccountInfo = require('./ledger/accountinfo');
|
||||
const preparePayment = require('./transaction/payment');
|
||||
const prepareTrustline = require('./transaction/trustline');
|
||||
const prepareOrder = require('./transaction/order');
|
||||
const prepareOrderCancellation = require('./transaction/ordercancellation');
|
||||
const prepareSuspendedPaymentCreation =
|
||||
require('./transaction/suspended-payment-creation');
|
||||
const prepareSuspendedPaymentExecution =
|
||||
require('./transaction/suspended-payment-execution');
|
||||
const prepareSuspendedPaymentCancellation =
|
||||
require('./transaction/suspended-payment-cancellation');
|
||||
const prepareSettings = require('./transaction/settings');
|
||||
const sign = require('./transaction/sign');
|
||||
const submit = require('./transaction/submit');
|
||||
const errors = require('./common').errors;
|
||||
const generateAddress = common.generateAddressAPI;
|
||||
const computeLedgerHash = require('./offline/ledgerhash');
|
||||
const getLedger = require('./ledger/ledger');
|
||||
|
||||
type APIOptions = {
|
||||
servers?: Array<string>,
|
||||
feeCushion?: number,
|
||||
trace?: boolean,
|
||||
proxy?: string,
|
||||
timeout?: number
|
||||
}
|
||||
|
||||
// prevent access to non-validated ledger versions
|
||||
class RestrictedConnection extends common.Connection {
|
||||
request(request, timeout) {
|
||||
const ledger_index = request.ledger_index;
|
||||
if (ledger_index !== undefined && ledger_index !== 'validated') {
|
||||
if (!_.isNumber(ledger_index) || ledger_index > this._ledgerVersion) {
|
||||
return Promise.reject(new errors.LedgerVersionError(
|
||||
`ledgerVersion ${ledger_index} is greater than server\'s ` +
|
||||
`most recent validated ledger: ${this._ledgerVersion}`));
|
||||
}
|
||||
}
|
||||
return super.request(request, timeout);
|
||||
}
|
||||
}
|
||||
|
||||
class RippleAPI extends EventEmitter {
|
||||
constructor(options: APIOptions = {}) {
|
||||
common.validate.apiOptions(options);
|
||||
super();
|
||||
this._feeCushion = options.feeCushion || 1.2;
|
||||
if (options.servers !== undefined) {
|
||||
const servers: Array<string> = options.servers;
|
||||
if (servers.length === 1) {
|
||||
this.connection = new RestrictedConnection(servers[0], options);
|
||||
this.connection.on('ledgerClosed', message => {
|
||||
this.emit('ledger', server.formatLedgerClose(message));
|
||||
});
|
||||
this.connection.on('error', (type, info) => {
|
||||
this.emit('error', type, info);
|
||||
});
|
||||
} else {
|
||||
throw new errors.RippleError('Multi-server not implemented');
|
||||
}
|
||||
} else {
|
||||
// use null object pattern to provide better error message if user
|
||||
// tries to call a method that requires a connection
|
||||
this.connection = new RestrictedConnection(null, options);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_.assign(RippleAPI.prototype, {
|
||||
connect,
|
||||
disconnect,
|
||||
isConnected,
|
||||
getServerInfo,
|
||||
getFee,
|
||||
getLedgerVersion,
|
||||
|
||||
getTransaction,
|
||||
getTransactions,
|
||||
getTrustlines,
|
||||
getBalances,
|
||||
getBalanceSheet,
|
||||
getPaths,
|
||||
getOrders,
|
||||
getOrderbook,
|
||||
getSettings,
|
||||
getAccountInfo,
|
||||
getLedger,
|
||||
|
||||
preparePayment,
|
||||
prepareTrustline,
|
||||
prepareOrder,
|
||||
prepareOrderCancellation,
|
||||
prepareSuspendedPaymentCreation,
|
||||
prepareSuspendedPaymentExecution,
|
||||
prepareSuspendedPaymentCancellation,
|
||||
prepareSettings,
|
||||
sign,
|
||||
submit,
|
||||
|
||||
generateAddress,
|
||||
computeLedgerHash,
|
||||
errors
|
||||
});
|
||||
|
||||
// these are exposed only for use by unit tests; they are not part of the API
|
||||
RippleAPI._PRIVATE = {
|
||||
validate: common.validate,
|
||||
RangeSet: require('./common/rangeset').RangeSet,
|
||||
ledgerUtils: require('./ledger/utils'),
|
||||
schemaValidator: require('./common/schema-validator')
|
||||
module.exports = {
|
||||
RippleAPI: require('./api').RippleAPI,
|
||||
RippleAPIBroadcast: require('./broadcast').RippleAPIBroadcast
|
||||
};
|
||||
|
||||
module.exports.RippleAPI = RippleAPI;
|
||||
|
||||
@@ -87,15 +87,17 @@ function createSettingsTransaction(account: string, settings: Settings
|
||||
TransactionType: 'AccountSet',
|
||||
Account: account
|
||||
};
|
||||
setTransactionFlags(txJSON, settings);
|
||||
|
||||
if (settings.memos !== undefined) {
|
||||
txJSON.Memos = _.map(settings.memos, utils.convertMemo);
|
||||
}
|
||||
|
||||
setTransactionFlags(txJSON, _.omit(settings, 'memos'));
|
||||
setTransactionFields(txJSON, settings);
|
||||
|
||||
if (txJSON.TransferRate !== undefined) {
|
||||
txJSON.TransferRate = convertTransferRate(txJSON.TransferRate);
|
||||
}
|
||||
if (settings.memos !== undefined) {
|
||||
txJSON.Memos = _.map(settings.memos, utils.convertMemo);
|
||||
}
|
||||
return txJSON;
|
||||
}
|
||||
|
||||
|
||||
553
test/api-test.js
553
test/api-test.js
@@ -1,7 +1,6 @@
|
||||
/* eslint-disable max-nested-callbacks */
|
||||
'use strict';
|
||||
const _ = require('lodash');
|
||||
const net = require('net');
|
||||
const assert = require('assert-diff');
|
||||
const setupAPI = require('./setup-api');
|
||||
const RippleAPI = require('ripple-api').RippleAPI;
|
||||
@@ -35,314 +34,90 @@ function checkResult(expected, schemaName, response) {
|
||||
return response;
|
||||
}
|
||||
|
||||
function createServer() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.on('listening', function() {
|
||||
resolve(server);
|
||||
});
|
||||
server.on('error', function(error) {
|
||||
reject(error);
|
||||
});
|
||||
server.listen(0, '0.0.0.0');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
describe('RippleAPI', function() {
|
||||
const instructions = {maxLedgerVersionOffset: 100};
|
||||
beforeEach(setupAPI.setup);
|
||||
afterEach(setupAPI.teardown);
|
||||
|
||||
describe('Connection', function() {
|
||||
|
||||
it('connection default options', function() {
|
||||
const connection = new utils.common.Connection('url');
|
||||
assert.strictEqual(connection._url, 'url');
|
||||
assert(_.isUndefined(connection._proxyURL));
|
||||
assert(_.isUndefined(connection._authorization));
|
||||
});
|
||||
|
||||
it('with proxy', function(done) {
|
||||
createServer().then((server) => {
|
||||
const port = server.address().port;
|
||||
const expect = 'CONNECT localhost';
|
||||
server.on('connection', (socket) => {
|
||||
socket.on('data', (data) => {
|
||||
const got = data.toString('ascii', 0, expect.length);
|
||||
assert.strictEqual(got, expect);
|
||||
server.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
const options = {
|
||||
proxy: 'ws://localhost:' + port,
|
||||
authorization: 'authorization',
|
||||
trustedCertificates: 'something'
|
||||
};
|
||||
const connection =
|
||||
new utils.common.Connection(this.api.connection._url, options);
|
||||
connection.connect().catch(done);
|
||||
connection.connect().catch(done);
|
||||
}, done);
|
||||
});
|
||||
|
||||
it('Multiply disconnect calls', function() {
|
||||
this.api.disconnect();
|
||||
return this.api.disconnect();
|
||||
});
|
||||
|
||||
it('reconnect', function() {
|
||||
return this.api.connection.reconnect();
|
||||
});
|
||||
|
||||
it('NotConnectedError', function() {
|
||||
const connection = new utils.common.Connection('url');
|
||||
return connection.getLedgerVersion().then(() => {
|
||||
assert(false, 'Should throw NotConnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.NotConnectedError);
|
||||
});
|
||||
});
|
||||
|
||||
it('DisconnectedError', function() {
|
||||
this.api.connection._send = function() {
|
||||
this._ws.close();
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw DisconnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.DisconnectedError);
|
||||
});
|
||||
});
|
||||
|
||||
it('TimeoutError', function() {
|
||||
this.api.connection._send = function() {
|
||||
return Promise.resolve({});
|
||||
};
|
||||
const request = {command: 'server_info'};
|
||||
return this.api.connection.request(request, 1).then(() => {
|
||||
assert(false, 'Should throw TimeoutError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.TimeoutError);
|
||||
});
|
||||
});
|
||||
|
||||
it('DisconnectedError on send', function() {
|
||||
this.api.connection._ws.send = function(message, options, callback) {
|
||||
unused(message, options);
|
||||
callback({message: 'not connected'});
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw DisconnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.DisconnectedError);
|
||||
assert.strictEqual(error.message, 'not connected');
|
||||
});
|
||||
});
|
||||
|
||||
it('ResponseFormatError', function() {
|
||||
this.api.connection._send = function(message) {
|
||||
const parsed = JSON.parse(message);
|
||||
setTimeout(() => {
|
||||
this._ws.emit('message', JSON.stringify({
|
||||
id: parsed.id,
|
||||
type: 'response',
|
||||
status: 'unrecognized'
|
||||
}));
|
||||
}, 2);
|
||||
return new Promise(() => {});
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw ResponseFormatError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.ResponseFormatError);
|
||||
});
|
||||
});
|
||||
|
||||
it('reconnect on unexpected close ', function(done) {
|
||||
this.api.connection.on('connected', () => {
|
||||
done();
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
this.api.connection._ws.close();
|
||||
}, 1);
|
||||
});
|
||||
|
||||
it('Multiply connect calls', function() {
|
||||
return this.api.connect().then(() => {
|
||||
return this.api.connect();
|
||||
});
|
||||
});
|
||||
|
||||
it('hasLedgerVersion', function() {
|
||||
return this.api.connection.hasLedgerVersion(8819951).then((result) => {
|
||||
assert(result);
|
||||
});
|
||||
});
|
||||
|
||||
it('Cannot connect because no server', function() {
|
||||
const connection = new utils.common.Connection();
|
||||
return connection.connect().then(() => {
|
||||
assert(false, 'Should throw ConnectionError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.ConnectionError);
|
||||
});
|
||||
});
|
||||
|
||||
it('connect multiserver error', function() {
|
||||
const options = {
|
||||
servers: ['wss://server1.com', 'wss://server2.com']
|
||||
};
|
||||
assert.throws(function() {
|
||||
const api = new RippleAPI(options);
|
||||
unused(api);
|
||||
}, this.api.errors.RippleError);
|
||||
});
|
||||
|
||||
it('connect throws error', function(done) {
|
||||
this.api.once('error', (type, info) => {
|
||||
assert.strictEqual(type, 'type');
|
||||
assert.strictEqual(info, 'info');
|
||||
done();
|
||||
});
|
||||
this.api.connection.emit('error', 'type', 'info');
|
||||
});
|
||||
|
||||
it('connection emit stream messages', function(done) {
|
||||
let transactionCount = 0;
|
||||
let pathFindCount = 0;
|
||||
this.api.connection.on('transaction', () => {
|
||||
transactionCount++;
|
||||
});
|
||||
this.api.connection.on('path_find', () => {
|
||||
pathFindCount++;
|
||||
});
|
||||
this.api.connection.on('1', () => {
|
||||
assert.strictEqual(transactionCount, 1);
|
||||
assert.strictEqual(pathFindCount, 1);
|
||||
done();
|
||||
});
|
||||
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'transaction'
|
||||
}));
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'path_find'
|
||||
}));
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'response', id: 1
|
||||
}));
|
||||
});
|
||||
|
||||
it('connection - invalid message id', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'badMessage');
|
||||
assert.strictEqual(message,
|
||||
'{"type":"response","id":"must be integer"}');
|
||||
done();
|
||||
});
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'response', id: 'must be integer'
|
||||
}));
|
||||
});
|
||||
|
||||
it('connection - error message', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'slowDown');
|
||||
assert.strictEqual(message, 'slow down');
|
||||
done();
|
||||
});
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
error: 'slowDown', error_message: 'slow down'
|
||||
}));
|
||||
});
|
||||
|
||||
it('connection - unrecognized message type', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'badMessage');
|
||||
assert.strictEqual(message, '{"type":"unknown"}');
|
||||
done();
|
||||
});
|
||||
|
||||
this.api.connection._onMessage(JSON.stringify({type: 'unknown'}));
|
||||
});
|
||||
});
|
||||
|
||||
it('error inspect', function() {
|
||||
const error = new this.api.errors.RippleError('mess', {data: 1});
|
||||
assert.strictEqual(error.inspect(), '[RippleError(mess, { data: 1 })]');
|
||||
});
|
||||
|
||||
it('preparePayment', function() {
|
||||
const localInstructions = _.defaults({
|
||||
maxFee: '0.000012'
|
||||
}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePayment, localInstructions).then(
|
||||
_.partial(checkResult, responses.preparePayment.normal, 'prepare'));
|
||||
});
|
||||
describe('preparePayment', function() {
|
||||
|
||||
it('preparePayment - min amount xrp', function() {
|
||||
const localInstructions = _.defaults({
|
||||
maxFee: '0.000012'
|
||||
}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePaymentMinAmountXRP, localInstructions).then(
|
||||
_.partial(checkResult, responses.preparePayment.minAmountXRP, 'prepare'));
|
||||
});
|
||||
|
||||
it('preparePayment - min amount xrp2xrp', function() {
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePaymentMinAmount, instructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.preparePayment.minAmountXRPXRP, 'prepare'));
|
||||
});
|
||||
|
||||
it('preparePayment - XRP to XRP no partial', function() {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePaymentWrongPartial);
|
||||
}, /XRP to XRP payments cannot be partial payments/);
|
||||
});
|
||||
|
||||
it('preparePayment - address must match payment.source.address', function() {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePaymentWrongAddress);
|
||||
}, /address must match payment.source.address/);
|
||||
});
|
||||
|
||||
it('preparePayment - wrong amount', function() {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePaymentWrongAmount);
|
||||
}, this.api.errors.ValidationError);
|
||||
});
|
||||
|
||||
it('preparePayment with all options specified', function() {
|
||||
return this.api.getLedgerVersion().then((ver) => {
|
||||
const localInstructions = {
|
||||
maxLedgerVersion: ver + 100,
|
||||
fee: '0.000012'
|
||||
};
|
||||
it('normal', function() {
|
||||
const localInstructions = _.defaults({
|
||||
maxFee: '0.000012'
|
||||
}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePaymentAllOptions, localInstructions).then(
|
||||
_.partial(checkResult, responses.preparePayment.allOptions, 'prepare'));
|
||||
address, requests.preparePayment.normal, localInstructions).then(
|
||||
_.partial(checkResult, responses.preparePayment.normal, 'prepare'));
|
||||
});
|
||||
});
|
||||
|
||||
it('preparePayment without counterparty set', function() {
|
||||
const localInstructions = _.defaults({sequence: 23}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePaymentNoCounterparty, localInstructions).then(
|
||||
_.partial(checkResult, responses.preparePayment.noCounterparty,
|
||||
'prepare'));
|
||||
});
|
||||
it('preparePayment - min amount xrp', function() {
|
||||
const localInstructions = _.defaults({
|
||||
maxFee: '0.000012'
|
||||
}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePayment.minAmountXRP, localInstructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.preparePayment.minAmountXRP, 'prepare'));
|
||||
});
|
||||
|
||||
it('preparePayment - destination.minAmount', function() {
|
||||
return this.api.preparePayment(address, responses.getPaths.sendAll[0],
|
||||
instructions).then(_.partial(checkResult,
|
||||
responses.preparePayment.minAmount, 'prepare'));
|
||||
it('preparePayment - min amount xrp2xrp', function() {
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePayment.minAmount, instructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.preparePayment.minAmountXRPXRP, 'prepare'));
|
||||
});
|
||||
|
||||
it('preparePayment - XRP to XRP no partial', function() {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePayment.wrongPartial);
|
||||
}, /XRP to XRP payments cannot be partial payments/);
|
||||
});
|
||||
|
||||
it('preparePayment - address must match payment.source.address', function(
|
||||
) {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePayment.wrongAddress);
|
||||
}, /address must match payment.source.address/);
|
||||
});
|
||||
|
||||
it('preparePayment - wrong amount', function() {
|
||||
assert.throws(() => {
|
||||
this.api.preparePayment(address, requests.preparePayment.wrongAmount);
|
||||
}, this.api.errors.ValidationError);
|
||||
});
|
||||
|
||||
it('preparePayment with all options specified', function() {
|
||||
return this.api.getLedgerVersion().then((ver) => {
|
||||
const localInstructions = {
|
||||
maxLedgerVersion: ver + 100,
|
||||
fee: '0.000012'
|
||||
};
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePayment.allOptions, localInstructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.preparePayment.allOptions, 'prepare'));
|
||||
});
|
||||
});
|
||||
|
||||
it('preparePayment without counterparty set', function() {
|
||||
const localInstructions = _.defaults({sequence: 23}, instructions);
|
||||
return this.api.preparePayment(
|
||||
address, requests.preparePayment.noCounterparty, localInstructions)
|
||||
.then(_.partial(checkResult, responses.preparePayment.noCounterparty,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('preparePayment - destination.minAmount', function() {
|
||||
return this.api.preparePayment(address, responses.getPaths.sendAll[0],
|
||||
instructions).then(_.partial(checkResult,
|
||||
responses.preparePayment.minAmount, 'prepare'));
|
||||
});
|
||||
});
|
||||
|
||||
it('prepareOrder - buy order', function() {
|
||||
@@ -365,17 +140,25 @@ describe('RippleAPI', function() {
|
||||
});
|
||||
|
||||
it('prepareOrderCancellation', function() {
|
||||
const request = requests.prepareOrderCancellation;
|
||||
const request = requests.prepareOrderCancellation.simple;
|
||||
return this.api.prepareOrderCancellation(address, request, instructions)
|
||||
.then(_.partial(checkResult, responses.prepareOrder.cancellation,
|
||||
.then(_.partial(checkResult, responses.prepareOrderCancellation.normal,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareOrderCancellation - no instructions', function() {
|
||||
const request = requests.prepareOrderCancellation;
|
||||
const request = requests.prepareOrderCancellation.simple;
|
||||
return this.api.prepareOrderCancellation(address, request)
|
||||
.then(_.partial(checkResult,
|
||||
responses.prepareOrder.cancellationNoInstructions,
|
||||
responses.prepareOrderCancellation.noInstructions,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareOrderCancellation - with memos', function() {
|
||||
const request = requests.prepareOrderCancellation.withMemos;
|
||||
return this.api.prepareOrderCancellation(address, request)
|
||||
.then(_.partial(checkResult,
|
||||
responses.prepareOrderCancellation.withMemos,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
@@ -458,63 +241,71 @@ describe('RippleAPI', function() {
|
||||
maxFee: '0.000012'
|
||||
}, instructions);
|
||||
return this.api.prepareSuspendedPaymentCreation(
|
||||
address, requests.prepareSuspendedPaymentCreation,
|
||||
address, requests.prepareSuspendedPaymentCreation.normal,
|
||||
localInstructions).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCreation,
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCreation.normal,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareSuspendedPaymentCreation full', function() {
|
||||
return this.api.prepareSuspendedPaymentCreation(
|
||||
address, requests.prepareSuspendedPaymentCreationFull).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCreationFull,
|
||||
address, requests.prepareSuspendedPaymentCreation.full).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCreation.full,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareSuspendedPaymentExecution', function() {
|
||||
return this.api.prepareSuspendedPaymentExecution(
|
||||
address, requests.prepareSuspendedPaymentExecution, instructions).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentExecution,
|
||||
'prepare'));
|
||||
address,
|
||||
requests.prepareSuspendedPaymentExecution.normal, instructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.prepareSuspendedPaymentExecution.normal,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareSuspendedPaymentExecution - simple', function() {
|
||||
return this.api.prepareSuspendedPaymentExecution(
|
||||
address, requests.prepareSuspendedPaymentExecutionSimple).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentExecutionSimple,
|
||||
'prepare'));
|
||||
address,
|
||||
requests.prepareSuspendedPaymentExecution.simple).then(
|
||||
_.partial(checkResult,
|
||||
responses.prepareSuspendedPaymentExecution.simple,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareSuspendedPaymentCancellation', function() {
|
||||
return this.api.prepareSuspendedPaymentCancellation(
|
||||
address, requests.prepareSuspendedPaymentCancellation, instructions).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCancellation,
|
||||
'prepare'));
|
||||
address,
|
||||
requests.prepareSuspendedPaymentCancellation.normal, instructions).then(
|
||||
_.partial(checkResult,
|
||||
responses.prepareSuspendedPaymentCancellation.normal,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('prepareSuspendedPaymentCancellation with memos', function() {
|
||||
return this.api.prepareSuspendedPaymentCancellation(
|
||||
address, requests.prepareSuspendedPaymentCancellationMemos).then(
|
||||
_.partial(checkResult, responses.prepareSuspendedPaymentCancellationMemos,
|
||||
'prepare'));
|
||||
address,
|
||||
requests.prepareSuspendedPaymentCancellation.memos).then(
|
||||
_.partial(checkResult,
|
||||
responses.prepareSuspendedPaymentCancellation.memos,
|
||||
'prepare'));
|
||||
});
|
||||
|
||||
it('sign', function() {
|
||||
const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV';
|
||||
const result = this.api.sign(requests.sign.txJSON, secret);
|
||||
assert.deepEqual(result, responses.sign);
|
||||
const result = this.api.sign(requests.sign.normal.txJSON, secret);
|
||||
assert.deepEqual(result, responses.sign.normal);
|
||||
schemaValidator.schemaValidate('sign', result);
|
||||
});
|
||||
|
||||
it('sign - SuspendedPaymentExecution', function() {
|
||||
const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb';
|
||||
const result = this.api.sign(requests.signSuspended.txJSON, secret);
|
||||
assert.deepEqual(result, responses.signSuspended);
|
||||
const result = this.api.sign(requests.sign.suspended.txJSON, secret);
|
||||
assert.deepEqual(result, responses.sign.suspended);
|
||||
schemaValidator.schemaValidate('sign', result);
|
||||
});
|
||||
|
||||
it('submit', function() {
|
||||
return this.api.submit(responses.sign.signedTransaction).then(
|
||||
return this.api.submit(responses.sign.normal.signedTransaction).then(
|
||||
_.partial(checkResult, responses.submit, 'submit'));
|
||||
});
|
||||
|
||||
@@ -860,7 +651,7 @@ describe('RippleAPI', function() {
|
||||
it('getTransactions', function() {
|
||||
const options = {types: ['payment', 'order'], initiated: true, limit: 2};
|
||||
return this.api.getTransactions(address, options).then(
|
||||
_.partial(checkResult, responses.getTransactions,
|
||||
_.partial(checkResult, responses.getTransactions.normal,
|
||||
'getTransactions'));
|
||||
});
|
||||
|
||||
@@ -868,7 +659,7 @@ describe('RippleAPI', function() {
|
||||
const options = {types: ['payment', 'order'], initiated: true, limit: 2,
|
||||
earliestFirst: true
|
||||
};
|
||||
const expected = _.cloneDeep(responses.getTransactions)
|
||||
const expected = _.cloneDeep(responses.getTransactions.normal)
|
||||
.sort(utils.compareTransactions);
|
||||
return this.api.getTransactions(address, options).then(
|
||||
_.partial(checkResult, expected, 'getTransactions'));
|
||||
@@ -951,7 +742,8 @@ describe('RippleAPI', function() {
|
||||
limit: 2
|
||||
};
|
||||
return this.api.getTransactions(address, options).then(
|
||||
_.partial(checkResult, responses.getTransactions, 'getTransactions'));
|
||||
_.partial(checkResult, responses.getTransactions.normal,
|
||||
'getTransactions'));
|
||||
});
|
||||
|
||||
it('getTransactions - start transaction with zero ledger version', function(
|
||||
@@ -966,18 +758,19 @@ describe('RippleAPI', function() {
|
||||
|
||||
it('getTransactions - no options', function() {
|
||||
return this.api.getTransactions(addresses.OTHER_ACCOUNT).then(
|
||||
_.partial(checkResult, responses.getTransactionsOne, 'getTransactions'));
|
||||
_.partial(checkResult, responses.getTransactions.one, 'getTransactions'));
|
||||
});
|
||||
|
||||
it('getTrustlines', function() {
|
||||
it('getTrustlines - filtered', function() {
|
||||
const options = {currency: 'USD'};
|
||||
return this.api.getTrustlines(address, options).then(
|
||||
_.partial(checkResult, responses.getTrustlines, 'getTrustlines'));
|
||||
_.partial(checkResult,
|
||||
responses.getTrustlines.filtered, 'getTrustlines'));
|
||||
});
|
||||
|
||||
it('getTrustlines - ono options', function() {
|
||||
it('getTrustlines - no options', function() {
|
||||
return this.api.getTrustlines(address).then(
|
||||
_.partial(checkResult, responses.getTrustlinesAll, 'getTrustlines'));
|
||||
_.partial(checkResult, responses.getTrustlines.all, 'getTrustlines'));
|
||||
});
|
||||
|
||||
it('generateAddress', function() {
|
||||
@@ -1045,59 +838,66 @@ describe('RippleAPI', function() {
|
||||
}, this.api.errors.ValidationError);
|
||||
});
|
||||
|
||||
it('getOrderbook', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook, undefined)
|
||||
.then(
|
||||
_.partial(checkResult, responses.getOrderbook, 'getOrderbook'));
|
||||
});
|
||||
describe('getOrderbook', function() {
|
||||
|
||||
it('getOrderbook - invalid options', function() {
|
||||
assert.throws(() => {
|
||||
this.api.getOrderbook(address, requests.getOrderbook,
|
||||
{invalid: 'options'});
|
||||
}, this.api.errors.ValidationError);
|
||||
});
|
||||
|
||||
it('getOrderbook with XRP', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbookWithXRP).then(
|
||||
_.partial(checkResult, responses.getOrderbookWithXRP, 'getOrderbook'));
|
||||
});
|
||||
|
||||
it('getOrderbook - sorted so that best deals come first', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook)
|
||||
.then(data => {
|
||||
const bidRates = data.bids.map(bid => bid.properties.makerExchangeRate);
|
||||
const askRates = data.asks.map(ask => ask.properties.makerExchangeRate);
|
||||
// makerExchangeRate = quality = takerPays.value/takerGets.value
|
||||
// so the best deal for the taker is the lowest makerExchangeRate
|
||||
// bids and asks should be sorted so that the best deals come first
|
||||
assert.deepEqual(_.sortBy(bidRates, x => Number(x)), bidRates);
|
||||
assert.deepEqual(_.sortBy(askRates, x => Number(x)), askRates);
|
||||
it('normal', function() {
|
||||
return this.api.getOrderbook(address,
|
||||
requests.getOrderbook.normal, undefined).then(
|
||||
_.partial(checkResult,
|
||||
responses.getOrderbook.normal, 'getOrderbook'));
|
||||
});
|
||||
});
|
||||
|
||||
it('getOrderbook - currency & counterparty are correct', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook)
|
||||
.then(data => {
|
||||
const orders = _.flatten([data.bids, data.asks]);
|
||||
_.forEach(orders, order => {
|
||||
const quantity = order.specification.quantity;
|
||||
const totalPrice = order.specification.totalPrice;
|
||||
const {base, counter} = requests.getOrderbook;
|
||||
assert.strictEqual(quantity.currency, base.currency);
|
||||
assert.strictEqual(quantity.counterparty, base.counterparty);
|
||||
assert.strictEqual(totalPrice.currency, counter.currency);
|
||||
assert.strictEqual(totalPrice.counterparty, counter.counterparty);
|
||||
it('invalid options', function() {
|
||||
assert.throws(() => {
|
||||
this.api.getOrderbook(address, requests.getOrderbook.normal,
|
||||
{invalid: 'options'});
|
||||
}, this.api.errors.ValidationError);
|
||||
});
|
||||
|
||||
it('with XRP', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook.withXRP).then(
|
||||
_.partial(checkResult, responses.getOrderbook.withXRP, 'getOrderbook'));
|
||||
});
|
||||
|
||||
it('sorted so that best deals come first', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook.normal)
|
||||
.then(data => {
|
||||
const bidRates = data.bids.map(bid => bid.properties.makerExchangeRate);
|
||||
const askRates = data.asks.map(ask => ask.properties.makerExchangeRate);
|
||||
// makerExchangeRate = quality = takerPays.value/takerGets.value
|
||||
// so the best deal for the taker is the lowest makerExchangeRate
|
||||
// bids and asks should be sorted so that the best deals come first
|
||||
assert.deepEqual(_.sortBy(bidRates, x => Number(x)), bidRates);
|
||||
assert.deepEqual(_.sortBy(askRates, x => Number(x)), askRates);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('getOrderbook - direction is correct for bids and asks', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook)
|
||||
.then(data => {
|
||||
assert(_.every(data.bids, bid => bid.specification.direction === 'buy'));
|
||||
assert(_.every(data.asks, ask => ask.specification.direction === 'sell'));
|
||||
it('currency & counterparty are correct', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook.normal)
|
||||
.then(data => {
|
||||
const orders = _.flatten([data.bids, data.asks]);
|
||||
_.forEach(orders, order => {
|
||||
const quantity = order.specification.quantity;
|
||||
const totalPrice = order.specification.totalPrice;
|
||||
const {base, counter} = requests.getOrderbook.normal;
|
||||
assert.strictEqual(quantity.currency, base.currency);
|
||||
assert.strictEqual(quantity.counterparty, base.counterparty);
|
||||
assert.strictEqual(totalPrice.currency, counter.currency);
|
||||
assert.strictEqual(totalPrice.counterparty, counter.counterparty);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('direction is correct for bids and asks', function() {
|
||||
return this.api.getOrderbook(address, requests.getOrderbook.normal)
|
||||
.then(data => {
|
||||
assert(
|
||||
_.every(data.bids, bid => bid.specification.direction === 'buy'));
|
||||
assert(
|
||||
_.every(data.asks, ask => ask.specification.direction === 'sell'));
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
it('getServerInfo', function() {
|
||||
@@ -1455,7 +1255,8 @@ describe('RippleAPI - offline', function() {
|
||||
};
|
||||
return api.prepareSettings(address, settings, instructions).then(data => {
|
||||
checkResult(responses.prepareSettings.flags, 'prepare', data);
|
||||
assert.deepEqual(api.sign(data.txJSON, secret), responses.sign);
|
||||
assert.deepEqual(api.sign(data.txJSON, secret),
|
||||
responses.prepareSettings.signed);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1499,7 +1300,7 @@ describe('RippleAPI - offline', function() {
|
||||
|
||||
/* eslint-disable no-unused-vars */
|
||||
it('RippleAPI - implicit server port', function() {
|
||||
const api = new RippleAPI({servers: ['wss://s1.ripple.com']});
|
||||
const api = new RippleAPI({server: 'wss://s1.ripple.com'});
|
||||
});
|
||||
/* eslint-enable no-unused-vars */
|
||||
it('RippleAPI invalid options', function() {
|
||||
@@ -1507,12 +1308,12 @@ describe('RippleAPI - offline', function() {
|
||||
});
|
||||
|
||||
it('RippleAPI valid options', function() {
|
||||
const api = new RippleAPI({servers: ['wss://s:1']});
|
||||
const api = new RippleAPI({server: 'wss://s:1'});
|
||||
assert.deepEqual(api.connection._url, 'wss://s:1');
|
||||
});
|
||||
|
||||
it('RippleAPI invalid server uri', function() {
|
||||
assert.throws(() => new RippleAPI({servers: ['wss//s:1']}));
|
||||
assert.throws(() => new RippleAPI({server: 'wss//s:1'}));
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
261
test/connection-test.js
Normal file
261
test/connection-test.js
Normal file
@@ -0,0 +1,261 @@
|
||||
/* eslint-disable max-nested-callbacks */
|
||||
'use strict';
|
||||
|
||||
const _ = require('lodash');
|
||||
const net = require('net');
|
||||
const assert = require('assert-diff');
|
||||
const setupAPI = require('./setup-api');
|
||||
const RippleAPI = require('ripple-api').RippleAPI;
|
||||
const utils = RippleAPI._PRIVATE.ledgerUtils;
|
||||
|
||||
|
||||
function unused() {
|
||||
}
|
||||
|
||||
function createServer() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.on('listening', function() {
|
||||
resolve(server);
|
||||
});
|
||||
server.on('error', function(error) {
|
||||
reject(error);
|
||||
});
|
||||
server.listen(0, '0.0.0.0');
|
||||
});
|
||||
}
|
||||
|
||||
describe('Connection', function() {
|
||||
beforeEach(setupAPI.setup);
|
||||
afterEach(setupAPI.teardown);
|
||||
|
||||
it('default options', function() {
|
||||
const connection = new utils.common.Connection('url');
|
||||
assert.strictEqual(connection._url, 'url');
|
||||
assert(_.isUndefined(connection._proxyURL));
|
||||
assert(_.isUndefined(connection._authorization));
|
||||
});
|
||||
|
||||
it('trace', function() {
|
||||
const connection = new utils.common.Connection('url', {trace: true});
|
||||
const message1 = '{"type": "transaction"}';
|
||||
const message2 = '{"type": "path_find"}';
|
||||
const messages = [];
|
||||
connection._console = {
|
||||
log: function(message) {
|
||||
messages.push(message);
|
||||
}
|
||||
};
|
||||
connection._onMessage(message1);
|
||||
connection._send(message2);
|
||||
|
||||
assert.deepEqual(messages, [message1, message2]);
|
||||
});
|
||||
|
||||
it('with proxy', function(done) {
|
||||
createServer().then((server) => {
|
||||
const port = server.address().port;
|
||||
const expect = 'CONNECT localhost';
|
||||
server.on('connection', (socket) => {
|
||||
socket.on('data', (data) => {
|
||||
const got = data.toString('ascii', 0, expect.length);
|
||||
assert.strictEqual(got, expect);
|
||||
server.close();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
const options = {
|
||||
proxy: 'ws://localhost:' + port,
|
||||
authorization: 'authorization',
|
||||
trustedCertificates: ['path/to/pem']
|
||||
};
|
||||
const connection =
|
||||
new utils.common.Connection(this.api.connection._url, options);
|
||||
connection.connect().catch(done);
|
||||
connection.connect().catch(done);
|
||||
}, done);
|
||||
});
|
||||
|
||||
it('Multiply disconnect calls', function() {
|
||||
this.api.disconnect();
|
||||
return this.api.disconnect();
|
||||
});
|
||||
|
||||
it('reconnect', function() {
|
||||
return this.api.connection.reconnect();
|
||||
});
|
||||
|
||||
it('NotConnectedError', function() {
|
||||
const connection = new utils.common.Connection('url');
|
||||
return connection.getLedgerVersion().then(() => {
|
||||
assert(false, 'Should throw NotConnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.NotConnectedError);
|
||||
});
|
||||
});
|
||||
|
||||
it('DisconnectedError', function() {
|
||||
this.api.connection._send = function() {
|
||||
this._ws.close();
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw DisconnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.DisconnectedError);
|
||||
});
|
||||
});
|
||||
|
||||
it('TimeoutError', function() {
|
||||
this.api.connection._send = function() {
|
||||
return Promise.resolve({});
|
||||
};
|
||||
const request = {command: 'server_info'};
|
||||
return this.api.connection.request(request, 1).then(() => {
|
||||
assert(false, 'Should throw TimeoutError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.TimeoutError);
|
||||
});
|
||||
});
|
||||
|
||||
it('DisconnectedError on send', function() {
|
||||
this.api.connection._ws.send = function(message, options, callback) {
|
||||
unused(message, options);
|
||||
callback({message: 'not connected'});
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw DisconnectedError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.DisconnectedError);
|
||||
assert.strictEqual(error.message, 'not connected');
|
||||
});
|
||||
});
|
||||
|
||||
it('ResponseFormatError', function() {
|
||||
this.api.connection._send = function(message) {
|
||||
const parsed = JSON.parse(message);
|
||||
setTimeout(() => {
|
||||
this._ws.emit('message', JSON.stringify({
|
||||
id: parsed.id,
|
||||
type: 'response',
|
||||
status: 'unrecognized'
|
||||
}));
|
||||
}, 2);
|
||||
return new Promise(() => {});
|
||||
};
|
||||
return this.api.getServerInfo().then(() => {
|
||||
assert(false, 'Should throw ResponseFormatError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.ResponseFormatError);
|
||||
});
|
||||
});
|
||||
|
||||
it('reconnect on unexpected close ', function(done) {
|
||||
this.api.connection.on('connected', () => {
|
||||
done();
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
this.api.connection._ws.close();
|
||||
}, 1);
|
||||
});
|
||||
|
||||
it('Multiply connect calls', function() {
|
||||
return this.api.connect().then(() => {
|
||||
return this.api.connect();
|
||||
});
|
||||
});
|
||||
|
||||
it('hasLedgerVersion', function() {
|
||||
return this.api.connection.hasLedgerVersion(8819951).then((result) => {
|
||||
assert(result);
|
||||
});
|
||||
});
|
||||
|
||||
it('Cannot connect because no server', function() {
|
||||
const connection = new utils.common.Connection();
|
||||
return connection.connect().then(() => {
|
||||
assert(false, 'Should throw ConnectionError');
|
||||
}).catch(error => {
|
||||
assert(error instanceof this.api.errors.ConnectionError);
|
||||
});
|
||||
});
|
||||
|
||||
it('connect multiserver error', function() {
|
||||
const options = {
|
||||
servers: ['wss://server1.com', 'wss://server2.com']
|
||||
};
|
||||
assert.throws(function() {
|
||||
const api = new RippleAPI(options);
|
||||
unused(api);
|
||||
}, this.api.errors.RippleError);
|
||||
});
|
||||
|
||||
it('connect throws error', function(done) {
|
||||
this.api.once('error', (type, info) => {
|
||||
assert.strictEqual(type, 'type');
|
||||
assert.strictEqual(info, 'info');
|
||||
done();
|
||||
});
|
||||
this.api.connection.emit('error', 'type', 'info');
|
||||
});
|
||||
|
||||
it('emit stream messages', function(done) {
|
||||
let transactionCount = 0;
|
||||
let pathFindCount = 0;
|
||||
this.api.connection.on('transaction', () => {
|
||||
transactionCount++;
|
||||
});
|
||||
this.api.connection.on('path_find', () => {
|
||||
pathFindCount++;
|
||||
});
|
||||
this.api.connection.on('1', () => {
|
||||
assert.strictEqual(transactionCount, 1);
|
||||
assert.strictEqual(pathFindCount, 1);
|
||||
done();
|
||||
});
|
||||
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'transaction'
|
||||
}));
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'path_find'
|
||||
}));
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'response', id: 1
|
||||
}));
|
||||
});
|
||||
|
||||
it('invalid message id', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'badMessage');
|
||||
assert.strictEqual(message,
|
||||
'{"type":"response","id":"must be integer"}');
|
||||
done();
|
||||
});
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
type: 'response', id: 'must be integer'
|
||||
}));
|
||||
});
|
||||
|
||||
it('propagate error message', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'slowDown');
|
||||
assert.strictEqual(message, 'slow down');
|
||||
done();
|
||||
});
|
||||
this.api.connection._onMessage(JSON.stringify({
|
||||
error: 'slowDown', error_message: 'slow down'
|
||||
}));
|
||||
});
|
||||
|
||||
it('unrecognized message type', function(done) {
|
||||
this.api.on('error', (type, message) => {
|
||||
assert.strictEqual(type, 'badMessage');
|
||||
assert.strictEqual(message, '{"type":"unknown"}');
|
||||
done();
|
||||
});
|
||||
|
||||
this.api.connection._onMessage(JSON.stringify({type: 'unknown'}));
|
||||
});
|
||||
});
|
||||
59
test/fixtures/requests/index.js
vendored
59
test/fixtures/requests/index.js
vendored
@@ -6,35 +6,42 @@ module.exports = {
|
||||
sell: require('./prepare-order-sell'),
|
||||
expiration: require('./prepare-order-expiration')
|
||||
},
|
||||
prepareOrderCancellation: require('./prepare-order-cancellation'),
|
||||
preparePayment: require('./prepare-payment'),
|
||||
preparePaymentMinAmountXRP: require('./prepare-payment-min-xrp'),
|
||||
preparePaymentMinAmount: require('./prepare-payment-min'),
|
||||
preparePaymentWrongAddress: require('./prepare-payment-wrong-address'),
|
||||
preparePaymentWrongAmount: require('./prepare-payment-wrong-amount'),
|
||||
preparePaymentWrongPartial: require('./prepare-payment-wrong-partial'),
|
||||
preparePaymentAllOptions: require('./prepare-payment-all-options'),
|
||||
preparePaymentNoCounterparty: require('./prepare-payment-no-counterparty'),
|
||||
prepareOrderCancellation: {
|
||||
simple: require('./prepare-order-cancellation'),
|
||||
withMemos: require('./prepare-order-cancellation-memos')
|
||||
},
|
||||
preparePayment: {
|
||||
normal: require('./prepare-payment'),
|
||||
minAmountXRP: require('./prepare-payment-min-xrp'),
|
||||
minAmount: require('./prepare-payment-min'),
|
||||
wrongAddress: require('./prepare-payment-wrong-address'),
|
||||
wrongAmount: require('./prepare-payment-wrong-amount'),
|
||||
wrongPartial: require('./prepare-payment-wrong-partial'),
|
||||
allOptions: require('./prepare-payment-all-options'),
|
||||
noCounterparty: require('./prepare-payment-no-counterparty')
|
||||
},
|
||||
prepareSettings: require('./prepare-settings'),
|
||||
prepareSuspendedPaymentCreation:
|
||||
require('./prepare-suspended-payment-creation'),
|
||||
prepareSuspendedPaymentCreationFull:
|
||||
require('./prepare-suspended-payment-creation-full'),
|
||||
prepareSuspendedPaymentExecution:
|
||||
require('./prepare-suspended-payment-execution'),
|
||||
prepareSuspendedPaymentExecutionSimple:
|
||||
require('./prepare-suspended-payment-execution-simple'),
|
||||
prepareSuspendedPaymentCancellation:
|
||||
require('./prepare-suspended-payment-cancellation'),
|
||||
prepareSuspendedPaymentCancellationMemos:
|
||||
require('./prepare-suspended-payment-cancellation-memos'),
|
||||
prepareSuspendedPaymentCreation: {
|
||||
normal: require('./prepare-suspended-payment-creation'),
|
||||
full: require('./prepare-suspended-payment-creation-full')
|
||||
},
|
||||
prepareSuspendedPaymentExecution: {
|
||||
normal: require('./prepare-suspended-payment-execution'),
|
||||
simple: require('./prepare-suspended-payment-execution-simple')
|
||||
},
|
||||
prepareSuspendedPaymentCancellation: {
|
||||
normal: require('./prepare-suspended-payment-cancellation'),
|
||||
memos: require('./prepare-suspended-payment-cancellation-memos')
|
||||
},
|
||||
prepareTrustline: {
|
||||
simple: require('./prepare-trustline-simple'),
|
||||
complex: require('./prepare-trustline'),
|
||||
frozen: require('./prepare-trustline-frozen.json')
|
||||
},
|
||||
sign: require('./sign'),
|
||||
signSuspended: require('./sign-suspended.json'),
|
||||
sign: {
|
||||
normal: require('./sign'),
|
||||
suspended: require('./sign-suspended.json')
|
||||
},
|
||||
getPaths: {
|
||||
normal: require('./getpaths/normal'),
|
||||
UsdToUsd: require('./getpaths/usd2usd'),
|
||||
@@ -47,8 +54,10 @@ module.exports = {
|
||||
invalid: require('./getpaths/invalid'),
|
||||
issuer: require('./getpaths/issuer')
|
||||
},
|
||||
getOrderbook: require('./get-orderbook'),
|
||||
getOrderbookWithXRP: require('./get-orderbook-with-xrp'),
|
||||
getOrderbook: {
|
||||
normal: require('./get-orderbook'),
|
||||
withXRP: require('./get-orderbook-with-xrp')
|
||||
},
|
||||
computeLedgerHash: {
|
||||
header: require('./compute-ledger-hash'),
|
||||
transactions: require('./compute-ledger-hash-transactions')
|
||||
|
||||
10
test/fixtures/requests/prepare-order-cancellation-memos.json
vendored
Normal file
10
test/fixtures/requests/prepare-order-cancellation-memos.json
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"orderSequence": 23,
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -9,5 +9,12 @@
|
||||
"currency": "XRP",
|
||||
"value": "2"
|
||||
},
|
||||
"immediateOrCancel": true
|
||||
"immediateOrCancel": true,
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
9
test/fixtures/requests/prepare-settings.json
vendored
9
test/fixtures/requests/prepare-settings.json
vendored
@@ -1,3 +1,10 @@
|
||||
{
|
||||
"domain": "ripple.com"
|
||||
"domain": "ripple.com",
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -5,5 +5,12 @@
|
||||
"qualityIn": 0.91,
|
||||
"qualityOut": 0.87,
|
||||
"ripplingDisabled": true,
|
||||
"frozen": false
|
||||
"frozen": false,
|
||||
"memos": [
|
||||
{
|
||||
"type": "test",
|
||||
"format": "plain/text",
|
||||
"data": "texted data"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
61
test/fixtures/responses/index.js
vendored
61
test/fixtures/responses/index.js
vendored
@@ -5,8 +5,10 @@ module.exports = {
|
||||
getAccountInfo: require('./get-account-info.json'),
|
||||
getBalances: require('./get-balances.json'),
|
||||
getBalanceSheet: require('./get-balance-sheet.json'),
|
||||
getOrderbook: require('./get-orderbook.json'),
|
||||
getOrderbookWithXRP: require('./get-orderbook-with-xrp.json'),
|
||||
getOrderbook: {
|
||||
normal: require('./get-orderbook.json'),
|
||||
withXRP: require('./get-orderbook-with-xrp.json')
|
||||
},
|
||||
getOrders: require('./get-orders.json'),
|
||||
getPaths: {
|
||||
XrpToUsd: require('./get-paths.json'),
|
||||
@@ -43,10 +45,14 @@ module.exports = {
|
||||
suspendedPaymentExecutionSimple:
|
||||
require('./get-transaction-suspended-payment-execution-simple.json')
|
||||
},
|
||||
getTransactions: require('./get-transactions.json'),
|
||||
getTransactionsOne: require('./get-transactions-one.json'),
|
||||
getTrustlines: require('./get-trustlines.json'),
|
||||
getTrustlinesAll: require('./get-trustlines-all.json'),
|
||||
getTransactions: {
|
||||
normal: require('./get-transactions.json'),
|
||||
one: require('./get-transactions-one.json')
|
||||
},
|
||||
getTrustlines: {
|
||||
filtered: require('./get-trustlines.json'),
|
||||
all: require('./get-trustlines-all.json')
|
||||
},
|
||||
getLedger: {
|
||||
header: require('./get-ledger'),
|
||||
full: require('./get-ledger-full'),
|
||||
@@ -56,10 +62,12 @@ module.exports = {
|
||||
prepareOrder: {
|
||||
buy: require('./prepare-order.json'),
|
||||
sell: require('./prepare-order-sell.json'),
|
||||
expiration: require('./prepare-order-expiration'),
|
||||
cancellation: require('./prepare-order-cancellation.json'),
|
||||
cancellationNoInstructions:
|
||||
require('./prepare-order-cancellation-no-instructions.json')
|
||||
expiration: require('./prepare-order-expiration')
|
||||
},
|
||||
prepareOrderCancellation: {
|
||||
normal: require('./prepare-order-cancellation.json'),
|
||||
withMemos: require('./prepare-order-cancellation-memos.json'),
|
||||
noInstructions: require('./prepare-order-cancellation-no-instructions.json')
|
||||
},
|
||||
preparePayment: {
|
||||
normal: require('./prepare-payment.json'),
|
||||
@@ -77,27 +85,30 @@ module.exports = {
|
||||
flagClear: require('./prepare-settings-flag-clear.json'),
|
||||
setTransferRate: require('./prepare-settings-set-transfer-rate.json'),
|
||||
fieldClear: require('./prepare-settings-field-clear.json'),
|
||||
noInstructions: require('./prepare-settings-no-instructions.json')
|
||||
noInstructions: require('./prepare-settings-no-instructions.json'),
|
||||
signed: require('./prepare-settings-signed.json')
|
||||
},
|
||||
prepareSuspendedPaymentCreation: {
|
||||
normal: require('./prepare-suspended-payment-creation'),
|
||||
full: require('./prepare-suspended-payment-creation-full')
|
||||
},
|
||||
prepareSuspendedPaymentExecution: {
|
||||
normal: require('./prepare-suspended-payment-execution'),
|
||||
simple: require('./prepare-suspended-payment-execution-simple')
|
||||
},
|
||||
prepareSuspendedPaymentCancellation: {
|
||||
normal: require('./prepare-suspended-payment-cancellation'),
|
||||
memos: require('./prepare-suspended-payment-cancellation-memos')
|
||||
},
|
||||
prepareSuspendedPaymentCreation:
|
||||
require('./prepare-suspended-payment-creation'),
|
||||
prepareSuspendedPaymentCreationFull:
|
||||
require('./prepare-suspended-payment-creation-full'),
|
||||
prepareSuspendedPaymentExecution:
|
||||
require('./prepare-suspended-payment-execution'),
|
||||
prepareSuspendedPaymentExecutionSimple:
|
||||
require('./prepare-suspended-payment-execution-simple'),
|
||||
prepareSuspendedPaymentCancellation:
|
||||
require('./prepare-suspended-payment-cancellation'),
|
||||
prepareSuspendedPaymentCancellationMemos:
|
||||
require('./prepare-suspended-payment-cancellation-memos'),
|
||||
prepareTrustline: {
|
||||
simple: require('./prepare-trustline-simple.json'),
|
||||
frozen: require('./prepare-trustline-frozen.json'),
|
||||
complex: require('./prepare-trustline.json')
|
||||
},
|
||||
sign: require('./sign.json'),
|
||||
signSuspended: require('./sign-suspended.json'),
|
||||
sign: {
|
||||
normal: require('./sign.json'),
|
||||
suspended: require('./sign-suspended.json')
|
||||
},
|
||||
submit: require('./submit.json'),
|
||||
ledgerEvent: require('./ledger-event.json')
|
||||
};
|
||||
|
||||
8
test/fixtures/responses/prepare-order-cancellation-memos.json
vendored
Normal file
8
test/fixtures/responses/prepare-order-cancellation-memos.json
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"txJSON": "{\"TransactionType\":\"OfferCancel\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"OfferSequence\":23,\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"Flags\":2147483648,\"LastLedgerSequence\":8819954,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
"maxLedgerVersion": 8819954
|
||||
}
|
||||
}
|
||||
16
test/fixtures/responses/prepare-order-sell.json
vendored
16
test/fixtures/responses/prepare-order-sell.json
vendored
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"txJSON": "{\"Flags\":2148139008,\"TransactionType\":\"OfferCreate\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"TakerGets\":{\"value\":\"10.1\",\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\"},\"TakerPays\":\"2000000\",\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
"maxLedgerVersion": 8820051
|
||||
}
|
||||
}
|
||||
{
|
||||
"txJSON": "{\"TransactionType\":\"OfferCreate\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"TakerGets\":{\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\",\"value\":\"10.1\"},\"TakerPays\":\"2000000\",\"Flags\":2148139008,\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
"maxLedgerVersion": 8820051
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,8 @@
|
||||
{"txJSON":"{\"TransactionType\":\"AccountSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"Domain\":\"726970706C652E636F6D\",\"Flags\":2147483648,\"LastLedgerSequence\":8819954,\"Fee\":\"12\",\"Sequence\":23}","instructions":{"fee":"0.000012","sequence":23,"maxLedgerVersion":8819954}}
|
||||
{
|
||||
"txJSON": "{\"TransactionType\":\"AccountSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"Domain\":\"726970706C652E636F6D\",\"Flags\":2147483648,\"LastLedgerSequence\":8819954,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
"maxLedgerVersion": 8819954
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"signedTransaction": "12000322000000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402207660BDEF67105CE1EBA9AD35DC7156BAB43FF1D47633199EE257D70B6B9AAFBF022045A812486A675750B5A3F37131E9F92299728D37FF6BB7195CA5EE881268CB4C770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304",
|
||||
"id": "29D23159EBA79170DCA5EF467CBC15114DBD35B7A8C3DBF76809BA354D00D250"
|
||||
}
|
||||
{
|
||||
"signedTransaction": "12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D87446304402202FBF6A6F74DFDA17C7341D532B66141206BC71A147C08DBDA6A950AA9A1741DC022055859A39F2486A46487F8DA261E3D80B4FDD26178A716A929F26377D1BEC7E43770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304F9EA7C04746573747D0B74657874656420646174617E0A706C61696E2F74657874E1F1",
|
||||
"id": "4755D26FAC39E3E477870D4E03CC6783DDDF967FFBE240606755D3D03702FC16"
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"txJSON": "{\"Flags\":2147483648,\"TransactionType\":\"AccountSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"Domain\":\"726970706C652E636F6D\",\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"txJSON": "{\"TransactionType\":\"AccountSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"Domain\":\"726970706C652E636F6D\",\"Flags\":2147483648,\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"txJSON": "{\"Flags\":2149711872,\"TransactionType\":\"TrustSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"LimitAmount\":{\"value\":\"10000\",\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\"},\"QualityIn\":910000000,\"QualityOut\":870000000,\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"txJSON": "{\"TransactionType\":\"TrustSet\",\"Account\":\"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59\",\"LimitAmount\":{\"currency\":\"USD\",\"issuer\":\"rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM\",\"value\":\"10000\"},\"Flags\":2149711872,\"QualityIn\":910000000,\"QualityOut\":870000000,\"Memos\":[{\"Memo\":{\"MemoData\":\"7465787465642064617461\",\"MemoType\":\"74657374\",\"MemoFormat\":\"706C61696E2F74657874\"}}],\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
|
||||
"instructions": {
|
||||
"fee": "0.000012",
|
||||
"sequence": 23,
|
||||
|
||||
32
test/fixtures/rippled/index.js
vendored
32
test/fixtures/rippled/index.js
vendored
@@ -5,11 +5,13 @@ module.exports = {
|
||||
success: require('./submit'),
|
||||
failure: require('./submit-failed')
|
||||
},
|
||||
ledger: require('./ledger'),
|
||||
ledgerNotFound: require('./ledger-not-found'),
|
||||
ledgerWithoutCloseTime: require('./ledger-without-close-time'),
|
||||
ledgerWithSettingsTx: require('./ledger-with-settings-tx'),
|
||||
ledgerWithStateAsHashes: require('./ledger-with-state-as-hashes'),
|
||||
ledger: {
|
||||
normal: require('./ledger'),
|
||||
notFound: require('./ledger-not-found'),
|
||||
withoutCloseTime: require('./ledger-without-close-time'),
|
||||
withSettingsTx: require('./ledger-with-settings-tx'),
|
||||
withStateAsHashes: require('./ledger-with-state-as-hashes')
|
||||
},
|
||||
subscribe: require('./subscribe'),
|
||||
unsubscribe: require('./unsubscribe'),
|
||||
account_info: {
|
||||
@@ -17,14 +19,20 @@ module.exports = {
|
||||
notfound: require('./account-info-not-found')
|
||||
},
|
||||
account_offers: require('./account-offers'),
|
||||
account_tx: require('./account-tx'),
|
||||
account_tx_one: require('./get-transactions-one'),
|
||||
account_tx: {
|
||||
normal: require('./account-tx'),
|
||||
one: require('./get-transactions-one')
|
||||
},
|
||||
gateway_balances: require('./gateway-balances'),
|
||||
book_offers: require('./book-offers'),
|
||||
book_offers_1: require('./book-offers-1'),
|
||||
book_offers_2: require('./book-offers-2'),
|
||||
server_info: require('./server-info'),
|
||||
server_info_error: require('./server-info-error'),
|
||||
book_offers: {
|
||||
fabric: require('./book-offers'),
|
||||
usd_xrp: require('./book-offers-usd-xrp'),
|
||||
xrp_usd: require('./book-offers-xrp-usd')
|
||||
},
|
||||
server_info: {
|
||||
normal: require('./server-info'),
|
||||
error: require('./server-info-error')
|
||||
},
|
||||
path_find: {
|
||||
generate: require('./path-find'),
|
||||
sendUSD: require('./path-find-send-usd'),
|
||||
|
||||
17
test/integration/broadcast-test.js
Normal file
17
test/integration/broadcast-test.js
Normal file
@@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
const {RippleAPIBroadcast} = require('../../src');
|
||||
|
||||
function main() {
|
||||
const servers = ['wss://s1.ripple.com', 'wss://s2.ripple.com'];
|
||||
const api = new RippleAPIBroadcast(servers);
|
||||
api.connect().then(() => {
|
||||
api.getServerInfo().then(info => {
|
||||
console.log(JSON.stringify(info, null, 2));
|
||||
});
|
||||
api.on('ledger', ledger => {
|
||||
console.log(JSON.stringify(ledger, null, 2));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -58,7 +58,7 @@ function testTransaction(testcase, type, lastClosedLedgerVersion, prepared) {
|
||||
}
|
||||
|
||||
function setup() {
|
||||
this.api = new RippleAPI({servers: ['wss://s1.ripple.com']});
|
||||
this.api = new RippleAPI({server: 'wss://s1.ripple.com'});
|
||||
console.log('CONNECTING...');
|
||||
return this.api.connect().then(() => {
|
||||
console.log('CONNECTED...');
|
||||
|
||||
@@ -97,9 +97,9 @@ module.exports = function(port) {
|
||||
mock.on('request_server_info', function(request, conn) {
|
||||
assert.strictEqual(request.command, 'server_info');
|
||||
if (mock.returnErrorOnServerInfo) {
|
||||
conn.send(createResponse(request, fixtures.server_info_error));
|
||||
conn.send(createResponse(request, fixtures.server_info.error));
|
||||
} else {
|
||||
conn.send(createResponse(request, fixtures.server_info));
|
||||
conn.send(createResponse(request, fixtures.server_info.normal));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -139,19 +139,20 @@ module.exports = function(port) {
|
||||
mock.on('request_ledger', function(request, conn) {
|
||||
assert.strictEqual(request.command, 'ledger');
|
||||
if (request.ledger_index === 34) {
|
||||
conn.send(createLedgerResponse(request, fixtures.ledgerNotFound));
|
||||
conn.send(createLedgerResponse(request, fixtures.ledger.notFound));
|
||||
} else if (request.ledger_index === 6) {
|
||||
conn.send(createResponse(request, fixtures.ledgerWithStateAsHashes));
|
||||
conn.send(createResponse(request, fixtures.ledger.withStateAsHashes));
|
||||
} else if (request.ledger_index === 9038215) {
|
||||
conn.send(createLedgerResponse(request, fixtures.ledgerWithoutCloseTime));
|
||||
conn.send(
|
||||
createLedgerResponse(request, fixtures.ledger.withoutCloseTime));
|
||||
} else if (request.ledger_index === 4181996) {
|
||||
conn.send(createLedgerResponse(request, fixtures.ledgerWithSettingsTx));
|
||||
conn.send(createLedgerResponse(request, fixtures.ledger.withSettingsTx));
|
||||
} else if (request.ledger_index === 38129) {
|
||||
const response = _.assign({}, fixtures.ledger,
|
||||
const response = _.assign({}, fixtures.ledger.normal,
|
||||
{result: {ledger: fullLedger}});
|
||||
conn.send(createLedgerResponse(request, response));
|
||||
} else {
|
||||
conn.send(createLedgerResponse(request, fixtures.ledger));
|
||||
conn.send(createLedgerResponse(request, fixtures.ledger.normal));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -263,7 +264,7 @@ module.exports = function(port) {
|
||||
if (request.account === addresses.ACCOUNT) {
|
||||
conn.send(transactionsResponse(request));
|
||||
} else if (request.account === addresses.OTHER_ACCOUNT) {
|
||||
conn.send(createResponse(request, fixtures.account_tx_one));
|
||||
conn.send(createResponse(request, fixtures.account_tx.one));
|
||||
} else {
|
||||
assert(false, 'Unrecognized account address: ' + request.account);
|
||||
}
|
||||
@@ -279,16 +280,18 @@ module.exports = function(port) {
|
||||
|
||||
mock.on('request_book_offers', function(request, conn) {
|
||||
if (request.taker_pays.issuer === 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') {
|
||||
conn.send(createResponse(request, fixtures.book_offers_2));
|
||||
conn.send(createResponse(request, fixtures.book_offers.xrp_usd));
|
||||
} else if (request.taker_gets.issuer
|
||||
=== 'rp8rJYTpodf8qbSCHVTNacf8nSW8mRakFw') {
|
||||
conn.send(createResponse(request, fixtures.book_offers_1));
|
||||
conn.send(createResponse(request, fixtures.book_offers.usd_xrp));
|
||||
} else if (isBTC(request.taker_gets.currency)
|
||||
&& isUSD(request.taker_pays.currency)) {
|
||||
conn.send(fixtures.book_offers.requestBookOffersBidsResponse(request));
|
||||
conn.send(
|
||||
fixtures.book_offers.fabric.requestBookOffersBidsResponse(request));
|
||||
} else if (isUSD(request.taker_gets.currency)
|
||||
&& isBTC(request.taker_pays.currency)) {
|
||||
conn.send(fixtures.book_offers.requestBookOffersAsksResponse(request));
|
||||
conn.send(
|
||||
fixtures.book_offers.fabric.requestBookOffersAsksResponse(request));
|
||||
} else {
|
||||
assert(false, 'Unrecognized order book: ' + JSON.stringify(request));
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ function getFreePort(callback) {
|
||||
|
||||
function setupMockRippledConnection(testcase, port, done) {
|
||||
testcase.mockRippled = createMockRippled(port);
|
||||
testcase.api = new RippleAPI({servers: ['ws://localhost:' + port]});
|
||||
testcase.api = new RippleAPI({server: 'ws://localhost:' + port});
|
||||
testcase.api.connect().then(() => {
|
||||
testcase.api.once('ledger', () => done());
|
||||
testcase.api.connection._ws.emit('message', JSON.stringify(ledgerClosed));
|
||||
|
||||
Reference in New Issue
Block a user