Compare commits

..

50 Commits

Author SHA1 Message Date
Elliot Lee
a29ec1b8c7 Release 1.0.2 2018-10-16 12:28:24 -07:00
Elliot Lee
232a760a58 yarn: Add integrity hashes to yarn.lock
Added in yarn v1.10.0, see https://github.com/yarnpkg/yarn/pull/5042
2018-10-16 12:24:15 -07:00
Elliot Lee
f4ad04d334 Exclude SendMax from XRP to XRP payments (#957)
Fix #954
2018-10-16 12:21:29 -07:00
Cory Perkins
64745017e9 book_offers returns offers type OfferLedgerEntry (#951)
* rippled-api function book_offers returns offers in the format of OfferLedgerEntry not OfferCreateTransaction
* updated type of account_objects
2018-10-02 02:14:17 -07:00
Elliot Lee
37edede728 Use object instead of Object (#936) 2018-10-02 02:13:28 -07:00
Elliot Lee
f785605db8 Release 1.0.1 2018-09-27 19:01:38 -07:00
Elliot Lee
01ad30ab07 Fix typos in ledger_entries.ts 2018-09-19 14:24:02 -07:00
Cory Perkins
e08d507462 Add remaining LedgerEntry types (#943)
* Replaced the union with 'any' in the LedgerEntry type
* Added DepositPreauthLedgerEntry (new in rippled 1.1.0)
2018-09-19 14:21:52 -07:00
wudanjs
4c23bd5ad3 Include memos when parsing trustlines (#949) 2018-09-19 14:17:38 -07:00
Scott M Sunarto
b15abd5376 Update server regex to accommodate UDS (#944) 2018-09-18 11:47:46 -07:00
Elliot Lee
79971f906b Update release notes 2018-09-11 18:45:52 -07:00
Elliot Lee
9eec98778f Expose validation methods (#932)
Merge branch 'movitto-expose_validation_methods' into develop
2018-09-11 18:33:55 -07:00
Elliot Lee
dcd0e14142 Add test of deriveKeypair with ed25519 secret 2018-09-11 18:33:07 -07:00
Elliot Lee
cfcbc9aab7 Update checksums for 1.0.0 2018-09-10 14:52:14 -07:00
Mo Morsi
a80de5658a Move deriveKeypair and deriveAddress to offline module 2018-09-09 09:39:25 -04:00
Mo Morsi
34215eb309 Add docs for newly exposed API methods 2018-09-09 09:39:25 -04:00
Mo Morsi
9458005d7f Add tests for newly exposed API methods 2018-09-09 09:39:25 -04:00
Mo Morsi
5f36df0172 Expose deriveKeypair, deriveAddress, isValidAddress, and isValidSecret to the public API 2018-09-09 09:39:25 -04:00
Elliot Lee
3ff4929a49 Fix PendingLedgerVersionError message and export FormattedTransactionType (#941) 2018-09-04 18:31:24 -07:00
Elliot Lee
4bea69d647 Release 1.0.0 2018-08-30 14:30:57 -07:00
Elliot Lee
09541dae86 docs: rippled APIs use issuer 2018-08-30 14:12:45 -07:00
Elliot Lee
bcbcc53c87 No `--coverage' option anymore with nyc
See https://github.com/istanbuljs/nyc
2018-08-30 13:41:52 -07:00
Elliot Lee
76f120bec9 Merge branch 'getLedger-includeRawTransaction-2' into develop 2018-08-30 13:30:18 -07:00
Elliot Lee
f8bf28876d if statements must be braced 2018-08-30 13:29:50 -07:00
wilsonianb
b03795df09 Add hidden computeTreeHashes option 2018-08-30 13:29:50 -07:00
Elliot Lee
dbe20d6574 getLedger: include raw transaction with each transaction
computeLedgerHash: support new getLedger response by using
rawTransaction

BREAKING CHANGES:

* Remove the `rawTransactions` field and replace it with a new `rawTransaction` field in each transaction.
* Rename the `metaData` field (in each raw transaction) to `meta` (for consistency with rippled's `tx` method).
* Add `ledger_index` to each raw transaction.
2018-08-30 13:28:52 -07:00
Elliot Lee
0550fab73e Update escrowCreation error message and docs (#934)
Fix #933
2018-08-29 19:03:33 -07:00
Elliot Lee
3f2d9d198e computeLedgerHash - add requireRawTransactions option 2018-08-28 17:31:12 -07:00
Elliot Lee
b9c953fce6 Fix getPaths (#930)
* getPaths:
  * Filter paths correctly
  * Use correct value when XRP is the destination currency
2018-08-23 17:37:02 -07:00
Elliot Lee
181cfd69de Prevent 'amount' from being misinterpreted (#924)
The 'amount' field should almost never be used.
With partial payments, the field can show an amount that is
significantly less than the amount that the transaction actually
delivered. This change sets amount to 0 XRP when it may be misleading.

This change omits the `amount` when parsing payment transactions.
See `HISTORY.md` for recommended alternatives.
2018-08-23 16:17:23 -07:00
Elliot Lee
569766b8f8 Rename json schemas (#931)
Rename files for consistency with their titles:

* Rename amount-base to amountbase
* Rename tx-hash to transaction-hash
* Rename id to transactionHash
* Rename objects/settings.json to objects/settings-plus-memos.json
* Rename ledgerversion to ledger-version
2018-08-22 14:41:41 -07:00
Elliot Lee
53a232ebdc Update docs 2018-08-14 20:05:50 -07:00
Elliot Lee
4c9a2ff538 Improve Order docs. Fix #776 2018-08-14 19:27:50 -07:00
Elliot Lee
dc623cd049 Release 1.0.0-beta.5 2018-08-11 01:38:36 -07:00
Elliot Lee
7cd517268b Fix error TS2307: Cannot find module 2018-08-11 01:35:47 -07:00
Elliot Lee
2438295e70 Release 1.0.0-beta.4 2018-08-10 14:58:19 -07:00
Elliot Lee
f5e1a4a588 Revert "Expose validation methods in public api"
This reverts commit 9e9a0a7d9b.

We should move methods like deriveKeypair and deriveAddress
off of the schemaValidator object.
2018-08-10 14:54:01 -07:00
Mo Morsi
9e9a0a7d9b Expose validation methods in public api
Updated to fix tests
2018-08-06 16:09:04 -07:00
Elliot Lee
1c68283d1e ES6: omit property value since it matches the variable name 2018-07-28 00:42:37 -07:00
Elliot Lee
28796d37cb Update TypeScript to 2.9.2 2018-07-28 00:18:58 -07:00
Elliot Lee
067bc48d4e Add prepareTransaction() (#898)
* Export iso8601ToRippleTime(), txFlags, convertStringToHex()

* Fix a bug that caused fees exceeding 999 to throw an error

e.g. '1,000' would not be recognized as a valid number.
To use 6 decimal places, toFixed should be used instead of toFormat.
2018-07-26 12:24:29 -07:00
Fred K. Schott
b94698df0b Update some API methods to use api.request() internally (#896)
* use any instead of object
2018-07-26 12:23:07 -07:00
Elliot Lee
4f40b5cb6d Update README.md - How to build ripple-lib (#837) 2018-07-25 12:09:55 -07:00
Elliot Lee
14704eee6b Add more tests of getFee (#897) 2018-07-25 01:53:27 -07:00
Elliot Lee
860f6a6cd8 Release 1.0.0-beta.3 2018-07-17 22:39:00 -07:00
Elliot Lee
7a928804ec feat: add payment channel details to tx (2) (#920)
* Bump transactionparser to v0.7.1 and update output schema
* yarn docgen for required `threshold` and `weights`
2018-07-17 22:22:07 -07:00
adrianhopebailie
14444bea3f feat: add payment channel details to tx 2018-07-17 22:20:47 -07:00
Rome Reginelli
47a139fdff Fix text/plain MIMETYPE in examples with memos (#914) 2018-07-03 17:18:46 -07:00
Brandon Wilson
4e30b9b2fa Require threshold and weights in signers settings (#909)
Fixes #908
2018-07-02 16:27:03 -07:00
Elliot Lee
2112d4c0b3 Round XRP fee to 6 decimal places (#912)
* Round XRP fee to 6 decimal places

Fix #911
2018-06-28 17:59:00 -07:00
149 changed files with 3995 additions and 1045 deletions

View File

@@ -1,5 +1,138 @@
# ripple-lib Release History
## 1.0.2 (2018-10-16)
+ Fix #954: Exclude SendMax from all XRP to XRP payments (thanks @jefftrudeau)
+ TypeScript
+ book_offers returns offers type OfferLedgerEntry (#951)
+ Use `object` (#936)
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
2556fe17296e127ed44e7066e90a6175e2b164f00ca3c1aa7b1c554f31c688dd ripple-1.0.2-debug.js
e0342ea21eac32a1024c62034fba09c6f26dd3e7371b23ea1e153e03135cd590 ripple-1.0.2-min.js
c7286c517497d018d02d09257e81172b61d36c8b9885a077af68e8133c3b3b9b ripple-1.0.2.js
```
## 1.0.1 (2018-09-27)
+ Add address/secret/key validation and derivation methods ([#932](https://github.com/ripple/ripple-lib/pull/932))
+ `isValidAddress(address: string) : boolean`: Checks if the specified string contains a valid address.
+ `isValidSecret(secret: string): boolean`: Checks if the specified string contains a valid secret.
+ `deriveKeypair(seed: string): {privateKey: string, publicKey: string}`: Derive a public and private key from a seed.
+ `deriveAddress(publicKey: string): string`: Derive an XRP Ledger address from a public key.
+ To derive an address from a secret:
1. Derive the public key from the secret.
2. Derive the address from the public key.
+ Example: `const address = api.deriveAddress(api.deriveKeypair(secret).publicKey)`
+ Update server regex to accommodate UDS (#944)
+ Include memos when parsing trustlines (#949)
+ Add remaining LedgerEntry types (#943)
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
9b6408641ce83659afcd5765c256c35829a4fcb4c3244dc9ca6bf27c871a45c4 ripple-1.0.1-debug.js
7ab2b69fe59c2d4a74638116e2ba3b387155eb2d23e48a01bbf7beb72911f898 ripple-1.0.1-min.js
8bb4dcad9ce25a27003b1d73d71ddf41b8a5af02ece4ebbfeaff4aeb91f3b8c4 ripple-1.0.1.js
```
## 1.0.0 (2018-08-30)
We are pleased to announce the release of `ripple-lib` version 1.0.0.
This version features a range of changes and improvements that make the library
more capable and flexible. It includes new methods for accessing rippled APIs,
including subscriptions.
When using this version with `rippled` for online functionality, we recommend
using `rippled` version 1.0.1 or later.
Here is a summary of the changes since `ripple-lib` version 0.22.0, which was
the last non-beta version.
### New Features
+ [Add `request()`, `hasNextPage()`, and `requestNextPage()` for accessing `rippled`
APIs](https://github.com/ripple/ripple-lib/blob/09541dae86bc859bf5928ac65b2645dfaaf7f8b1/docs/index.md#rippled-apis).
+ Add `prepareTransaction()` for preparing raw `txJSON`.
+ XRP amounts can be specified in drops. Also, `xrpToDrops()` and `dropsToXrp()`
are available to make conversions.
+ `getTransaction` responses can include a new `channelChanges` property that
describes the details of a payment channel.
### Data Validation and Errors
+ [Amounts in drops and XRP are checked for
validity](https://github.com/ripple/ripple-lib/blob/develop/HISTORY.md#100-beta1-2018-05-24).
+ [A maximum fee is now
imposed](https://github.com/ripple/ripple-lib/blob/develop/HISTORY.md#100-beta2-2018-06-08). Exceeding it causes a `ValidationError` to be
thrown.
+ Errors are improved and more data validation was added.
+ Bug fix: `getPaths` now filters paths correctly and works correctly when the
destination currency is XRP.
### Breaking Changes
The following changes were introduced in 1.0.0.
+ `getTransaction()` and `getTransactions()`
+ The `specification.destination.amount` field has been removed from the parsed transaction response.
+ To determine the amount that a transaction delivered, use `outcome.deliveredAmount`.
+ If you require the provisional requested `Amount` from the original transaction:
+ Use `getTransaction`'s `includeRawTransaction` option, or
+ Use `getTransactions`'s `includeRawTransactions` option, or
+ Use the rippled APIs directly with `request`. For example, call the API methods `tx`, `account_tx`, etc.
+ `getLedger()` response object
+ The `rawTransactions` field has been removed (for consistency with `getTransaction()` and `getTransactions()`).
+ Instead, within each `transaction`, use the new `rawTransaction` JSON string.
+ The `metaData` field has been renamed to `meta` for consistency with rippled's `tx` method.
+ `ledger_index` has been added to each raw transaction.
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
06e5efcb6846ad45dedfd85cfa2ef4bdeb608b15ccbfb60b872c995d97342426 ripple-1.0.0-debug.js
cdb26b928a89ce228c727d1ff966df266eb46b2f76bd94f81cbeb0a9d75febf0 ripple-1.0.0-min.js
f74ee804e8a945a994e4e3901a0a3eb52292fbdcbff61ed30cefb8ffbcba50c3 ripple-1.0.0.js
```
## 1.0.0-beta.5 (2018-08-11)
+ [Fix a TypeScript error by importing the `Prepare` type](https://github.com/ripple/ripple-lib/commit/7cd517268bda5fe74b91dad02fedf8b51b7eae9b)
## 1.0.0-beta.4 (2018-08-10)
+ [Add `prepareTransaction()`](https://github.com/ripple/ripple-lib/pull/898)
+ Internal improvements and cleanup
## 1.0.0-beta.3 (2018-07-17)
+ For payment channel transactions, `getTransaction` includes a new
`channelChanges` property that describes the details of the payment channel.
(#920)
### Bug Fixes
+ A bug caused calculated fees to use too many decimal places. This was fixed by
rounding fees to 6 decimal places. (#912)
+ When using the Settings transaction to set up a multi-signing list, the
threshold and weights fields are required. (#909)
+ Docs: Fix the MIMETYPE in examples with memos. (#914)
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
460dbb521e24c44cb53dabc1a74feeca33d031b44d889dd5b51103ca92d51de6 ripple-1.0.0-beta.3-debug.js
cccfd24973c6b7990d9e933a589175dae26249825737fff4f2f73d8558a3f186 ripple-1.0.0-beta.3-min.js
0dc456a58fb078347d9920310621595905085595d73c2b8fe96bea73bcf35450 ripple-1.0.0-beta.3.js
```
## 1.0.0-beta.2 (2018-06-08)
### Breaking Changes

View File

@@ -28,7 +28,7 @@ $ yarn add ripple-lib
Then see the [documentation](https://github.com/ripple/ripple-lib/blob/develop/docs/index.md) and [code samples](https://github.com/ripple/ripple-lib/tree/develop/docs/samples).
### Mailing lists
### Mailing Lists
We have a low-traffic mailing list for announcements of new ripple-lib releases. (About 1 email per week)
@@ -38,11 +38,29 @@ If you're using the XRP Ledger in production, you should run a [rippled server](
+ [Subscribe to ripple-server](https://groups.google.com/forum/#!forum/ripple-server)
## Running tests
## Development
To build the library for Node.js:
```
$ yarn compile
```
The TypeScript compiler will [output](./tsconfig.json#L7) the resulting JS files in `./dist/npm/`.
To build the library for the browser:
```
$ yarn build
```
Gulp will [output](./Gulpfile.js) the resulting JS files in `./build/`.
For more details, see the `scripts` in `package.json`.
## Running Tests
1. Clone the repository
2. `cd` into the repository and install dependencies with `yarn install`
3. `yarn test` or `yarn test --coverage` (`istanbul` will create coverage reports in `coverage/lcov-report/`)
3. `yarn test`
## Generating Documentation

View File

@@ -76,6 +76,10 @@
- [combine](#combine)
- [submit](#submit)
- [generateAddress](#generateaddress)
- [isValidAddress](#isvalidaddress)
- [isValidSecret](#isvalidsecret)
- [deriveKeypair](#derivekeypair)
- [deriveAddress](#deriveaddress)
- [signPaymentChannelClaim](#signpaymentchannelclaim)
- [verifyPaymentChannelClaim](#verifypaymentchannelclaim)
- [computeLedgerHash](#computeledgerhash)
@@ -156,7 +160,7 @@ maxFeeXRP | string | *Optional* Maximum fee to use with transactions, in XRP. Mu
passphrase | string | *Optional* The passphrase for the private key of the client.
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**.
server | uri string | *Optional* URI for rippled websocket port to connect to. Must start with `wss://` or `ws://`.
server | uri string | *Optional* URI for rippled websocket port to connect to. Must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.
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.
@@ -363,7 +367,7 @@ source | object | The source of the funds to be sent.
*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](#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.* 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 cannot be used with `destination.minAmount`.)
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
*destination.* address | [address](#address) | The address to send to.
*destination.* minAmount | [laxAmount](#amount) | The minimum amount to be delivered. (This field is exclusive with destination.amount)
@@ -430,7 +434,7 @@ ripplingDisabled | boolean | *Optional* If true, payments cannot ripple through
"memos": [
{
"type": "test",
"format": "plain/text",
"format": "text/plain",
"data": "texted data"
}
]
@@ -448,12 +452,14 @@ direction | string | Equal to "buy" for buy orders and "sell" for sell orders.
quantity | [amount](#amount) | The amount of currency to buy or sell.
totalPrice | [amount](#amount) | The total price to be paid for the `quantity` to be bought or sold.
expirationTime | date-time string | *Optional* Time after which the offer is no longer active, as an [ISO 8601 date-time](https://en.wikipedia.org/wiki/ISO_8601).
fillOrKill | boolean | *Optional* Treat the offer as a [Fill or Kill order](http://en.wikipedia.org/wiki/Fill_or_kill). Only attempt to match existing offers in the ledger, and only do so if the entire quantity can be exchanged.
immediateOrCancel | boolean | *Optional* Treat the offer as an [Immediate or Cancel order](http://en.wikipedia.org/wiki/Immediate_or_cancel). If enabled, the offer will never become a ledger node: it only attempts to match existing offers in the ledger.
fillOrKill | boolean | *Optional* Treat the offer as a [Fill or Kill order](http://en.wikipedia.org/wiki/Fill_or_kill). Only attempt to match existing offers in the ledger, and only do so if the entire quantity can be exchanged. This cannot be used with `immediateOrCancel`.
immediateOrCancel | boolean | *Optional* Treat the offer as an [Immediate or Cancel order](http://en.wikipedia.org/wiki/Immediate_or_cancel). If enabled, the offer will never become a ledger node: it only attempts to match existing offers in the ledger. This cannot be used with `fillOrKill`.
memos | [memos](#transaction-memos) | *Optional* Array of memos to attach to the transaction.
orderToReplace | [sequence](#account-sequence-number) | *Optional* The [account sequence number](#account-sequence-number) of an order to cancel before the new order is created, effectively replacing the old order.
passive | boolean | *Optional* If enabled, the offer will not consume offers that exactly match it, and instead becomes an Offer node in the ledger. It will still consume offers that cross it.
The following invalid flag combination causes a `ValidationError`: `immediateOrCancel` and `fillOrKill`. These fields are mutually exclusive, and cannot both be set at the same time.
### Example
@@ -516,8 +522,8 @@ regularKey | [address](#address),null | *Optional* The public key of a new keypa
requireAuthorization | boolean | *Optional* If set, this account must individually approve other users in order for those users to hold this accounts issuances.
requireDestinationTag | boolean | *Optional* Requires incoming payments to specify a destination tag.
signers | object | *Optional* Settings that determine what sets of accounts can be used to sign a transaction on behalf of this account using multisigning.
*signers.* threshold | integer | *Optional* A target number for the signer weights. A multi-signature from this list is valid only if the sum weights of the signatures provided is equal or greater than this value. To delete the signers setting, use the value `0`.
*signers.* weights | array | *Optional* Weights of signatures for each signer.
*signers.* threshold | integer | A target number for the signer weights. A multi-signature from this list is valid only if the sum weights of the signatures provided is equal or greater than this value. To delete the signers setting, use the value `0`.
*signers.* weights | array | Weights of signatures for each signer.
*signers.* weights[] | object | An association of an address and a weight.
*signers.weights[].* address | [address](#address) | A Ripple account address
*signers.weights[].* weight | integer | The weight that the signature of this account counts as towards the threshold.
@@ -532,7 +538,7 @@ transferRate | number,null | *Optional* The fee to charge when users transfer t
"memos": [
{
"type": "test",
"format": "plain/text",
"format": "text/plain",
"data": "texted data"
}
]
@@ -761,11 +767,14 @@ ripple-lib relies on [rippled APIs](https://ripple.com/build/rippled-apis/) for
* Use `hasNextPage()` to determine whether a response has more pages. This is true when the response includes a [`marker` field](https://ripple.com/build/rippled-apis/#markers-and-pagination).
* Use `requestNextPage()` to request the next page of data.
When using rippled APIs, [specify XRP amounts in drops](https://ripple.com/build/rippled-apis/#specifying-currency-amounts). 1 XRP = 1000000 drops.
When using rippled APIs:
* [Specify XRP amounts in drops](https://developers.ripple.com/basic-data-types.html#specifying-currency-amounts).
* [Specify timestamps as the number of seconds since the "Ripple Epoch"](https://developers.ripple.com/basic-data-types.html#specifying-time).
* Instead of `counterparty`, use `issuer`.
## Listening to streams
The `rippled` server can push updates to your client when various events happen. Refer to [Subscriptions in the `rippled` API docs](https://ripple.com/build/rippled-apis/#subscriptions) for details.
The `rippled` server can push updates to your client when various events happen. Refer to [Subscriptions in the `rippled` API docs](https://developers.ripple.com/subscription-methods.html) for details.
Note that the `streams` parameter for generic streams takes an array. For example, to subscribe to the `validations` stream, use `{ streams: [ 'validations' ] }`.
@@ -1075,6 +1084,8 @@ return api.getServerInfo().then(info => {/* ... */});
Returns the estimated transaction fee for the rippled server the RippleAPI instance is connected to.
This will use the [feeCushion parameter](#parameters) provided to the RippleAPI constructor, or the default value of `1.2`.
### Parameters
Name | Type | Description
@@ -1083,7 +1094,7 @@ cushion | number | *Optional* The fee is the product of the base fee, the `load_
### Return Value
This method returns a promise that resolves with a string encoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
This method returns a promise that resolves with a string-encoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
### Example
@@ -1092,7 +1103,7 @@ return api.getFee().then(fee => {/* ... */});
```
```json
"0.012"
"0.000012"
```
## getLedgerVersion
@@ -1124,7 +1135,7 @@ return api.getLedgerVersion().then(ledgerVersion => {
## getTransaction
`getTransaction(id: string, options: Object): Promise<Object>`
`getTransaction(id: string, options: object): Promise<object>`
Retrieves a transaction by its [Transaction ID](#transaction-id).
@@ -1132,8 +1143,9 @@ Retrieves a transaction by its [Transaction ID](#transaction-id).
Name | Type | Description
---- | ---- | -----------
id | [id](#transaction-id) | A hash of a transaction used to identify the transaction, represented in hexadecimal.
options | object | *Optional* Options to limit the ledger versions to search.
id | [transactionHash](#transaction-id) | A hash of a transaction used to identify the transaction, represented in hexadecimal.
options | object | *Optional* Options to limit the ledger versions to search and/or to include raw transaction data.
*options.* includeRawTransaction | object | *Optional* Include raw transaction data. For advanced users; exercise caution when interpreting this data.
*options.* maxLedgerVersion | integer | *Optional* The highest ledger version to search
*options.* maxLedgerVersion | string | *Optional* The highest ledger version to search
*options.* minLedgerVersion | integer | *Optional* The lowest ledger version to search.
@@ -1145,16 +1157,16 @@ This method returns a promise that resolves with a transaction object containing
Name | Type | Description
---- | ---- | -----------
id | [id](#transaction-id) | A hash of the transaction that can be used to identify it.
id | [transactionHash](#transaction-id) | A hash of the transaction that can be used to identify it.
address | [address](#address) | The address of the account that initiated the transaction.
sequence | [sequence](#account-sequence-number) | The account sequence number of the transaction for the account that initiated it.
type | [transactionType](#transaction-types) | The type of the transaction.
specification | object | A specification that would produce the same outcome as this transaction. The structure of the specification depends on the value of the `type` field (see [Transaction Types](#transaction-types) for details). *Note:* This is **not** necessarily the same as the original specification.
specification | object | A specification that would produce the same outcome as this transaction. *Exception:* For payment transactions, this omits the `destination.amount` field, to prevent misunderstanding. The structure of the specification depends on the value of the `type` field (see [Transaction Types](#transaction-types) for details). *Note:* This is **not** necessarily the same as the original specification.
outcome | object | The outcome of the transaction (what effects it had).
*outcome.* result | string | Result code returned by rippled. See [Transaction Results](https://ripple.com/build/transactions/#full-transaction-response-list) for a complete list.
*outcome.* fee | [value](#value) | The XRP fee that was charged for the transaction.
*outcome.balanceChanges.* \* | array\<[balance](#amount)\> | Key is the ripple address; value is an array of signed amounts representing changes of balances for that address.
*outcome.orderbookChanges.* \* | array | Key is the maker's ripple address; value is an array of changes
*outcome.balanceChanges.* \* | array\<[balance](#amount)\> | Key is the XRP Ledger address; value is an array of signed amounts representing changes of balances for that address.
*outcome.orderbookChanges.* \* | array | Key is the maker's XRP Ledger address; value is an array of changes
*outcome.orderbookChanges.* \*[] | object | A change to an order.
*outcome.orderbookChanges.\*[].* direction | string | Equal to "buy" for buy orders and "sell" for sell orders.
*outcome.orderbookChanges.\*[].* quantity | [amount](#amount) | The amount to be bought or sold by the maker.
@@ -1166,8 +1178,10 @@ outcome | object | The outcome of the transaction (what effects it had).
*outcome.* ledgerVersion | integer | The ledger version that the transaction was validated in.
*outcome.* ledgerVersion | string | The ledger version that the transaction was validated in.
*outcome.* indexInLedger | integer | The ordering index of the transaction in the ledger.
*outcome.* channelChanges | object | *Optional* Properties reflecting the details of the payment channel.
*outcome.* deliveredAmount | [amount](#amount) | *Optional* For payment transactions, it is impossible to reliably compute the actual delivered amount from the balanceChanges due to fixed precision. If the payment is not a partial payment and the transaction succeeded, the deliveredAmount should always be considered to be the amount specified in the transaction.
*outcome.* timestamp | date-time string | *Optional* The timestamp when the transaction was validated. (May be missing when requesting transactions in binary mode.)
rawTransaction | string | *Optional* The raw transaction data as a JSON string. For advanced users only; exercise caution when interpreting this data.
### Example
@@ -1194,11 +1208,7 @@ return api.getTransaction(id).then(transaction => {
}
},
"destination": {
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM",
"amount": {
"currency": "USD",
"value": "0.001"
}
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"
},
"paths": "[[{\"currency\":\"USD\",\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"type\":48,\"type_hex\":\"0000000000000030\"},{\"account\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"currency\":\"USD\",\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"type\":49,\"type_hex\":\"0000000000000031\"}]]"
},
@@ -1277,7 +1287,7 @@ return api.getTransaction(id).then(transaction => {
## getTransactions
`getTransactions(address: string, options: Object): Promise<Array<Object>>`
`getTransactions(address: string, options: object): Promise<Array<object>>`
Retrieves historical transactions of an account.
@@ -1291,6 +1301,7 @@ options | object | *Optional* Options to filter the resulting transactions.
*options.* counterparty | [address](#address) | *Optional* If provided, only return transactions with this account as a counterparty to the transaction.
*options.* earliestFirst | boolean | *Optional* If true, sort transactions so that the earliest ones come first. By default, the newest transactions will come first.
*options.* excludeFailures | boolean | *Optional* If true, the result will omit transactions that did not succeed.
*options.* includeRawTransactions | object | *Optional* Include raw transaction data. For advanced users; exercise caution when interpreting this data.
*options.* initiated | boolean | *Optional* If true, return only transactions initiated by the account specified by `address`. If false, return only transactions not initiated by the account specified by `address`.
*options.* limit | integer | *Optional* If specified, return at most this many transactions.
*options.* maxLedgerVersion | integer | *Optional* Return only transactions in this ledger version or lower.
@@ -1336,11 +1347,7 @@ return api.getTransactions(address).then(transaction => {
}
},
"destination": {
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM",
"amount": {
"currency": "USD",
"value": "0.001"
}
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"
},
"paths": "[[{\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"currency\":\"USD\"},{\"account\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"currency\":\"USD\"}]]"
},
@@ -1433,11 +1440,7 @@ return api.getTransactions(address).then(transaction => {
}
},
"destination": {
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM",
"amount": {
"currency": "USD",
"value": "0.001"
}
"address": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM"
},
"paths": "[[{\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"currency\":\"USD\"},{\"account\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"issuer\":\"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo\",\"currency\":\"USD\"}]]"
},
@@ -1516,7 +1519,7 @@ return api.getTransactions(address).then(transaction => {
## getTrustlines
`getTrustlines(address: string, options: Object): Promise<Array<Object>>`
`getTrustlines(address: string, options: object): Promise<Array<object>>`
Returns trustlines for a specified account.
@@ -1661,7 +1664,7 @@ return api.getTrustlines(address).then(trustlines =>
## getBalances
`getBalances(address: string, options: Object): Promise<Array<Object>>`
`getBalances(address: string, options: object): Promise<Array<object>>`
Returns balances for a specified account.
@@ -1828,7 +1831,7 @@ return api.getBalances(address).then(balances =>
## getBalanceSheet
`getBalanceSheet(address: string, options: Object): Promise<Object>`
`getBalanceSheet(address: string, options: object): Promise<object>`
Returns aggregate balances by currency plus a breakdown of assets and obligations for a specified account.
@@ -1924,7 +1927,7 @@ return api.getBalanceSheet(address).then(balanceSheet =>
## getPaths
`getPaths(pathfind: Object): Promise<Array<Object>>`
`getPaths(pathfind: object): Promise<Array<object>>`
Finds paths to send a payment. Paths are options for how to route a payment.
@@ -1957,7 +1960,7 @@ source | object | Properties of the source of the payment.
*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](#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.* 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 cannot be used with `destination.minAmount`.)
*destination.* tag | integer | *Optional* An arbitrary unsigned 32-bit integer that identifies a reason for payment or a non-Ripple account.
*destination.* address | [address](#address) | The address to send to.
*destination.* minAmount | [laxAmount](#amount) | The minimum amount to be delivered. (This field is exclusive with destination.amount)
@@ -2046,7 +2049,7 @@ return api.getPaths(pathfind)
## getOrders
`getOrders(address: string, options: Object): Promise<Array<Object>>`
`getOrders(address: string, options: object): Promise<Array<object>>`
Returns open orders for the specified account. Open orders are orders that have not yet been fully executed and are still in the order book.
@@ -2427,7 +2430,7 @@ return api.getOrders(address).then(orders =>
## getOrderbook
`getOrderbook(address: string, orderbook: Object, options: Object): Promise<Object>`
`getOrderbook(address: string, orderbook: object, options: object): Promise<object>`
Returns open orders for the specified account. Open orders are orders that have not yet been fully executed and are still in the order book.
@@ -3531,7 +3534,7 @@ return api.getOrderbook(address, orderbook)
## getSettings
`getSettings(address: string, options: Object): Promise<Object>`
`getSettings(address: string, options: object): Promise<object>`
Returns settings for the specified account. Note: For account data that is not modifiable by the user, see [getAccountInfo](#getaccountinfo).
@@ -3566,8 +3569,8 @@ regularKey | [address](#address),null | *Optional* The public key of a new keypa
requireAuthorization | boolean | *Optional* If set, this account must individually approve other users in order for those users to hold this accounts issuances.
requireDestinationTag | boolean | *Optional* Requires incoming payments to specify a destination tag.
signers | object | *Optional* Settings that determine what sets of accounts can be used to sign a transaction on behalf of this account using multisigning.
*signers.* threshold | integer | *Optional* A target number for the signer weights. A multi-signature from this list is valid only if the sum weights of the signatures provided is equal or greater than this value. To delete the signers setting, use the value `0`.
*signers.* weights | array | *Optional* Weights of signatures for each signer.
*signers.* threshold | integer | A target number for the signer weights. A multi-signature from this list is valid only if the sum weights of the signatures provided is equal or greater than this value. To delete the signers setting, use the value `0`.
*signers.* weights | array | Weights of signatures for each signer.
*signers.* weights[] | object | An association of an address and a weight.
*signers.weights[].* address | [address](#address) | A Ripple account address
*signers.weights[].* weight | integer | The weight that the signature of this account counts as towards the threshold.
@@ -3610,7 +3613,7 @@ return api.getSettings(address).then(settings =>
## getAccountInfo
`getAccountInfo(address: string, options: Object): Promise<Object>`
`getAccountInfo(address: string, options: object): Promise<object>`
Returns information for the specified account. Note: For account data that is modifiable by the user, see [getSettings](#getsettings).
@@ -3983,7 +3986,7 @@ return api.getAccountObjects(address: address).then(objects =>
## getPaymentChannel
`getPaymentChannel(id: string): Promise<Object>`
`getPaymentChannel(id: string): Promise<object>`
Returns specified payment channel.
@@ -4039,7 +4042,7 @@ return api.getPaymentChannel(channelId).then(channel =>
## getLedger
`getLedger(options: Object): Promise<Object>`
`getLedger(options: object): Promise<object>`
Returns header information for the specified ledger (or the most recent validated ledger if no ledger is specified). Optionally, all the transactions that were validated in the ledger or the account state information can be returned with the ledger header.
@@ -4072,9 +4075,8 @@ parentCloseTime | date-time string | The time at which the previous ledger was c
totalDrops | [value](#value) | Total number of drops (1/1,000,000th of an XRP) in the network, as a quoted integer. (This decreases as transaction fees cause XRP to be destroyed.)
transactionHash | string | Hash of the transaction information included in this ledger.
rawState | string | *Optional* A JSON string containing all state data for this ledger in rippled JSON format.
rawTransactions | string | *Optional* A JSON string containing rippled format transaction JSON for all transactions that were validated in this ledger.
stateHashes | array\<string\> | *Optional* An array of hashes of all state data in this ledger.
transactionHashes | array\<[id](#transaction-id)\> | *Optional* An array of hashes of all transactions that were validated in this ledger.
transactionHashes | array\<[transactionHash](#transaction-id)\> | *Optional* An array of hashes of all transactions that were validated in this ledger.
transactions | array\<[getTransaction](#gettransaction)\> | *Optional* Array of all transactions that were validated in this ledger. Transactions are represented in the same format as the return value of [getTransaction](#gettransaction).
### Example
@@ -4103,7 +4105,7 @@ return api.getLedger()
## preparePayment
`preparePayment(address: string, payment: Object, instructions: Object): Promise<Object>`
`preparePayment(address: string, payment: object, instructions: object): Promise<object>`
Prepare a payment transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4173,7 +4175,7 @@ return api.preparePayment(address, payment).then(prepared =>
## prepareTrustline
`prepareTrustline(address: string, trustline: Object, instructions: Object): Promise<Object>`
`prepareTrustline(address: string, trustline: object, instructions: object): Promise<object>`
Prepare a trustline transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4217,7 +4219,7 @@ const trustline = {
"memos": [
{
"type": "test",
"format": "plain/text",
"format": "text/plain",
"data": "texted data"
}
]
@@ -4229,7 +4231,7 @@ return api.prepareTrustline(address, trustline).then(prepared =>
```json
{
"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}",
"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\":\"746578742F706C61696E\"}}],\"LastLedgerSequence\":8820051,\"Fee\":\"12\",\"Sequence\":23}",
"instructions": {
"fee": "0.000012",
"sequence": 23,
@@ -4241,7 +4243,7 @@ return api.prepareTrustline(address, trustline).then(prepared =>
## prepareOrder
`prepareOrder(address: string, order: Object, instructions: Object): Promise<Object>`
`prepareOrder(address: string, order: object, instructions: object): Promise<object>`
Prepare an order transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4309,7 +4311,7 @@ return api.prepareOrder(address, order)
## prepareOrderCancellation
`prepareOrderCancellation(address: string, orderCancellation: Object, 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).
@@ -4362,7 +4364,7 @@ return api.prepareOrderCancellation(address, orderCancellation)
## prepareSettings
`prepareSettings(address: string, settings: Object, instructions: Object): Promise<Object>`
`prepareSettings(address: string, settings: object, instructions: object): Promise<object>`
Prepare a settings transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4400,7 +4402,7 @@ const settings = {
"memos": [
{
"type": "test",
"format": "plain/text",
"format": "text/plain",
"data": "texted data"
}
]
@@ -4416,7 +4418,7 @@ return api.prepareSettings(address, settings)
"memos": [
{
"type": "test",
"format": "plain/text",
"format": "text/plain",
"data": "texted data"
}
]
@@ -4426,7 +4428,7 @@ return api.prepareSettings(address, settings)
## prepareEscrowCreation
`prepareEscrowCreation(address: string, escrowCreation: Object, instructions: Object): Promise<Object>`
`prepareEscrowCreation(address: string, escrowCreation: object, instructions: object): Promise<object>`
Prepare an escrow creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4438,6 +4440,12 @@ address | [address](#address) | The address of the account that is creating the
escrowCreation | [escrowCreation](#escrow-creation) | The specification of the escrow creation to prepare.
instructions | [instructions](#transaction-instructions) | *Optional* Instructions for executing the transaction
This is a convenience method for generating the EscrowCreate JSON used by rippled, so the same restrictions apply.
Field mapping: `allowCancelAfter` is equivalent to rippled's `CancelAfter`; `allowExecuteAfter` is equivalent to `FinishAfter`. At the `allowCancelAfter` time, the escrow is considered expired. This means that the funds can only be returned to the sender. At the `allowExecuteAfter` time, the escrow is permitted to be released to the recipient (if the `condition` is fulfilled).
Note that `allowCancelAfter` must be chronologically later than `allowExecuteAfter`.
### Return Value
This method returns a promise that resolves with an object with the following structure:
@@ -4484,7 +4492,7 @@ return api.prepareEscrowCreation(address, escrowCreation).then(prepared =>
## prepareEscrowCancellation
`prepareEscrowCancellation(address: string, escrowCancellation: Object, instructions: Object): Promise<Object>`
`prepareEscrowCancellation(address: string, escrowCancellation: object, instructions: object): Promise<object>`
Prepare an escrow cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4540,7 +4548,7 @@ return api.prepareEscrowCancellation(address, escrowCancellation).then(prepared
## prepareEscrowExecution
`prepareEscrowExecution(address: string, escrowExecution: Object, instructions: Object): Promise<Object>`
`prepareEscrowExecution(address: string, escrowExecution: object, instructions: object): Promise<object>`
Prepare an escrow execution transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4598,7 +4606,7 @@ return api.prepareEscrowExecution(address, escrowExecution).then(prepared =>
## preparePaymentChannelCreate
`preparePaymentChannelCreate(address: string, paymentChannelCreate: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelCreate(address: string, paymentChannelCreate: object, instructions: object): Promise<object>`
Prepare a payment channel creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4656,7 +4664,7 @@ return api.preparePaymentChannelCreate(address, paymentChannelCreate).then(prepa
## preparePaymentChannelClaim
`preparePaymentChannelClaim(address: string, paymentChannelClaim: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelClaim(address: string, paymentChannelClaim: object, instructions: object): Promise<object>`
Prepare a payment channel claim transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4711,7 +4719,7 @@ return api.preparePaymentChannelClaim(address, paymentChannelClaim).then(prepare
## preparePaymentChannelFund
`preparePaymentChannelFund(address: string, paymentChannelFund: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelFund(address: string, paymentChannelFund: object, instructions: object): Promise<object>`
Prepare a payment channel fund transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4767,7 +4775,7 @@ return api.preparePaymentChannelFund(address, paymentChannelFund).then(prepared
## prepareCheckCreate
`prepareCheckCreate(address: string, checkCreate: Object, instructions: Object): Promise<Object>`
`prepareCheckCreate(address: string, checkCreate: object, instructions: object): Promise<object>`
Prepare a Check creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4826,7 +4834,7 @@ return api.prepareCheckCreate(address, checkCreate).then(prepared =>
## prepareCheckCancel
`prepareCheckCancel(address: string, checkCancel: Object, instructions: Object): Promise<Object>`
`prepareCheckCancel(address: string, checkCancel: object, instructions: object): Promise<object>`
Prepare a Check cancellation transaction. This cancels an unredeemed Check, removing it from the ledger without sending any money. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4881,7 +4889,7 @@ return api.prepareCheckCancel(address, checkCancel).then(prepared =>
## prepareCheckCash
`prepareCheckCash(address: string, checkCash: Object, instructions: Object): Promise<Object>`
`prepareCheckCash(address: string, checkCash: object, instructions: object): Promise<object>`
Prepare a Check cashing transaction. This redeems a Check to receive up to the amount authorized by the corresponding CheckCreate transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -4941,8 +4949,8 @@ return api.prepareCheckCash(address, checkCash).then(prepared =>
## sign
```
sign(txJSON: string, secret: string, options: Object): {signedTransaction: string, id: string}
sign(txJSON: string, keypair: Object, options: Object): {signedTransaction: string, id: string}
sign(txJSON: string, secret: string, options: object): {signedTransaction: string, id: string}
sign(txJSON: string, keypair: object, options: object): {signedTransaction: string, id: string}
```
Sign a prepared transaction. The signed transaction must subsequently be [submitted](#submit).
@@ -4966,7 +4974,7 @@ This method returns an object with the following structure:
Name | Type | Description
---- | ---- | -----------
signedTransaction | string | The signed transaction represented as an uppercase hexadecimal string.
id | [id](#transaction-id) | The [Transaction ID](#transaction-id) of the signed transaction.
id | [transactionHash](#transaction-id) | The [Transaction ID](#transaction-id) of the signed transaction.
### Example
@@ -5005,7 +5013,7 @@ This method returns an object with the following structure:
Name | Type | Description
---- | ---- | -----------
signedTransaction | string | The signed transaction represented as an uppercase hexadecimal string.
id | [id](#transaction-id) | The [Transaction ID](#transaction-id) of the signed transaction.
id | [transactionHash](#transaction-id) | The [Transaction ID](#transaction-id) of the signed transaction.
### Example
@@ -5026,7 +5034,7 @@ return api.combine(signedTransactions);
## submit
`submit(signedTransaction: string): Promise<Object>`
`submit(signedTransaction: string): Promise<object>`
Submits a signed transaction. The transaction is not guaranteed to succeed; it must be verified with [getTransaction](#gettransaction).
@@ -5100,6 +5108,88 @@ return api.generateAddress();
```
## isValidAddress
`isValidAddress(address: string): boolean`
Checks if the specified string contains a valid address.
### Parameters
This method takes one parameter, the address to validate.
### Return Value
This method returns `true` if the address is valid and `false` if it is not.
### Example
```javascript
return api.isValidAddress("address")
```
## isValidSecret
`isValidSecret(secret: string): boolean`
Checks if the specified string contains a valid secret.
### Parameters
This method takes one parameter, the secret which to validate.
### Return Value
This method returns `true` if the secret is valid and `false` if it is not.
### Example
```javascript
return api.isValidSecret("secret")
```
## deriveKeypair
`deriveKeypair(seed: string): {privateKey: string, publicKey: string}`
Derive a public and private key from a seed.
### Parameters
This method takes one parameter, the seed from which to derive the public and private key.
### Return Value
This method returns an object containing the public and private components of the keypair corresponding to the seed.
### Example
```javascript
var keypair = api.deriveKeypair(seed)
var public_key = keypair.publicKey;
var private_key = keypair.privateKey;
```
## deriveAddress
`deriveAddress(publicKey: string): string`
Derive an XRP Ledger address from a public key.
### Parameters
This method takes one parameter, the public key from which to derive the address.
### Return Value
This method returns a string corresponding to the address derived from the public key.
### Example
```javascript
var address = api.deriveAddress(public_key);
```
## signPaymentChannelClaim
`signPaymentChannelClaim(channel: string, amount: string, privateKey: string): string`
@@ -5180,7 +5270,7 @@ true
## computeLedgerHash
`computeLedgerHash(ledger: Object): string`
`computeLedgerHash(ledger: object): string`
Compute the hash of a ledger.
@@ -5205,9 +5295,8 @@ ledger | object | The ledger header to hash.
*ledger.* totalDrops | [value](#value) | Total number of drops (1/1,000,000th of an XRP) in the network, as a quoted integer. (This decreases as transaction fees cause XRP to be destroyed.)
*ledger.* transactionHash | string | Hash of the transaction information included in this ledger.
*ledger.* rawState | string | *Optional* A JSON string containing all state data for this ledger in rippled JSON format.
*ledger.* rawTransactions | string | *Optional* A JSON string containing rippled format transaction JSON for all transactions that were validated in this ledger.
*ledger.* stateHashes | array\<string\> | *Optional* An array of hashes of all state data in this ledger.
*ledger.* transactionHashes | array\<[id](#transaction-id)\> | *Optional* An array of hashes of all transactions that were validated in this ledger.
*ledger.* transactionHashes | array\<[transactionHash](#transaction-id)\> | *Optional* An array of hashes of all transactions that were validated in this ledger.
*ledger.* transactions | array\<[getTransaction](#gettransaction)\> | *Optional* Array of all transactions that were validated in this ledger. Transactions are represented in the same format as the return value of [getTransaction](#gettransaction).
### Return Value

View File

@@ -52,4 +52,4 @@ A *lax lax amount* allows either or both the counterparty and value to be omitte
A *balance* is an amount than can have a negative value.
<%- renderSchema('objects/amount-base.json') %>
<%- renderSchema('objects/amountbase.json') %>

View File

@@ -1,6 +1,6 @@
## computeLedgerHash
`computeLedgerHash(ledger: Object): string`
`computeLedgerHash(ledger: object): string`
Compute the hash of a ledger.

View File

@@ -0,0 +1,19 @@
## deriveAddress
`deriveAddress(publicKey: string): string`
Derive an XRP Ledger address from a public key.
### Parameters
This method takes one parameter, the public key from which to derive the address.
### Return Value
This method returns a string corresponding to the address derived from the public key.
### Example
```javascript
var address = api.deriveAddress(public_key);
```

View File

@@ -0,0 +1,21 @@
## deriveKeypair
`deriveKeypair(seed: string): {privateKey: string, publicKey: string}`
Derive a public and private key from a seed.
### Parameters
This method takes one parameter, the seed from which to derive the public and private key.
### Return Value
This method returns an object containing the public and private components of the keypair corresponding to the seed.
### Example
```javascript
var keypair = api.deriveKeypair(seed)
var public_key = keypair.publicKey;
var private_key = keypair.privateKey;
```

View File

@@ -1,6 +1,6 @@
## getAccountInfo
`getAccountInfo(address: string, options: Object): Promise<Object>`
`getAccountInfo(address: string, options: object): Promise<object>`
Returns information for the specified account. Note: For account data that is modifiable by the user, see [getSettings](#getsettings).

View File

@@ -1,6 +1,6 @@
## getBalanceSheet
`getBalanceSheet(address: string, options: Object): Promise<Object>`
`getBalanceSheet(address: string, options: object): Promise<object>`
Returns aggregate balances by currency plus a breakdown of assets and obligations for a specified account.

View File

@@ -1,6 +1,6 @@
## getBalances
`getBalances(address: string, options: Object): Promise<Array<Object>>`
`getBalances(address: string, options: object): Promise<Array<object>>`
Returns balances for a specified account.

View File

@@ -4,13 +4,15 @@
Returns the estimated transaction fee for the rippled server the RippleAPI instance is connected to.
This will use the [feeCushion parameter](#parameters) provided to the RippleAPI constructor, or the default value of `1.2`.
### Parameters
<%- renderSchema('input/get-fee.json') %>
### Return Value
This method returns a promise that resolves with a string encoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
This method returns a promise that resolves with a string-encoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
### Example
@@ -19,5 +21,5 @@ return api.getFee().then(fee => {/* ... */});
```
```json
"0.012"
"0.000012"
```

View File

@@ -1,6 +1,6 @@
## getLedger
`getLedger(options: Object): Promise<Object>`
`getLedger(options: object): Promise<object>`
Returns header information for the specified ledger (or the most recent validated ledger if no ledger is specified). Optionally, all the transactions that were validated in the ledger or the account state information can be returned with the ledger header.

View File

@@ -1,6 +1,6 @@
## getOrderbook
`getOrderbook(address: string, orderbook: Object, options: Object): Promise<Object>`
`getOrderbook(address: string, orderbook: object, options: object): Promise<object>`
Returns open orders for the specified account. Open orders are orders that have not yet been fully executed and are still in the order book.

View File

@@ -1,6 +1,6 @@
## getOrders
`getOrders(address: string, options: Object): Promise<Array<Object>>`
`getOrders(address: string, options: object): Promise<Array<object>>`
Returns open orders for the specified account. Open orders are orders that have not yet been fully executed and are still in the order book.

View File

@@ -1,6 +1,6 @@
## getPaths
`getPaths(pathfind: Object): Promise<Array<Object>>`
`getPaths(pathfind: object): Promise<Array<object>>`
Finds paths to send a payment. Paths are options for how to route a payment.

View File

@@ -1,6 +1,6 @@
## getPaymentChannel
`getPaymentChannel(id: string): Promise<Object>`
`getPaymentChannel(id: string): Promise<object>`
Returns specified payment channel.

View File

@@ -1,6 +1,6 @@
## getSettings
`getSettings(address: string, options: Object): Promise<Object>`
`getSettings(address: string, options: object): Promise<object>`
Returns settings for the specified account. Note: For account data that is not modifiable by the user, see [getAccountInfo](#getaccountinfo).

View File

@@ -1,6 +1,6 @@
## getTransaction
`getTransaction(id: string, options: Object): Promise<Object>`
`getTransaction(id: string, options: object): Promise<object>`
Retrieves a transaction by its [Transaction ID](#transaction-id).

View File

@@ -1,6 +1,6 @@
## getTransactions
`getTransactions(address: string, options: Object): Promise<Array<Object>>`
`getTransactions(address: string, options: object): Promise<Array<object>>`
Retrieves historical transactions of an account.

View File

@@ -1,6 +1,6 @@
## getTrustlines
`getTrustlines(address: string, options: Object): Promise<Array<Object>>`
`getTrustlines(address: string, options: object): Promise<Array<object>>`
Returns trustlines for a specified account.

View File

@@ -46,6 +46,10 @@
<% include combine.md.ejs %>
<% include submit.md.ejs %>
<% include generateAddress.md.ejs %>
<% include isValidAddress.md.ejs %>
<% include isValidSecret.md.ejs %>
<% include deriveKeypair.md.ejs %>
<% include deriveAddress.md.ejs %>
<% include signPaymentChannelClaim.md.ejs %>
<% include verifyPaymentChannelClaim.md.ejs %>
<% include computeLedgerHash.md.ejs %>

View File

@@ -0,0 +1,19 @@
## isValidAddress
`isValidAddress(address: string): boolean`
Checks if the specified string contains a valid address.
### Parameters
This method takes one parameter, the address to validate.
### Return Value
This method returns `true` if the address is valid and `false` if it is not.
### Example
```javascript
return api.isValidAddress("address")
```

View File

@@ -0,0 +1,19 @@
## isValidSecret
`isValidSecret(secret: string): boolean`
Checks if the specified string contains a valid secret.
### Parameters
This method takes one parameter, the secret which to validate.
### Return Value
This method returns `true` if the secret is valid and `false` if it is not.
### Example
```javascript
return api.isValidSecret("secret")
```

View File

@@ -1,6 +1,6 @@
## prepareCheckCancel
`prepareCheckCancel(address: string, checkCancel: Object, instructions: Object): Promise<Object>`
`prepareCheckCancel(address: string, checkCancel: object, instructions: object): Promise<object>`
Prepare a Check cancellation transaction. This cancels an unredeemed Check, removing it from the ledger without sending any money. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareCheckCash
`prepareCheckCash(address: string, checkCash: Object, instructions: Object): Promise<Object>`
`prepareCheckCash(address: string, checkCash: object, instructions: object): Promise<object>`
Prepare a Check cashing transaction. This redeems a Check to receive up to the amount authorized by the corresponding CheckCreate transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareCheckCreate
`prepareCheckCreate(address: string, checkCreate: Object, instructions: Object): Promise<Object>`
`prepareCheckCreate(address: string, checkCreate: object, instructions: object): Promise<object>`
Prepare a Check creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareEscrowCancellation
`prepareEscrowCancellation(address: string, escrowCancellation: Object, instructions: Object): Promise<Object>`
`prepareEscrowCancellation(address: string, escrowCancellation: object, instructions: object): Promise<object>`
Prepare an escrow cancellation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareEscrowCreation
`prepareEscrowCreation(address: string, escrowCreation: Object, instructions: Object): Promise<Object>`
`prepareEscrowCreation(address: string, escrowCreation: object, instructions: object): Promise<object>`
Prepare an escrow creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
@@ -8,6 +8,12 @@ Prepare an escrow creation transaction. The prepared transaction must subsequent
<%- renderSchema('input/prepare-escrow-creation.json') %>
This is a convenience method for generating the EscrowCreate JSON used by rippled, so the same restrictions apply.
Field mapping: `allowCancelAfter` is equivalent to rippled's `CancelAfter`; `allowExecuteAfter` is equivalent to `FinishAfter`. At the `allowCancelAfter` time, the escrow is considered expired. This means that the funds can only be returned to the sender. At the `allowExecuteAfter` time, the escrow is permitted to be released to the recipient (if the `condition` is fulfilled).
Note that `allowCancelAfter` must be chronologically later than `allowExecuteAfter`.
### Return Value
This method returns a promise that resolves with an object with the following structure:

View File

@@ -1,6 +1,6 @@
## prepareEscrowExecution
`prepareEscrowExecution(address: string, escrowExecution: Object, instructions: Object): Promise<Object>`
`prepareEscrowExecution(address: string, escrowExecution: object, instructions: object): Promise<object>`
Prepare an escrow execution transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareOrder
`prepareOrder(address: string, order: Object, instructions: Object): Promise<Object>`
`prepareOrder(address: string, order: object, instructions: object): Promise<object>`
Prepare an order transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareOrderCancellation
`prepareOrderCancellation(address: string, orderCancellation: Object, 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).

View File

@@ -1,6 +1,6 @@
## preparePayment
`preparePayment(address: string, payment: Object, instructions: Object): Promise<Object>`
`preparePayment(address: string, payment: object, instructions: object): Promise<object>`
Prepare a payment transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## preparePaymentChannelClaim
`preparePaymentChannelClaim(address: string, paymentChannelClaim: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelClaim(address: string, paymentChannelClaim: object, instructions: object): Promise<object>`
Prepare a payment channel claim transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## preparePaymentChannelCreate
`preparePaymentChannelCreate(address: string, paymentChannelCreate: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelCreate(address: string, paymentChannelCreate: object, instructions: object): Promise<object>`
Prepare a payment channel creation transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## preparePaymentChannelFund
`preparePaymentChannelFund(address: string, paymentChannelFund: Object, instructions: Object): Promise<Object>`
`preparePaymentChannelFund(address: string, paymentChannelFund: object, instructions: object): Promise<object>`
Prepare a payment channel fund transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareSettings
`prepareSettings(address: string, settings: Object, instructions: Object): Promise<Object>`
`prepareSettings(address: string, settings: object, instructions: object): Promise<object>`
Prepare a settings transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -1,6 +1,6 @@
## prepareTrustline
`prepareTrustline(address: string, trustline: Object, instructions: Object): Promise<Object>`
`prepareTrustline(address: string, trustline: object, instructions: object): Promise<object>`
Prepare a trustline transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).

View File

@@ -5,11 +5,14 @@ ripple-lib relies on [rippled APIs](https://ripple.com/build/rippled-apis/) for
* Use `hasNextPage()` to determine whether a response has more pages. This is true when the response includes a [`marker` field](https://ripple.com/build/rippled-apis/#markers-and-pagination).
* Use `requestNextPage()` to request the next page of data.
When using rippled APIs, [specify XRP amounts in drops](https://ripple.com/build/rippled-apis/#specifying-currency-amounts). 1 XRP = 1000000 drops.
When using rippled APIs:
* [Specify XRP amounts in drops](https://developers.ripple.com/basic-data-types.html#specifying-currency-amounts).
* [Specify timestamps as the number of seconds since the "Ripple Epoch"](https://developers.ripple.com/basic-data-types.html#specifying-time).
* Instead of `counterparty`, use `issuer`.
## Listening to streams
The `rippled` server can push updates to your client when various events happen. Refer to [Subscriptions in the `rippled` API docs](https://ripple.com/build/rippled-apis/#subscriptions) for details.
The `rippled` server can push updates to your client when various events happen. Refer to [Subscriptions in the `rippled` API docs](https://developers.ripple.com/subscription-methods.html) for details.
Note that the `streams` parameter for generic streams takes an array. For example, to subscribe to the `validations` stream, use `{ streams: [ 'validations' ] }`.

View File

@@ -1,8 +1,8 @@
## sign
```
sign(txJSON: string, secret: string, options: Object): {signedTransaction: string, id: string}
sign(txJSON: string, keypair: Object, options: Object): {signedTransaction: string, id: string}
sign(txJSON: string, secret: string, options: object): {signedTransaction: string, id: string}
sign(txJSON: string, keypair: object, options: object): {signedTransaction: string, id: string}
```
Sign a prepared transaction. The signed transaction must subsequently be [submitted](#submit).

View File

@@ -28,6 +28,8 @@ See [Transaction Types](#transaction-types) for a description.
<%- renderSchema('specifications/order.json') %>
The following invalid flag combination causes a `ValidationError`: `immediateOrCancel` and `fillOrKill`. These fields are mutually exclusive, and cannot both be set at the same time.
### Example
<%- renderFixture('requests/prepare-order.json') %>

View File

@@ -1,6 +1,6 @@
## submit
`submit(signedTransaction: string): Promise<Object>`
`submit(signedTransaction: string): Promise<object>`
Submits a signed transaction. The transaction is not guaranteed to succeed; it must be verified with [getTransaction](#gettransaction).

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-lib",
"version": "1.0.0-beta.2",
"version": "1.0.2",
"license": "ISC",
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
"files": [
@@ -26,7 +26,7 @@
"ripple-binary-codec": "^0.1.13",
"ripple-hashes": "^0.3.1",
"ripple-keypairs": "^0.10.1",
"ripple-lib-transactionparser": "^0.6.2",
"ripple-lib-transactionparser": "0.7.1",
"ws": "^3.3.1"
},
"devDependencies": {
@@ -53,7 +53,7 @@
"ts-node": "^3.3.0",
"tslint": "^5.8.0",
"tslint-eslint-rules": "^4.1.1",
"typescript": "^2.6.1",
"typescript": "2.9.2",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"yargs": "^8.0.2"

View File

@@ -1,5 +1,13 @@
import {EventEmitter} from 'events'
import {Connection, errors, validate, xrpToDrops, dropsToXrp} from './common'
import {
Connection,
errors,
validate,
xrpToDrops,
dropsToXrp,
iso8601ToRippleTime,
txFlags
} from './common'
import {
connect,
disconnect,
@@ -37,6 +45,7 @@ import sign from './transaction/sign'
import combine from './transaction/combine'
import submit from './transaction/submit'
import {generateAddressAPI} from './offline/generate-address'
import {deriveKeypair, deriveAddress} from './offline/derive'
import computeLedgerHash from './offline/ledgerhash'
import signPaymentChannelClaim from './offline/sign-payment-channel-claim'
import verifyPaymentChannelClaim from './offline/verify-payment-channel-claim'
@@ -57,9 +66,11 @@ import {
import RangeSet from './common/rangeset'
import * as ledgerUtils from './ledger/utils'
import * as transactionUtils from './transaction/utils'
import * as schemaValidator from './common/schema-validator'
import {getServerInfo, getFee} from './common/serverinfo'
import {clamp} from './ledger/utils'
import {Instructions, Prepare} from './transaction/types'
export type APIOptions = {
server?: string,
@@ -97,7 +108,7 @@ class RippleAPI extends EventEmitter {
// these are exposed only for use by unit tests; they are not part of the API.
static _PRIVATE = {
validate: validate,
validate,
RangeSet,
ledgerUtils,
schemaValidator
@@ -131,19 +142,16 @@ class RippleAPI extends EventEmitter {
}
/**
* Makes a request to the API with the given command and
* additional request body parameters.
*/
async request(command: 'account_info', params: AccountInfoRequest):
Promise<AccountInfoResponse>
async request(command: 'account_lines', params: AccountLinesRequest):
Promise<AccountLinesResponse>
/**
* Returns objects owned by an account.
* For an account's trust lines and balances,
* see `getTrustlines` and `getBalances`.
*/
async request(command: 'account_objects', params: AccountObjectsRequest):
Promise<AccountObjectsResponse>
async request(command: 'account_offers', params: AccountOffersRequest):
Promise<AccountOffersResponse>
async request(command: 'book_offers', params: BookOffersRequest):
@@ -156,15 +164,9 @@ class RippleAPI extends EventEmitter {
Promise<LedgerEntryResponse>
async request(command: 'server_info', params?: ServerInfoRequest):
Promise<ServerInfoResponse>
async request(command: string, params: object):
Promise<object>
/**
* Makes a request to the API with the given command and
* additional request body parameters.
*/
async request(command: string, params: object = {}): Promise<object> {
async request(command: string, params: any):
Promise<any>
async request(command: string, params: any = {}): Promise<any> {
return this.connection.request({
...params,
command
@@ -199,6 +201,27 @@ class RippleAPI extends EventEmitter {
return this.request(command, nextPageParams)
}
/**
* Prepare a transaction.
*
* You can later submit the transaction with `submit()`.
*/
async prepareTransaction(txJSON: object, instructions: Instructions = {}):
Promise<Prepare> {
return transactionUtils.prepareTransaction(txJSON, this, instructions)
}
/**
* Convert a string to hex.
*
* This can be used to generate `MemoData`, `MemoType`, and `MemoFormat`.
*
* @param string string to convert to hex
*/
convertStringToHex(string: string): string {
return transactionUtils.convertStringToHex(string)
}
/**
* Makes multiple paged requests to the API to return a given number of
* resources. _requestAll() will make multiple requests until the `limit`
@@ -299,6 +322,8 @@ class RippleAPI extends EventEmitter {
submit = submit
generateAddress = generateAddressAPI
deriveKeypair = deriveKeypair
deriveAddress = deriveAddress
computeLedgerHash = computeLedgerHash
signPaymentChannelClaim = signPaymentChannelClaim
verifyPaymentChannelClaim = verifyPaymentChannelClaim
@@ -306,6 +331,11 @@ class RippleAPI extends EventEmitter {
xrpToDrops = xrpToDrops
dropsToXrp = dropsToXrp
iso8601ToRippleTime = iso8601ToRippleTime
txFlags = txFlags
isValidAddress = schemaValidator.isValidAddress
isValidSecret = schemaValidator.isValidSecret
}
export {

View File

@@ -6,7 +6,7 @@ function setPrototypeOf(object, prototype) {
object.__proto__ = prototype
}
function getConstructorName(object: Object): string {
function getConstructorName(object: object): string {
// hack for internet explorer
if (!object.constructor.name) {
return object.constructor.toString().match(/^function\s+([^(]*)/)![1]

View File

@@ -70,7 +70,7 @@ class MissingLedgerHistoryError extends RippleError {
class PendingLedgerVersionError extends RippleError {
constructor(message?: string) {
super(message || 'maxLedgerVersion is greater than server\'s most recent ' +
super(message || 'maxLedgerVersion is greater than server\'s most recent' +
' validated ledger')
}
}

View File

@@ -9,13 +9,13 @@ function loadSchemas() {
// listed explicitly for webpack (instead of scanning schemas directory)
const schemas = [
require('./schemas/objects/tx-json.json'),
require('./schemas/objects/tx-type.json'),
require('./schemas/objects/transaction-type.json'),
require('./schemas/objects/hash128.json'),
require('./schemas/objects/hash256.json'),
require('./schemas/objects/sequence.json'),
require('./schemas/objects/signature.json'),
require('./schemas/objects/issue.json'),
require('./schemas/objects/ledgerversion.json'),
require('./schemas/objects/ledger-version.json'),
require('./schemas/objects/max-adjustment.json'),
require('./schemas/objects/memo.json'),
require('./schemas/objects/memos.json'),
@@ -31,21 +31,23 @@ function loadSchemas() {
require('./schemas/objects/min-adjustment.json'),
require('./schemas/objects/source-exact-adjustment.json'),
require('./schemas/objects/destination-exact-adjustment.json'),
require('./schemas/objects/tx-hash.json'),
require('./schemas/objects/destination-address-tag.json'),
require('./schemas/objects/transaction-hash.json'),
require('./schemas/objects/address.json'),
require('./schemas/objects/adjustment.json'),
require('./schemas/objects/quality.json'),
require('./schemas/objects/amount.json'),
require('./schemas/objects/amount-base.json'),
require('./schemas/objects/amountbase.json'),
require('./schemas/objects/balance.json'),
require('./schemas/objects/blob.json'),
require('./schemas/objects/currency.json'),
require('./schemas/objects/signed-value.json'),
require('./schemas/objects/orderbook.json'),
require('./schemas/objects/instructions.json'),
require('./schemas/objects/settings.json'),
require('./schemas/objects/settings-plus-memos.json'),
require('./schemas/specifications/settings.json'),
require('./schemas/specifications/payment.json'),
require('./schemas/specifications/get-payment.json'),
require('./schemas/specifications/escrow-cancellation.json'),
require('./schemas/specifications/order-cancellation.json'),
require('./schemas/specifications/order.json'),
@@ -158,5 +160,6 @@ function schemaValidate(schemaName: string, object: any): void {
export {
schemaValidate,
isValidSecret
isValidSecret,
isValidAddress
}

View File

@@ -18,9 +18,9 @@
},
"server": {
"type": "string",
"description": "URI for rippled websocket port to connect to. Must start with `wss://` or `ws://`.",
"description": "URI for rippled websocket port to connect to. Must start with `wss://`, `ws://`, `wss+unix://`, or `ws+unix://`.",
"format": "uri",
"pattern": "^wss?://"
"pattern": "^(wss?|wss?\\+unix)://"
},
"proxy": {
"format": "uri",

View File

@@ -4,9 +4,9 @@
"description": "Parameters for getTransaction",
"type": "object",
"properties": {
"id": {"$ref": "id"},
"id": {"$ref": "transactionHash"},
"options": {
"description": "Options to limit the ledger versions to search.",
"description": "Options to limit the ledger versions to search and/or to include raw transaction data.",
"properties": {
"minLedgerVersion": {
"$ref": "ledgerVersion",
@@ -15,6 +15,9 @@
"maxLedgerVersion": {
"$ref": "ledgerVersion",
"description": "The highest ledger version to search"
},
"includeRawTransaction": {
"description": "Include raw transaction data. For advanced users; exercise caution when interpreting this data. "
}
},
"additionalProperties": false

View File

@@ -49,6 +49,9 @@
"items": {"$ref": "transactionType"},
"description": "Only return transactions of the specified [Transaction Types](#transaction-types)."
},
"includeRawTransactions": {
"description": "Include raw transaction data. For advanced users; exercise caution when interpreting this data. "
},
"binary": {
"type": "boolean",
"description": "If true, the transactions will be sent from the server in a condensed binary format rather than JSON."

View File

@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "amount",
"link": "amount",
"description": "An Amount on the Ripple Protocol",
"description": "An Amount on the XRP Ledger",
"allOf": [
{"$ref": "amountbase"},
{"required": ["value"]}

View File

@@ -0,0 +1,15 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "destinationAddressTag",
"description": "A destination address and optional tag, with no amount included. When parsing an incoming transaction, the original specification's amount is hidden to prevent misinterpretation. For the amount that the transaction delivered, see `outcome.deliveredAmount`.",
"type": "object",
"properties": {
"address": {
"$ref": "address",
"description": "The address to receive at."
},
"tag": {"$ref": "tag"}
},
"required": ["address"],
"additionalProperties": false
}

View File

@@ -9,7 +9,7 @@
},
"amount": {
"$ref": "laxAmount",
"description": "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)."
"description": "An exact amount to deliver to the recipient. If the counterparty is not specified, amounts with any counterparty may be used. (This field cannot be used with `destination.minAmount`.)"
},
"tag": {"$ref": "tag"}
},

View File

@@ -93,7 +93,9 @@
"minItems": 1,
"maxItems": 8
}
}
},
"required": ["threshold", "weights"],
"additionalProperties": false
},
"transferRate": {
"description": " The fee to charge when users transfer this accounts issuances, as the decimal amount that must be sent to deliver 1 unit. Has precision up to 9 digits beyond the decimal point. Use `null` to set no fee.",

View File

@@ -1,6 +1,6 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "id",
"title": "transactionHash",
"link": "transaction-id",
"description": "A hash of a transaction used to identify the transaction, represented in hexadecimal.",
"type": "string",

View File

@@ -55,15 +55,11 @@
"description": "A transaction in the same format as the return value of [getTransaction](#gettransaction)."
}
},
"rawTransactions": {
"type": "string",
"description": "A JSON string containing rippled format transaction JSON for all transactions that were validated in this ledger."
},
"transactionHashes": {
"description": "An array of hashes of all transactions that were validated in this ledger.",
"type": "array",
"items": {
"$ref": "id"
"$ref": "transactionHash"
}
},
"rawState": {

View File

@@ -1,20 +1,21 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "getTransaction",
"description": "getTransaction response",
"link": "gettransaction",
"properties": {
"type": {
"$ref": "transactionType"
},
"specification": {
"description": "A specification that would produce the same outcome as this transaction. The structure of the specification depends on the value of the `type` field (see [Transaction Types](#transaction-types) for details). *Note:* This is **not** necessarily the same as the original specification."
"description": "A specification that would produce the same outcome as this transaction. *Exception:* For payment transactions, this omits the `destination.amount` field, to prevent misunderstanding. The structure of the specification depends on the value of the `type` field (see [Transaction Types](#transaction-types) for details). *Note:* This is **not** necessarily the same as the original specification."
},
"outcome": {
"$ref": "outcome",
"description": "The outcome of the transaction (what effects it had)."
},
"id": {
"$ref": "id",
"$ref": "transactionHash",
"description": "A hash of the transaction that can be used to identify it."
},
"address": {
@@ -24,6 +25,10 @@
"sequence": {
"$ref": "sequence",
"description": "The account sequence number of the transaction for the account that initiated it."
},
"rawTransaction": {
"description": "The raw transaction data as a JSON string. For advanced users only; exercise caution when interpreting this data.",
"type": "string"
}
},
"required": [
@@ -44,7 +49,7 @@
]
},
"specification": {
"$ref": "payment"
"$ref": "getPayment"
}
}
},

View File

@@ -25,7 +25,7 @@
"type": "object",
"additionalProperties": {
"type": "array",
"description": "Key is the ripple address; value is an array of signed amounts representing changes of balances for that address.",
"description": "Key is the XRP Ledger address; value is an array of signed amounts representing changes of balances for that address.",
"items": {"$ref": "balance"}
}
},
@@ -33,10 +33,14 @@
"type": "object",
"additionalProperties": {
"type": "array",
"description": "Key is the maker's ripple address; value is an array of changes",
"description": "Key is the maker's XRP Ledger address; value is an array of changes",
"items": {"$ref": "orderChange"}
}
},
"channelChanges": {
"type": "object",
"description": "Properties reflecting the details of the payment channel."
},
"ledgerVersion": {
"$ref": "ledgerVersion",
"description": "The ledger version that the transaction was validated in."

View File

@@ -9,7 +9,7 @@
"description": "The signed transaction represented as an uppercase hexadecimal string."
},
"id": {
"$ref": "id",
"$ref": "transactionHash",
"description": "The [Transaction ID](#transaction-id) of the signed transaction."
}
},

View File

@@ -0,0 +1,39 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "getPayment",
"description": "A specification of a payment in a response for getTransaction or getTransactions.",
"type": "object",
"properties": {
"source": {
"$ref": "sourceAdjustment",
"description": "The source of the funds to be sent."
},
"destination": {
"$ref": "destinationAddressTag",
"description": "The destination of the funds to be sent. Since this is a payment response, the amount is not shown here. For the amount that the transaction delivered, see `outcome.deliveredAmount`."
},
"paths": {
"type": "string",
"description": "The paths of trustlines and orders to use in executing the payment."
},
"memos": {"$ref": "memos"},
"invoiceID": {
"description": "A 256-bit hash that can be used to identify a particular payment.",
"$ref": "hash256"
},
"allowPartialPayment": {
"description": "If true, this payment should proceed even if the whole amount cannot be delivered due to a lack of liquidity or a lack of funds in the source account.",
"type": "boolean"
},
"noDirectRipple": {
"description": "If true and paths are specified, the sender would like the XRP Ledger to disregard any direct paths from the source account to the destination account. This may be used to take advantage of an arbitrage opportunity or by gateways wishing to issue balances from a hot wallet to a user who has mistakenly set a trustline directly to the hot wallet.",
"type": "boolean"
},
"limitQuality": {
"description": "Only take paths where all the conversions have an input:output ratio that is equal or better than the ratio of destination.amount:source.maxAmount.",
"type": "boolean"
}
},
"required": ["source", "destination"],
"additionalProperties": false
}

View File

@@ -19,11 +19,11 @@
},
"immediateOrCancel": {
"type": "boolean",
"description": "Treat the offer as an [Immediate or Cancel order](http://en.wikipedia.org/wiki/Immediate_or_cancel). If enabled, the offer will never become a ledger node: it only attempts to match existing offers in the ledger."
"description": "Treat the offer as an [Immediate or Cancel order](http://en.wikipedia.org/wiki/Immediate_or_cancel). If enabled, the offer will never become a ledger node: it only attempts to match existing offers in the ledger. This cannot be used with `fillOrKill`."
},
"fillOrKill": {
"type": "boolean",
"description": "Treat the offer as a [Fill or Kill order](http://en.wikipedia.org/wiki/Fill_or_kill). Only attempt to match existing offers in the ledger, and only do so if the entire quantity can be exchanged."
"description": "Treat the offer as a [Fill or Kill order](http://en.wikipedia.org/wiki/Fill_or_kill). Only attempt to match existing offers in the ledger, and only do so if the entire quantity can be exchanged. This cannot be used with `immediateOrCancel`."
},
"passive": {
"description": "If enabled, the offer will not consume offers that exactly match it, and instead becomes an Offer node in the ledger. It will still consume offers that cross it.",

View File

@@ -9,7 +9,7 @@ export type GetServerInfoResponse = {
hostID: string,
ioLatencyMs: number,
load?: {
jobTypes: Array<Object>,
jobTypes: Array<object>,
threads: number
},
lastClose: {
@@ -61,6 +61,8 @@ function getServerInfo(this: RippleAPI): Promise<GetServerInfoResponse> {
})
}
// This is a public API that can be called directly.
// This is not used by the `prepare*` methods. See `src/transaction/utils.ts`
async function getFee(
this: RippleAPI,
cushion?: number
@@ -74,10 +76,12 @@ async function getFee(
const serverInfo = (await this.request('server_info')).info
const baseFeeXrp = new BigNumber(serverInfo.validated_ledger.base_fee_xrp)
const fee = baseFeeXrp.times(serverInfo.load_factor).times(cushion)
let fee = baseFeeXrp.times(serverInfo.load_factor).times(cushion)
// Cap fee to `this._maxFeeXRP`
return BigNumber.min(fee, this._maxFeeXRP).toString(10)
fee = BigNumber.min(fee, this._maxFeeXRP)
// Round fee to 6 decimal places
return (new BigNumber(fee.toFixed(6))).toString(10)
}
export {

View File

@@ -1,4 +1,9 @@
import {CheckLedgerEntry} from '../objects'
import {
CheckLedgerEntry, RippleStateLedgerEntry,
OfferLedgerEntry, SignerListLedgerEntry,
EscrowLedgerEntry, PayChannelLedgerEntry,
DepositPreauthLedgerEntry
} from '../objects'
export interface GetAccountObjectsOptions {
type?: string | (
@@ -44,7 +49,16 @@ export interface AccountObjectsResponse {
account: string,
// Array of objects owned by this account.
account_objects: CheckLedgerEntry | object,
// from the getAccountObjects section of the dev center
account_objects: Array<
CheckLedgerEntry |
RippleStateLedgerEntry |
OfferLedgerEntry |
SignerListLedgerEntry |
EscrowLedgerEntry |
PayChannelLedgerEntry |
DepositPreauthLedgerEntry
>,
// (May be omitted) The identifying hash of the ledger
// that was used to generate this response.

View File

@@ -1,7 +1,7 @@
import {
TakerRequestAmount,
RippledAmount,
OfferCreateTransaction
OfferLedgerEntry
} from '../objects'
export interface BookOffersRequest {
@@ -22,7 +22,7 @@ export interface BookOffersResponse {
marker?: any
}
export interface BookOffer extends OfferCreateTransaction {
export interface BookOffer extends OfferLedgerEntry {
quality?: string
owner_funds?: string,
taker_gets_funded?: RippledAmount,

View File

@@ -1,4 +1,5 @@
import {SignerEntry} from './index'
import {Amount, RippledAmount} from './amounts'
export interface AccountRootLedgerEntry {
LedgerEntryType: 'AccountRoot',
@@ -44,6 +45,87 @@ export interface CheckLedgerEntry {
SourceTag: number
}
export interface DepositPreauthLedgerEntry {
LedgerEntryType: 'DepositPreauth',
Account: string,
Authorize: string,
OwnerNode: string,
PreviousTxnID: string,
PreviousTxnLgrSeq: number
}
export interface DirectoryNodeLedgerEntry {
LedgerEntryType: 'DirectoryNode',
Flags: number,
RootIndex: string,
Indexes: string[],
IndexNext?: number,
IndexPrevious?: number
}
export interface OfferDirectoryNodeLedgerEntry
extends DirectoryNodeLedgerEntry {
TakerPaysCurrency: string,
TakerPaysIssuer: string,
TakerGetsCurrency: string,
TakerGetsIssuer: string,
ExchangeRate?: number // DEPRECATED
}
export interface OwnerDirectoryNodeLedgerEntry
extends DirectoryNodeLedgerEntry {
Owner: string,
}
export interface EscrowLedgerEntry {
LedgerEntryType: 'Escrow',
Account: string,
Destination: string,
Amount: string,
Condition?: string,
CancelAfter?: number,
FinishAfter?: number,
Flags: number,
SourceTag?: number,
DestinationTag?: number,
OwnerNode: string,
DestinationNode?: string,
PreviousTxnID: string,
PreviousTxnLgrSeq: number
}
export interface FeeSettingsLedgerEntry {
LedgerEntryType: 'FeeSettings',
BaseFee: string,
ReferenceFeeUnits: number,
ReserveBase: number,
ReserveIncrement: number,
Flags: number
}
export interface LedgerHashesLedgerEntry {
LedgerEntryType: 'LedgerHashes',
Hashes: string[],
Flags: number,
FirstLedgerSequence?: number, // DEPRECATED
LastLedgerSequence?: number
}
export interface OfferLedgerEntry {
LedgerEntryType: 'Offer',
Flags: number,
Account: string,
Sequence: number,
TakerPays: RippledAmount,
TakerGets: RippledAmount,
BookDirectory: string,
BookNode: string,
OwnerNode: string,
PreviousTxnID: string,
PreviousTxnLgrSeq: number,
Expiration?: number
}
export interface PayChannelLedgerEntry {
LedgerEntryType: 'PayChannel',
Sequence: number,
@@ -63,6 +145,22 @@ export interface PayChannelLedgerEntry {
index: string
}
export interface RippleStateLedgerEntry {
LedgerEntryType: 'RippleState',
Flags: number,
Balance: Amount,
LowLimit: Amount,
HighLimit: Amount,
PreviousTxnID: string,
PreviousTxnLgrSeq: number,
LowNode?: string,
HighNode?: string,
LowQualityIn?: number,
LowQualityOut?: number,
HighQualityIn?: number,
HighQualityOut?: number
}
export interface SignerListLedgerEntry {
LedgerEntryType: 'SignerList',
OwnerNode: string,
@@ -73,11 +171,19 @@ export interface SignerListLedgerEntry {
PreviousTxnLgrSeq: number
}
// TODO: Add the other ledger entry types, then remove the `any` fallback
// see https://ripple.com/build/ledger-format/#ledger-object-types
export type LedgerEntry =
AccountRootLedgerEntry |
AmendmentsLedgerEntry |
CheckLedgerEntry |
DepositPreauthLedgerEntry |
DirectoryNodeLedgerEntry |
OfferDirectoryNodeLedgerEntry |
OwnerDirectoryNodeLedgerEntry |
EscrowLedgerEntry |
FeeSettingsLedgerEntry |
LedgerHashesLedgerEntry |
OfferLedgerEntry |
PayChannelLedgerEntry |
SignerListLedgerEntry |
any
RippleStateLedgerEntry |
SignerListLedgerEntry

View File

@@ -1,5 +1,8 @@
export {RippleAPI} from './api'
export {
FormattedTransactionType
} from './transaction/types'
// Broadcast api is experimental
export {RippleAPIBroadcast} from './broadcast'

View File

@@ -1,6 +1,6 @@
import * as assert from 'assert'
function parseOrderCancellation(tx: any): Object {
function parseOrderCancellation(tx: any): object {
assert(tx.TransactionType === 'OfferCancel')
return {
orderSequence: tx.OfferSequence

View File

@@ -2,7 +2,7 @@ import * as assert from 'assert'
import {parseMemos} from './utils'
import {removeUndefined} from '../../common'
function parseEscrowCancellation(tx: any): Object {
function parseEscrowCancellation(tx: any): object {
assert(tx.TransactionType === 'EscrowCancel')
return removeUndefined({

View File

@@ -3,7 +3,7 @@ import parseAmount from './amount'
import {parseTimestamp, parseMemos} from './utils'
import {removeUndefined} from '../../common'
function parseEscrowCreation(tx: any): Object {
function parseEscrowCreation(tx: any): object {
assert(tx.TransactionType === 'EscrowCreate')
return removeUndefined({

View File

@@ -2,7 +2,7 @@ import * as assert from 'assert'
import {parseMemos} from './utils'
import {removeUndefined} from '../../common'
function parseEscrowExecution(tx: any): Object {
function parseEscrowExecution(tx: any): object {
assert(tx.TransactionType === 'EscrowFinish')
return removeUndefined({

View File

@@ -13,7 +13,7 @@ function parseField(info, value) {
return value
}
function parseFields(data: any): Object {
function parseFields(data: any): object {
const settings: any = {}
for (const fieldName in AccountFields) {
const fieldValue = data[fieldName]

View File

@@ -17,19 +17,19 @@ export type FormattedLedger = {
parentCloseTime: string,
totalDrops: string,
transactionHash: string,
transactions?: Array<Object>,
rawTransactions?: string,
transactions?: Array<object>,
transactionHashes?: Array<string>,
rawState?: string,
stateHashes?: Array<string>
}
function parseTransactionWrapper(ledgerVersion, tx) {
// renames metaData to meta and adds ledger_index
const transaction = _.assign({}, _.omit(tx, 'metaData'), {
meta: tx.metaData,
ledger_index: ledgerVersion
})
const result = parseTransaction(transaction)
const result = parseTransaction(transaction, true)
if (!result.outcome.ledgerVersion) {
result.outcome.ledgerVersion = ledgerVersion
}
@@ -45,8 +45,7 @@ function parseTransactions(transactions, ledgerVersion) {
}
return {
transactions: _.map(transactions,
_.partial(parseTransactionWrapper, ledgerVersion)),
rawTransactions: JSON.stringify(transactions)
_.partial(parseTransactionWrapper, ledgerVersion))
}
}
@@ -62,19 +61,20 @@ function parseState(state) {
export function parseLedger(ledger: Ledger): FormattedLedger {
const ledgerVersion = parseInt(ledger.ledger_index || ledger.seqNum, 10)
return removeUndefined(Object.assign({
stateHash: ledger.account_hash,
closeTime: rippleTimeToISO8601(ledger.close_time),
closeTimeResolution: ledger.close_time_resolution,
closeFlags: ledger.close_flags,
ledgerHash: ledger.hash || ledger.ledger_hash,
ledgerVersion: ledgerVersion,
parentLedgerHash: ledger.parent_hash,
parentCloseTime: rippleTimeToISO8601(ledger.parent_close_time),
totalDrops: ledger.total_coins || ledger.totalCoins,
transactionHash: ledger.transaction_hash
},
parseTransactions(ledger.transactions, ledgerVersion),
parseState(ledger.accountState)
return removeUndefined(Object.assign(
{
stateHash: ledger.account_hash,
closeTime: rippleTimeToISO8601(ledger.close_time),
closeTimeResolution: ledger.close_time_resolution,
closeFlags: ledger.close_flags,
ledgerHash: ledger.hash || ledger.ledger_hash,
ledgerVersion: ledgerVersion,
parentLedgerHash: ledger.parent_hash,
parentCloseTime: rippleTimeToISO8601(ledger.parent_close_time),
totalDrops: ledger.total_coins || ledger.totalCoins,
transactionHash: ledger.transaction_hash
},
parseTransactions(ledger.transactions, ledgerVersion),
parseState(ledger.accountState)
))
}

View File

@@ -14,7 +14,7 @@ function removeAnyCounterpartyEncoding(address: string, amount: Amount) {
}
function createAdjustment(
address: string, adjustmentWithoutAddress: Object): any {
address: string, adjustmentWithoutAddress: object): any {
const amountKey = _.keys(adjustmentWithoutAddress)[0]
const amount = adjustmentWithoutAddress[amountKey]
return _.set({address: address}, amountKey,

View File

@@ -3,7 +3,7 @@ import {removeUndefined, txFlags} from '../../common'
import parseAmount from './amount'
const claimFlags = txFlags.PaymentChannelClaim
function parsePaymentChannelClaim(tx: any): Object {
function parsePaymentChannelClaim(tx: any): object {
assert(tx.TransactionType === 'PaymentChannelClaim')
return removeUndefined({

View File

@@ -3,7 +3,7 @@ import {parseTimestamp} from './utils'
import {removeUndefined} from '../../common'
import parseAmount from './amount'
function parsePaymentChannelCreate(tx: any): Object {
function parsePaymentChannelCreate(tx: any): object {
assert(tx.TransactionType === 'PaymentChannelCreate')
return removeUndefined({

View File

@@ -3,7 +3,7 @@ import {parseTimestamp} from './utils'
import {removeUndefined} from '../../common'
import parseAmount from './amount'
function parsePaymentChannelFund(tx: any): Object {
function parsePaymentChannelFund(tx: any): object {
assert(tx.TransactionType === 'PaymentChannelFund')
return removeUndefined({

View File

@@ -17,7 +17,8 @@ function removeGenericCounterparty(amount, address) {
_.omit(amount, 'counterparty') : amount
}
function parsePayment(tx: any): Object {
// Payment specification
function parsePayment(tx: any): object {
assert(tx.TransactionType === 'Payment')
const source = {
@@ -27,10 +28,13 @@ function parsePayment(tx: any): Object {
tag: tx.SourceTag
}
const destination = {
const destination: {
address: string,
tag: number | undefined
} = {
address: tx.Destination,
amount: removeGenericCounterparty(parseAmount(tx.Amount), tx.Destination),
tag: tx.DestinationTag
// Notice that `amount` is omitted to prevent misinterpretation
}
return removeUndefined({

View File

@@ -42,7 +42,7 @@ function parseTransactionType(type) {
return mapping[type] || null
}
function parseTransaction(tx: any): any {
function parseTransaction(tx: any, includeRawTransaction: boolean): any {
const type = parseTransactionType(tx.TransactionType)
const mapping = {
'payment': parsePayment,
@@ -72,7 +72,8 @@ function parseTransaction(tx: any): any {
sequence: tx.Sequence,
id: tx.hash,
specification: removeUndefined(specification),
outcome: outcome ? removeUndefined(outcome) : undefined
outcome: outcome ? removeUndefined(outcome) : undefined,
rawTransaction: includeRawTransaction ? JSON.stringify(tx) : undefined
})
}

View File

@@ -1,5 +1,5 @@
import * as assert from 'assert'
import {parseQuality} from './utils'
import {parseQuality, parseMemos} from './utils'
import {txFlags, removeUndefined} from '../../common'
const flags = txFlags.TrustSet
@@ -13,13 +13,14 @@ function parseFlag(flagsValue, trueValue, falseValue) {
return undefined
}
function parseTrustline(tx: any): Object {
function parseTrustline(tx: any): object {
assert(tx.TransactionType === 'TrustSet')
return removeUndefined({
limit: tx.LimitAmount.value,
currency: tx.LimitAmount.currency,
counterparty: tx.LimitAmount.issuer,
memos: parseMemos(tx),
qualityIn: parseQuality(tx.QualityIn),
qualityOut: parseQuality(tx.QualityOut),
ripplingDisabled: parseFlag(

View File

@@ -103,6 +103,8 @@ function parseOutcome(tx: any): any|undefined {
}
const balanceChanges = transactionParser.parseBalanceChanges(metadata)
const orderbookChanges = transactionParser.parseOrderbookChanges(metadata)
const channelChanges = transactionParser.parseChannelChanges(metadata)
removeEmptyCounterpartyInBalanceChanges(balanceChanges)
removeEmptyCounterpartyInOrderbookChanges(orderbookChanges)
@@ -112,6 +114,7 @@ function parseOutcome(tx: any): any|undefined {
fee: common.dropsToXrp(tx.Fee),
balanceChanges: balanceChanges,
orderbookChanges: orderbookChanges,
channelChanges: channelChanges,
ledgerVersion: tx.ledger_index,
indexInLedger: tx.meta.TransactionIndex,
deliveredAmount: parseDeliveredAmount(tx)

View File

@@ -1,7 +1,13 @@
import * as _ from 'lodash'
import BigNumber from 'bignumber.js'
import {getXRPBalance, renameCounterpartyToIssuer} from './utils'
import {validate, toRippledAmount, errors} from '../common'
import {
validate,
toRippledAmount,
errors,
xrpToDrops,
dropsToXrp
} from '../common'
import {Connection} from '../common'
import parsePathfind from './parse/pathfind'
import {RippledAmount, Amount} from '../common/types/objects'
@@ -23,7 +29,11 @@ function addParams(request: PathFindRequest, result: RippledPathsResponse
function requestPathFind(connection: Connection, pathfind: PathFind
): Promise<RippledPathsResponse> {
const destinationAmount: Amount = _.assign(
{value: '-1'},
{
// This is converted back to drops by toRippledAmount()
value: pathfind.destination.amount.currency === 'XRP' ?
dropsToXrp('-1') : '-1'
},
pathfind.destination.amount
)
const request: PathFindRequest = {
@@ -95,13 +105,21 @@ function filterSourceFundsLowPaths(pathfind: PathFind,
): RippledPathsResponse {
if (pathfind.source.amount &&
pathfind.destination.amount.value === undefined && paths.alternatives) {
paths.alternatives = _.filter(paths.alternatives, alt =>
!!alt.source_amount &&
!!pathfind.source.amount &&
// TODO: Returns false when alt.source_amount is a string. Fix?
typeof alt.source_amount !== 'string' &&
new BigNumber(alt.source_amount.value).eq(pathfind.source.amount.value)
)
paths.alternatives = _.filter(paths.alternatives, alt => {
if (!alt.source_amount) {
return false
}
const pathfindSourceAmountValue = new BigNumber(
pathfind.source.amount.currency === 'XRP' ?
xrpToDrops(pathfind.source.amount.value) :
pathfind.source.amount.value)
const altSourceAmountValue = new BigNumber(
typeof alt.source_amount === 'string' ?
alt.source_amount :
alt.source_amount.value
)
return altSourceAmountValue.eq(pathfindSourceAmountValue)
})
}
return paths
}

View File

@@ -7,7 +7,8 @@ import {FormattedTransactionType} from '../transaction/types'
export type TransactionOptions = {
minLedgerVersion?: number,
maxLedgerVersion?: number
maxLedgerVersion?: number,
includeRawTransaction?: boolean
}
type TransactionResponse = FormattedTransactionType & {
hash: string,
@@ -18,7 +19,7 @@ type TransactionResponse = FormattedTransactionType & {
function attachTransactionDate(connection: Connection, tx: any
): Promise<FormattedTransactionType> {
): Promise<TransactionResponse> {
if (tx.date) {
return Promise.resolve(tx)
}
@@ -83,31 +84,25 @@ function convertError(connection: Connection, options: TransactionOptions,
function formatResponse(options: TransactionOptions, tx: TransactionResponse
): FormattedTransactionType {
if (tx.validated !== true || !isTransactionInRange(tx, options)) {
throw new errors.NotFoundError('Transaction not found')
throw new errors.NotFoundError('Transaction not found')
}
return parseTransaction(tx)
return parseTransaction(tx, options.includeRawTransaction)
}
function getTransaction(id: string, options: TransactionOptions = {}
async function getTransaction(id: string, options: TransactionOptions = {}
): Promise<FormattedTransactionType> {
validate.getTransaction({id, options})
const request = {
command: 'tx',
transaction: id,
binary: false
const _options = await utils.ensureLedgerVersion.call(this, options)
try {
const tx = await this.request('tx', {
transaction: id,
binary: false
})
const txWithDate = await attachTransactionDate(this.connection, tx)
return formatResponse(_options, txWithDate)
} catch (error) {
throw (await convertError(this.connection, _options, error))
}
return utils.ensureLedgerVersion.call(this, options).then(_options => {
return this.connection.request(request).then((tx: TransactionResponse) =>
attachTransactionDate(this.connection, tx)
).then(_.partial(formatResponse, _options))
.catch(error => {
return convertError(this.connection, _options, error).then(_error => {
throw _error
})
})
})
}
export default getTransaction

View File

@@ -18,6 +18,7 @@ export type TransactionsOptions = {
initiated?: boolean,
counterparty?: string,
types?: Array<string>,
includeRawTransactions?: boolean,
binary?: boolean,
startTx?: FormattedTransactionType
}
@@ -35,11 +36,11 @@ function parseBinaryTransaction(transaction) {
}
}
function parseAccountTxTransaction(tx) {
function parseAccountTxTransaction(tx, includeRawTransaction: boolean) {
const _tx = tx.tx_blob ? parseBinaryTransaction(tx) : tx
// rippled uses a different response format for 'account_tx' than 'tx'
return parseTransaction(_.assign({}, _tx.tx,
{meta: _tx.meta, validated: _tx.validated}))
{meta: _tx.meta, validated: _tx.validated}), includeRawTransaction)
}
function counterpartyFilter(filters, tx: FormattedTransactionType) {
@@ -87,11 +88,13 @@ function orderFilter(
function formatPartialResponse(address: string,
options: TransactionsOptions, data
) {
const parse = tx =>
parseAccountTxTransaction(tx, options.includeRawTransactions)
return {
marker: data.marker,
results: data.transactions
.filter(tx => tx.validated)
.map(parseAccountTxTransaction)
.map(parse)
.filter(_.partial(transactionFilter, address, options))
.filter(_.partial(orderFilter, options))
}

View File

@@ -106,7 +106,7 @@ function isPendingLedgerVersion(connection: Connection,
}
function ensureLedgerVersion(options: any
): Promise<Object> {
): Promise<object> {
if (Boolean(options) && options.ledgerVersion !== undefined &&
options.ledgerVersion !== null
) {

7
src/offline/derive.ts Normal file
View File

@@ -0,0 +1,7 @@
import {deriveKeypair, deriveAddress} from 'ripple-keypairs'
export {
deriveKeypair,
deriveAddress
}

View File

@@ -2,14 +2,14 @@ import keypairs = require('ripple-keypairs')
import * as common from '../common'
const {errors, validate} = common
function generateAddress(options?: Object): Object {
function generateAddress(options?: object): object {
const secret = keypairs.generateSeed(options)
const keypair = keypairs.deriveKeypair(secret)
const address = keypairs.deriveAddress(keypair.publicKey)
return {secret, address}
}
function generateAddressAPI(options?: Object): Object {
function generateAddressAPI(options?: object): object {
validate.generateAddress({options})
try {
return generateAddress(options)

View File

@@ -25,13 +25,33 @@ function hashLedgerHeader(ledgerHeader) {
return hashes.computeLedgerHash(header)
}
function computeTransactionHash(ledger, version) {
if (ledger.rawTransactions === undefined) {
function computeTransactionHash(ledger, version,
options: ComputeLedgerHashOptions) {
let transactions: any[]
if (ledger.rawTransactions) {
transactions = JSON.parse(ledger.rawTransactions)
} else if (ledger.transactions) {
try {
transactions = ledger.transactions.map(tx =>
JSON.parse(tx.rawTransaction))
} catch (e) {
if (e.toString() === 'SyntaxError: Unexpected' +
' token u in JSON at position 0') {
// one or more of the `tx.rawTransaction`s is undefined
throw new common.errors.ValidationError('ledger'
+ ' is missing raw transactions')
}
}
} else {
if (options.computeTreeHashes) {
throw new common.errors.ValidationError('transactions'
+ ' property is missing from the ledger')
}
return ledger.transactionHash
}
const transactions: any[] = JSON.parse(ledger.rawTransactions)
const txs = _.map(transactions, tx => {
const mergeTx = _.assign({}, _.omit(tx, 'tx'), tx.tx || {})
// rename `meta` back to `metaData`
const renameMeta = _.assign({}, _.omit(mergeTx, 'meta'),
tx.meta ? {metaData: tx.meta} : {})
return renameMeta
@@ -40,13 +60,21 @@ function computeTransactionHash(ledger, version) {
if (ledger.transactionHash !== undefined
&& ledger.transactionHash !== transactionHash) {
throw new common.errors.ValidationError('transactionHash in header'
+ ' does not match computed hash of transactions')
+ ' does not match computed hash of transactions', {
transactionHashInHeader: ledger.transactionHash,
computedHashOfTransactions: transactionHash
})
}
return transactionHash
}
function computeStateHash(ledger, version) {
function computeStateHash(ledger, version,
options: ComputeLedgerHashOptions) {
if (ledger.rawState === undefined) {
if (options.computeTreeHashes) {
throw new common.errors.ValidationError('rawState'
+ ' property is missing from the ledger')
}
return ledger.stateHash
}
const state = JSON.parse(ledger.rawState)
@@ -60,11 +88,16 @@ function computeStateHash(ledger, version) {
const sLCF_SHAMapV2 = 0x02
function computeLedgerHash(ledger: any): string {
export type ComputeLedgerHashOptions = {
computeTreeHashes?: boolean
}
function computeLedgerHash(ledger: any,
options: ComputeLedgerHashOptions = {}): string {
const version = ((ledger.closeFlags & sLCF_SHAMapV2) === 0) ? 1 : 2
const subhashes = {
transactionHash: computeTransactionHash(ledger, version),
stateHash: computeStateHash(ledger, version)
transactionHash: computeTransactionHash(ledger, version, options),
stateHash: computeStateHash(ledger, version, options)
}
return hashLedgerHeader(_.assign({}, ledger, subhashes))
}

View File

@@ -16,7 +16,7 @@ function disconnect(): Promise<void> {
return this.connection.disconnect()
}
function formatLedgerClose(ledgerClose: any): Object {
function formatLedgerClose(ledgerClose: any): object {
return {
baseFeeXRP: common.dropsToXrp(ledgerClose.fee_base),
ledgerHash: ledgerClose.ledger_hash,

View File

@@ -16,7 +16,7 @@ function compareSigners(a, b) {
.comparedTo(addressToBigNumber(b.Signer.Account))
}
function combine(signedTransactions: Array<string>): Object {
function combine(signedTransactions: Array<string>): object {
validate.combine({signedTransactions})
// TODO: signedTransactions is an array of strings in the documentation, but

View File

@@ -12,7 +12,7 @@ export type EscrowCancellation = {
function createEscrowCancellationTransaction(account: string,
payment: EscrowCancellation
): Object {
): object {
const txJSON: any = {
TransactionType: 'EscrowCancel',
Account: account,

View File

@@ -18,7 +18,7 @@ export type EscrowCreation = {
function createEscrowCreationTransaction(account: string,
payment: EscrowCreation
): Object {
): object {
const txJSON: any = {
TransactionType: 'EscrowCreate',
Account: account,
@@ -46,8 +46,8 @@ function createEscrowCreationTransaction(account: string,
}
if (Boolean(payment.allowCancelAfter) && Boolean(payment.allowExecuteAfter) &&
txJSON.CancelAfter <= txJSON.FinishAfter) {
throw new ValidationError('"CancelAfter" must be after "FinishAfter" for'
+ ' EscrowCreate')
throw new ValidationError('prepareEscrowCreation: ' +
'"allowCancelAfter" must be after "allowExecuteAfter"')
}
return txJSON
}

View File

@@ -15,7 +15,7 @@ export type EscrowExecution = {
function createEscrowExecutionTransaction(account: string,
payment: EscrowExecution
): Object {
): object {
const txJSON: any = {
TransactionType: 'EscrowFinish',
Account: account,

View File

@@ -5,7 +5,7 @@ import {Instructions, Prepare} from './types'
function createOrderCancellationTransaction(account: string,
orderCancellation: any
): Object {
): object {
const txJSON: any = {
TransactionType: 'OfferCancel',
Account: account,
@@ -17,7 +17,7 @@ function createOrderCancellationTransaction(account: string,
return txJSON
}
function prepareOrderCancellation(address: string, orderCancellation: Object,
function prepareOrderCancellation(address: string, orderCancellation: object,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareOrderCancellation({address, orderCancellation, instructions})

View File

@@ -16,7 +16,7 @@ export type PaymentChannelClaim = {
function createPaymentChannelClaimTransaction(account: string,
claim: PaymentChannelClaim
): Object {
): object {
const txJSON: any = {
Account: account,
TransactionType: 'PaymentChannelClaim',

View File

@@ -14,7 +14,7 @@ export type PaymentChannelCreate = {
function createPaymentChannelCreateTransaction(account: string,
paymentChannel: PaymentChannelCreate
): Object {
): object {
const txJSON: any = {
Account: account,
TransactionType: 'PaymentChannelCreate',

View File

@@ -10,7 +10,7 @@ export type PaymentChannelFund = {
function createPaymentChannelFundTransaction(account: string,
fund: PaymentChannelFund
): Object {
): object {
const txJSON: any = {
Account: account,
TransactionType: 'PaymentChannelFund',

View File

@@ -7,6 +7,7 @@ const ValidationError = utils.common.errors.ValidationError
import {Instructions, Prepare} from './types'
import {Amount, Adjustment, MaxAdjustment,
MinAdjustment, Memo} from '../common/types/objects'
import {xrpToDrops} from '../common'
export interface Payment {
@@ -32,12 +33,12 @@ export interface Payment {
function isMaxAdjustment(
source: Adjustment | MaxAdjustment): source is MaxAdjustment {
return (source as MaxAdjustment).maxAmount !== undefined
return (source as MaxAdjustment).maxAmount !== undefined
}
function isMinAdjustment(
destination: Adjustment | MinAdjustment): destination is MinAdjustment {
return (destination as MinAdjustment).minAmount !== undefined
return (destination as MinAdjustment).minAmount !== undefined
}
function isXRPToXRPPayment(payment: Payment): boolean {
@@ -46,11 +47,12 @@ function isXRPToXRPPayment(payment: Payment): boolean {
? source.maxAmount.currency : source.amount.currency
const destinationCurrency = isMinAdjustment(destination)
? destination.minAmount.currency : destination.amount.currency
return sourceCurrency === 'XRP' && destinationCurrency === 'XRP'
return (sourceCurrency === 'XRP' || sourceCurrency === 'drops') &&
(destinationCurrency === 'XRP' || destinationCurrency === 'drops')
}
function isIOUWithoutCounterparty(amount: Amount): boolean {
return amount && amount.currency !== 'XRP'
return amount && amount.currency !== 'XRP' && amount.currency !== 'drops'
&& amount.counterparty === undefined
}
@@ -72,12 +74,19 @@ function applyAnyCounterpartyEncoding(payment: Payment): void {
function createMaximalAmount(amount: Amount): Amount {
const maxXRPValue = '100000000000'
const maxIOUValue = '9999999999999999e80'
const maxValue = amount.currency === 'XRP' ? maxXRPValue : maxIOUValue
let maxValue
if (amount.currency === 'XRP') {
maxValue = maxXRPValue
} else if (amount.currency === 'drops') {
maxValue = xrpToDrops(maxXRPValue)
} else {
maxValue = maxIOUValue
}
return _.assign({}, amount, {value: maxValue})
}
function createPaymentTransaction(address: string, paymentArgument: Payment
): Object {
): object {
const payment = _.cloneDeep(paymentArgument)
applyAnyCounterpartyEncoding(payment)

View File

@@ -26,7 +26,7 @@ function setTransactionFlags(txJSON: any, values: FormattedSettings) {
}
}
function setTransactionFields(txJSON: Object, input: FormattedSettings) {
function setTransactionFields(txJSON: object, input: FormattedSettings) {
const fieldSchema = AccountFields
for (const fieldName in fieldSchema) {
const field = fieldSchema[fieldName]
@@ -67,7 +67,7 @@ function convertTransferRate(transferRate: number | string): number | string {
return (new BigNumber(transferRate)).shift(9).toNumber()
}
function formatSignerEntry(signer: WeightedSigner): Object {
function formatSignerEntry(signer: WeightedSigner): object {
return {
SignerEntry: {
Account: signer.address,
@@ -114,7 +114,7 @@ function createSettingsTransactionWithoutMemos(
}
function createSettingsTransaction(account: string, settings: FormattedSettings
): Object {
): object {
const txJSON = createSettingsTransactionWithoutMemos(account, settings)
if (settings.memos !== undefined) {
txJSON.Memos = _.map(settings.memos, utils.convertMemo)

Some files were not shown because too many files have changed in this diff Show More