Compare commits

..

27 Commits
1.0.0 ... 1.1.0

Author SHA1 Message Date
Elliot Lee
50a7320886 Release 1.1.0 2018-10-31 16:36:20 -07:00
Elliot Lee
418987476e Add DepositPreauth (#958)
* Expose parseAccountFlags() and add docs
* Add example snippet
* Default to node v10 for nvm
* Maintain existing behavior for getSettings
* Increase max line length from 80 to 120 (ter-max-len)
2018-10-31 16:27:32 -07:00
Elliot Lee
89e4ff328c Apply formatting to book-offers fixture 2018-10-31 16:07:25 -07:00
Elliot Lee
04bf49cb43 Support node 10 (#964)
* Update webpack from 3.11.0 to 3.12.0 and upath from 1.0.4 to 1.1.0
* Run: yarn upgrade gulp
  * See https://github.com/gulpjs/gulp/issues/2162
* Update README
* Travis: test node 10
2018-10-30 14:15:42 -07:00
Elliot Lee
1c017df2a3 Merge pull request #955 from jcperkins12/feature/balanceChanges-TypeCorrection
Type balanceChanges should be array of changes not array with one change
2018-10-24 20:34:03 -07:00
Elliot Lee
5fed1f08e4 Document xrpToDrops, dropsToXrp, iso8601ToRippleTime, schemaValidator, and more
The following methods are available directly under the RippleAPI object,
not under schemaValidator:

isValidAddress, isValidSecret, deriveKeypair, deriveAddress
2018-10-18 01:16:50 -07:00
Elliot Lee
82c349c8c4 HISTORY: List Check transaction types
Transaction types that were added in 0.19.0
2018-10-17 16:22:48 -07:00
Elliot Lee
0f7af6a4e9 Add depositAuth to FormattedSettings type 2018-10-17 15:58:52 -07:00
Elliot Lee
8db1791ed2 README: Remove obsolete badges 2018-10-16 12:48:48 -07:00
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
8dfec20871 Changed type of balanceChanges made to an account from an array of one change to an array of 1 change to and array of records with the type of a blanceChange 2018-10-10 12:21:16 -05: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
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
101 changed files with 2854 additions and 498 deletions

2
.nvmrc
View File

@@ -1 +1 @@
v8
v10

View File

@@ -3,6 +3,7 @@ node_js:
- 6
- 8
- 9
- 10
script:
- yarn compile
- yarn test

View File

@@ -1,5 +1,62 @@
# ripple-lib Release History
## 1.1.0 (2018-10-31)
+ Add support for Node.js v10 LTS (#964)
+ Add [DepositPreauth](https://developers.ripple.com/depositauth.html) ([#958](https://github.com/ripple/ripple-lib/pull/958))
+ In `FormattedTransactionType`, the `Outcome`'s `balanceChanges` property had
the wrong type. This is now fixed (#955)
+ Add/fix docs for: xrpToDrops, dropsToXrp, iso8601ToRippleTime, schemaValidator, isValidAddress, isValidSecret, deriveKeypair, deriveAddress
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
e1d742092b3c0fcee97a875e18db4baeab3bbc82f08b96e883ee188c5f0cfb37 ripple-1.1.0-debug.js
f28921f57a133678dcb3cb54c497626bd76b1f953d22d61f3ddca31c8947d552 ripple-1.1.0-min.js
3696871a80c1102635699994adcaf00cdfdfcff5014fc2eba3d8f8d8437c8f91 ripple-1.1.0.js
```
## 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.
@@ -233,6 +290,9 @@ below.
## 0.19.0 (2018-03-02)
+ [Add support for Checks](https://github.com/ripple/ripple-lib/pull/853)
+ **CheckCreate** adds a check entry to the ledger. The check is a promise from the source of the check that the destination of the check may cash the check and receive up to the SendMax specified on the check. The check may have an (optional) expiration, after which the check may no longer be cashed.
+ **CheckCancel** removes the check from the ledger without transferring funds. Either the check's source or destination can cancel the check at any time. After a check has expired, any account can cancel the check.
+ **CheckCash** is a request by the destination of the check to transfer a requested amount of funds, up to the check's SendMax, from the source to the destination. The destination may receive less than the SendMax due to transfer fees.
+ [Add support for the Deposit Authorization account root flag](https://github.com/ripple/ripple-lib/pull/852)
+ [Generate .ts.d TypeScript declaration files](https://github.com/ripple/ripple-lib/pull/851)
+ [Improve documentation of getTransactions params](https://github.com/ripple/ripple-lib/pull/856)

View File

@@ -2,8 +2,6 @@
A JavaScript API for interacting with the XRP Ledger
[![Circle CI](https://circleci.com/gh/ripple/ripple-lib/tree/develop.svg?style=svg)](https://circleci.com/gh/ripple/ripple-lib/tree/develop) [![Coverage Status](https://coveralls.io/repos/ripple/ripple-lib/badge.png?branch=develop)](https://coveralls.io/r/ripple/ripple-lib?branch=develop)
[![NPM](https://nodei.co/npm/ripple-lib.png)](https://www.npmjs.org/package/ripple-lib)
### Features
@@ -12,16 +10,20 @@ A JavaScript API for interacting with the XRP Ledger
+ Issue [rippled API](https://ripple.com/build/rippled-apis/) requests
+ Listen to events on the XRP Ledger (transaction, ledger, etc.)
+ Sign and submit transactions to the XRP Ledger
+ Type definitions for TypeScript
## Getting Started
See also: [RippleAPI Beginners Guide](https://ripple.com/build/rippleapi-beginners-guide/)
You can use `npm`, but we recommend using `yarn` for the added assurance provided by `yarn.lock`.
### Requirements
+ [Yarn Installation Instructions](https://yarnpkg.com/en/docs/install)
+ **[Node v10](https://nodejs.org/)** is recommended. Other versions may work but are not frequently tested.
+ **[Yarn](https://yarnpkg.com/)** is recommended. `npm` may work but we use `yarn.lock`.
Install `ripple-lib`:
### Install
In an existing project (with `package.json`), install `ripple-lib`:
```
$ yarn add ripple-lib
```

View File

@@ -58,6 +58,8 @@
- [getAccountObjects](#getaccountobjects)
- [getPaymentChannel](#getpaymentchannel)
- [getLedger](#getledger)
- [parseAccountFlags](#parseaccountflags)
- [prepareTransaction](#preparetransaction)
- [preparePayment](#preparepayment)
- [prepareTrustline](#preparetrustline)
- [prepareOrder](#prepareorder)
@@ -76,9 +78,19 @@
- [combine](#combine)
- [submit](#submit)
- [generateAddress](#generateaddress)
- [isValidAddress](#isvalidaddress)
- [isValidSecret](#isvalidsecret)
- [deriveKeypair](#derivekeypair)
- [deriveAddress](#deriveaddress)
- [signPaymentChannelClaim](#signpaymentchannelclaim)
- [verifyPaymentChannelClaim](#verifypaymentchannelclaim)
- [computeLedgerHash](#computeledgerhash)
- [xrpToDrops](#xrptodrops)
- [dropsToXrp](#dropstoxrp)
- [iso8601ToRippleTime](#iso8601torippletime)
- [txFlags](#txflags)
- [schemaValidator](#schemavalidator)
- [schemaValidate](#schemavalidate)
- [API Events](#api-events)
- [ledger](#ledger)
- [error](#error)
@@ -156,7 +168,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.
@@ -1131,7 +1143,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).
@@ -1283,7 +1295,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.
@@ -1515,7 +1527,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.
@@ -1660,7 +1672,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.
@@ -1827,7 +1839,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.
@@ -1923,7 +1935,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.
@@ -2045,7 +2057,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.
@@ -2426,7 +2438,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.
@@ -3530,7 +3542,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).
@@ -3609,7 +3621,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).
@@ -3982,7 +3994,7 @@ return api.getAccountObjects(address: address).then(objects =>
## getPaymentChannel
`getPaymentChannel(id: string): Promise<Object>`
`getPaymentChannel(id: string): Promise<object>`
Returns specified payment channel.
@@ -4038,7 +4050,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.
@@ -4099,9 +4111,103 @@ return api.getLedger()
```
## parseAccountFlags
`parseAccountFlags(Flags: number): object`
Parse an `AccountRoot` object's [`Flags`](https://developers.ripple.com/accountroot.html#accountroot-flags).
### Parameters
This method takes one parameter, the AccountRoot `Flags` number to parse. Note that flags have different mappings on other types of objects or in transactions such as AccountSet.
### Return Value
This method returns an object with containing a key for each AccountRoot flag known to this version of RippleAPI. Each flag has a boolean value of `true` or `false`.
### Example
```javascript
const account_info = await api.request('account_info', {account: 'rKsdkGhyZH6b2Zzd5hNnEqSv2wpznn4n6N'})
const flags = api.parseAccountFlags(account_info.account_data.Flags)
console.log(JSON.stringify(flags, null, 2))
```
```json
{
"passwordSpent": false,
"requireDestinationTag": false,
"requireAuthorization": false,
"depositAuth": true,
"disallowIncomingXRP": false,
"disableMasterKey": false,
"noFreeze": false,
"globalFreeze": false,
"defaultRipple": false
}
```
## prepareTransaction
`prepareTransaction(address: string, transaction: object, instructions: object): Promise<object>`
Prepare a transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
This method works with any of [the transaction types supported by rippled](https://developers.ripple.com/transaction-types.html).
Notably, this is the preferred method for preparing a `DepositPreauth` transaction (added in rippled 1.1.0).
### Parameters
Name | Type | Description
---- | ---- | -----------
transaction | [transaction](https://developers.ripple.com/transaction-formats.html) | The specification (JSON) of the transaction to prepare. Set `Account` to the address of the account that is creating the transaction. You may omit auto-fillable fields like `Fee`, `Flags`, and `Sequence` to have them set automatically.
instructions | [instructions](#transaction-instructions) | *Optional* Instructions for executing the transaction.
### Return Value
This method returns a promise that resolves with an object with the following structure:
<aside class="notice">
All "prepare*" methods have the same return type.
</aside>
Name | Type | Description
---- | ---- | -----------
txJSON | string | The prepared transaction in rippled JSON format.
instructions | object | The instructions for how to execute the transaction after adding automatic defaults.
*instructions.* fee | [value](#value) | An exact fee to pay for the transaction. See [Transaction Fees](#transaction-fees) for more information.
*instructions.* sequence | [sequence](#account-sequence-number) | The initiating account's sequence number for this transaction.
*instructions.* maxLedgerVersion | integer,null | The highest ledger version that the transaction can be included in. Set to `null` if there is no maximum.
*instructions.* maxLedgerVersion | string,null | The highest ledger version that the transaction can be included in. Set to `null` if there is no maximum.
### Example
```javascript
async function preparedPreauth() {
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.prepareTransaction({
TransactionType: 'DepositPreauth',
Account: address,
Authorize: 'rMyVso4p83khNyHdV1m1PggV9QNadCj8wM'
});
}
```
```javascript
{
txJSON: '{"TransactionType":"DepositPreauth","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Authorize":"rMyVso4p83khNyHdV1m1PggV9QNadCj8wM","Flags":2147483648,"LastLedgerSequence":13561714,"Fee":"12","Sequence":1}',
instructions: {
fee: '0.000012',
sequence: 1,
maxLedgerVersion: 13561714
}
}
```
## 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).
@@ -4171,7 +4277,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).
@@ -4239,7 +4345,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).
@@ -4307,7 +4413,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).
@@ -4360,7 +4466,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).
@@ -4424,7 +4530,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).
@@ -4488,7 +4594,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).
@@ -4544,7 +4650,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).
@@ -4602,7 +4708,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).
@@ -4660,7 +4766,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).
@@ -4715,7 +4821,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).
@@ -4771,7 +4877,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).
@@ -4830,7 +4936,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).
@@ -4885,7 +4991,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).
@@ -4945,12 +5051,16 @@ 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).
This method can sign any of [the transaction types supported by ripple-binary-codec](https://github.com/ripple/ripple-binary-codec/blob/cfcde79c19c359e9a0466d7bc3dc9a3aef47bb99/src/enums/definitions.json#L1637). When a new transaction type is added to the XRP Ledger, it will be unrecognized until `ripple-binary-codec` is updated. If you try to sign an unrecognized transaction type, this method throws an error similar to the following:
`Error: [TRANSACTION_TYPE] is not a valid name or ordinal for TransactionType`
### Parameters
Name | Type | Description
@@ -5030,7 +5140,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).
@@ -5104,6 +5214,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`
@@ -5184,7 +5376,7 @@ true
## computeLedgerHash
`computeLedgerHash(ledger: Object): string`
`computeLedgerHash(ledger: object): string`
Compute the hash of a ledger.
@@ -5238,6 +5430,200 @@ return api.computeLedgerHash(ledger);
"F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349"
```
## xrpToDrops
`xrpToDrops(xrp: string | BigNumber): string`
Converts an XRP amount to drops. 1 XRP = 1,000,000 drops, so 1 drop = 0.000001 XRP. This method is useful when converting amounts for use with the rippled API, which requires XRP amounts to be specified in drops.
### Parameters
`xrp`: A string or BigNumber representing an amount of XRP. If `xrp` is a string, it may start with `-`, must contain at least one number, and may contain up to one `.`. This method throws a `ValidationError` for invalid input.
### Return Value
A string representing an equivalent amount of drops.
### Example
```javascript
return api.xrpToDrops('1');
```
```json
'1000000'
```
## dropsToXrp
`dropsToXrp(drops: string | BigNumber): string`
Converts an amount of drops to XRP. 1 drop = 0.000001 XRP, so 1 XRP = 1,000,000 drops. This method is useful when converting amounts from the rippled API, which describes XRP amounts in drops.
### Parameters
`drops`: A string or BigNumber representing an amount of drops. If `drops` is a string, it may start with `-` and must contain at least one number. This method throws a `ValidationError` for invalid input.
### Return Value
A string representing an equivalent amount of XRP.
### Example
```javascript
return api.dropsToXrp('1');
```
```json
'0.000001'
```
## iso8601ToRippleTime
`iso8601ToRippleTime(iso8601: string): number`
This method parses a string representation of a date, and returns the number of seconds since the "Ripple Epoch" of January 1, 2000 (00:00 UTC).
The Ripple Epoch is 946684800 seconds after the Unix Epoch.
This method is useful for creating timestamps to use with the rippled APIs. The rippled APIs represent time as an unsigned integer of the number of seconds since the Ripple Epoch.
### Parameters
`iso8601`: A string representing a date and time. This string is parsed using JavaScript's `Date.parse()` method.
### Return Value
The number of seconds since the Ripple Epoch.
### Example
```javascript
api.iso8601ToRippleTime('2017-02-17T15:04:57Z');
```
```json
540659097
```
## txFlags
`txFlags.TRANSACTION_TYPE.FLAG`
This object provides constants for use when creating or interpreting transaction flags. Most transactions have a set of bit-flags that represent various options that affect how a transaction should behave. These options are represented as binary values that can be combined with bitwise-or operations to encode multiple flags at once.
Most flags only have meaning for a specific transaction type. The same bitwise value may be reused for flags on different transaction types, so it is important to pay attention to the transaction type when setting and reading flags.
Bits that are not defined as flags MUST be 0.
### Global Flag
Applies globally to all transactions.
`txFlags.Universal.FullyCanonicalSig`: Require a fully-canonical signature. When preparing transactions, ripple-lib enables this flag for you.
### Payment Flags
`txFlags.Payment.NoRippleDirect`: Do not use the default path; only use specified paths. This is intended to force the transaction to take arbitrage opportunities. Most clients do not need this.
`txFlags.Payment.PartialPayment`: If the specified destination amount cannot be sent without spending more than the source maxAmount, reduce the received amount instead of failing outright. See [Partial Payments](https://developers.ripple.com/partial-payments.html) for more details.
`txFlags.Payment.LimitQuality`: 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`. See [Limit Quality](https://developers.ripple.com/payment.html#limit-quality) for details.
### OfferCreate Flags
`txFlags.OfferCreate.Passive`: If enabled, the offer does not consume offers that exactly match it, and instead becomes an Offer object in the ledger. It still consumes offers that cross it.
`txFlags.OfferCreate.ImmediateOrCancel`: Treat the offer as an Immediate or Cancel order. If enabled, the offer never becomes a ledger object: it only tries to match existing offers in the ledger.
`txFlags.OfferCreate.FillOrKill`: Treat the offer as a Fill or Kill order.
`txFlags.OfferCreate.Sell`: Treat the offer as a Sell order. With `order.direction = 'sell'`, exchange the entire `order.quantity`, even if it means obtaining more than the `order.totalPrice` amount in exchange. If using `prepareOrder`, ripple-lib sets this flag for you.
### TrustSet Flags
`txFlags.TrustSet.SetAuth`: Authorize the other party to hold issuances from this account. (No effect unless using the AccountSet.RequireAuth flag.) Cannot be unset.
`txFlags.TrustSet.NoRipple`: Obsolete.
`txFlags.TrustSet.SetNoRipple`: Blocks [rippling](https://developers.ripple.com/rippling.html) between two trustlines of the same currency, if this flag is set on both.
`txFlags.TrustSet.ClearNoRipple`: Clears the No-[Rippling](https://developers.ripple.com/rippling.html) flag.
`txFlags.TrustSet.SetFreeze`: Freeze the trustline. A non-XRP currency can be frozen by the exchange or gateway that issued it. XRP cannot be frozen.
`txFlags.TrustSet.ClearFreeze`: Unfreeze the trustline.
### AccountSet Flags
You can use the `prepareSettings` method to change your account flags. This method uses AccountSet flags internally.
In the rippled API, Account Flags can be enabled and disabled with the SetFlag and ClearFlag parameters. See [AccountSet Flags](https://developers.ripple.com/accountset.html#accountset-flags).
The AccountSet transaction type has some transaction flags, but their use is discouraged.
* `txFlags.AccountSet.RequireDestTag`
* `txFlags.AccountSet.OptionalDestTag`
* `txFlags.AccountSet.RequireAuth`
* `txFlags.AccountSet.OptionalAuth`
* `txFlags.AccountSet.DisallowXRP`
* `txFlags.AccountSet.AllowXRP`
### PaymentChannelClaim Flags
`txFlags.PaymentChannelClaim.Renew`: Clear the channel's Expiration time. (Expiration is different from the channel's immutable CancelAfter time.) Only the source address of the payment channel can use this flag.
`txFlags.PaymentChannelClaim.Close`: Request to close the channel. Only the channel source and destination addresses can use this flag. This flag closes the channel immediately if it has no more XRP allocated to it after processing the current claim, or if the destination address uses it. If the source address uses this flag when the channel still holds XRP, this schedules the channel to close after SettleDelay seconds have passed. (Specifically, this sets the Expiration of the channel to the close time of the previous ledger plus the channel's SettleDelay time, unless the channel already has an earlier Expiration time.) If the destination address uses this flag when the channel still holds XRP, any XRP that remains after processing the claim is returned to the source address.
### Other Transaction Types
The remaining transaction types do not have any flags at this time.
* OfferCancel
* SetRegularKey
* SignerListSet
* EscrowCreate
* EscrowFinish
* EscrowCancel
* PaymentChannelCreate
* PaymentChannelFund
## schemaValidator
Unlike the rest of the ripple-lib API, schemaValidator is a static object on RippleAPI. It provides utility methods that do not use a server.
## schemaValidate
`RippleAPI.schemaValidator.schemaValidate(schemaName: string, object: any): void`
This method checks an object for conformance to a specified schema. It does not return anything, but will throw a `ValidationError` if the object does not conform to the schema.
### Example
```javascript
RippleAPI.schemaValidator.schemaValidate('sign', {
signedTransaction: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100BDE09A1F6670403F341C21A77CF35BA47E45CDE974096E1AA5FC39811D8269E702203D60291B9A27F1DCABA9CF5DED307B4F23223E0B6F156991DB601DFB9C41CE1C770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '02ACE87F1996E3A23690A5BB7F1774BF71CCBA68F79805831B42ABAD5913D6F4'
})
```
```json
undefined
```
If the object is valid (conforms to the schema), nothing is returned. Otherwise, `schemaValidate` throws an error:
```javascript
RippleAPI.schemaValidator.schemaValidate('sign', {
signedTransaction: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100BDE09A1F6670403F341C21A77CF35BA47E45CDE974096E1AA5FC39811D8269E702203D60291B9A27F1DCABA9CF5DED307B4F23223E0B6F156991DB601DFB9C41CE1C770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '123'
})
```
```
[ValidationError(instance.id does not match pattern "^[A-F0-9]{64}$")]
```
# API Events
## ledger

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

@@ -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

@@ -28,6 +28,8 @@
<% include getAccountObjects.md.ejs %>
<% include getPaymentChannel.md.ejs %>
<% include getLedger.md.ejs %>
<% include parseAccountFlags.md.ejs %>
<% include prepareTransaction.md.ejs %>
<% include preparePayment.md.ejs %>
<% include prepareTrustline.md.ejs %>
<% include prepareOrder.md.ejs %>
@@ -46,7 +48,15 @@
<% 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 %>
<% include xrpToDropsAndDropsToXrp.md.ejs %>
<% include iso8601ToRippleTime.md.ejs %>
<% include txFlags.md.ejs %>
<% include schemaValidator.md.ejs %>
<% include events.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

@@ -0,0 +1,27 @@
## iso8601ToRippleTime
`iso8601ToRippleTime(iso8601: string): number`
This method parses a string representation of a date, and returns the number of seconds since the "Ripple Epoch" of January 1, 2000 (00:00 UTC).
The Ripple Epoch is 946684800 seconds after the Unix Epoch.
This method is useful for creating timestamps to use with the rippled APIs. The rippled APIs represent time as an unsigned integer of the number of seconds since the Ripple Epoch.
### Parameters
`iso8601`: A string representing a date and time. This string is parsed using JavaScript's `Date.parse()` method.
### Return Value
The number of seconds since the Ripple Epoch.
### Example
```javascript
api.iso8601ToRippleTime('2017-02-17T15:04:57Z');
```
```json
540659097
```

View File

@@ -0,0 +1,35 @@
## parseAccountFlags
`parseAccountFlags(Flags: number): object`
Parse an `AccountRoot` object's [`Flags`](https://developers.ripple.com/accountroot.html#accountroot-flags).
### Parameters
This method takes one parameter, the AccountRoot `Flags` number to parse. Note that flags have different mappings on other types of objects or in transactions such as AccountSet.
### Return Value
This method returns an object with containing a key for each AccountRoot flag known to this version of RippleAPI. Each flag has a boolean value of `true` or `false`.
### Example
```javascript
const account_info = await api.request('account_info', {account: 'rKsdkGhyZH6b2Zzd5hNnEqSv2wpznn4n6N'})
const flags = api.parseAccountFlags(account_info.account_data.Flags)
console.log(JSON.stringify(flags, null, 2))
```
```json
{
"passwordSpent": false,
"requireDestinationTag": false,
"requireAuthorization": false,
"depositAuth": true,
"disallowIncomingXRP": false,
"disableMasterKey": false,
"noFreeze": false,
"globalFreeze": false,
"defaultRipple": false
}
```

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).

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

@@ -0,0 +1,50 @@
## prepareTransaction
`prepareTransaction(address: string, transaction: object, instructions: object): Promise<object>`
Prepare a transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
This method works with any of [the transaction types supported by rippled](https://developers.ripple.com/transaction-types.html).
Notably, this is the preferred method for preparing a `DepositPreauth` transaction (added in rippled 1.1.0).
### Parameters
Name | Type | Description
---- | ---- | -----------
transaction | [transaction](https://developers.ripple.com/transaction-formats.html) | The specification (JSON) of the transaction to prepare. Set `Account` to the address of the account that is creating the transaction. You may omit auto-fillable fields like `Fee`, `Flags`, and `Sequence` to have them set automatically.
instructions | [instructions](#transaction-instructions) | *Optional* Instructions for executing the transaction.
### Return Value
This method returns a promise that resolves with an object with the following structure:
<aside class="notice">
All "prepare*" methods have the same return type.
</aside>
<%- renderSchema("output/prepare.json") %>
### Example
```javascript
async function preparedPreauth() {
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.prepareTransaction({
TransactionType: 'DepositPreauth',
Account: address,
Authorize: 'rMyVso4p83khNyHdV1m1PggV9QNadCj8wM'
});
}
```
```javascript
{
txJSON: '{"TransactionType":"DepositPreauth","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Authorize":"rMyVso4p83khNyHdV1m1PggV9QNadCj8wM","Flags":2147483648,"LastLedgerSequence":13561714,"Fee":"12","Sequence":1}',
instructions: {
fee: '0.000012',
sequence: 1,
maxLedgerVersion: 13561714
}
}
```

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

@@ -0,0 +1,35 @@
## schemaValidator
Unlike the rest of the ripple-lib API, schemaValidator is a static object on RippleAPI. It provides utility methods that do not use a server.
## schemaValidate
`RippleAPI.schemaValidator.schemaValidate(schemaName: string, object: any): void`
This method checks an object for conformance to a specified schema. It does not return anything, but will throw a `ValidationError` if the object does not conform to the schema.
### Example
```javascript
RippleAPI.schemaValidator.schemaValidate('sign', {
signedTransaction: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100BDE09A1F6670403F341C21A77CF35BA47E45CDE974096E1AA5FC39811D8269E702203D60291B9A27F1DCABA9CF5DED307B4F23223E0B6F156991DB601DFB9C41CE1C770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '02ACE87F1996E3A23690A5BB7F1774BF71CCBA68F79805831B42ABAD5913D6F4'
})
```
```json
undefined
```
If the object is valid (conforms to the schema), nothing is returned. Otherwise, `schemaValidate` throws an error:
```javascript
RippleAPI.schemaValidator.schemaValidate('sign', {
signedTransaction: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D874473045022100BDE09A1F6670403F341C21A77CF35BA47E45CDE974096E1AA5FC39811D8269E702203D60291B9A27F1DCABA9CF5DED307B4F23223E0B6F156991DB601DFB9C41CE1C770A726970706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '123'
})
```
```
[ValidationError(instance.id does not match pattern "^[A-F0-9]{64}$")]
```

View File

@@ -1,12 +1,16 @@
## 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).
This method can sign any of [the transaction types supported by ripple-binary-codec](https://github.com/ripple/ripple-binary-codec/blob/cfcde79c19c359e9a0466d7bc3dc9a3aef47bb99/src/enums/definitions.json#L1637). When a new transaction type is added to the XRP Ledger, it will be unrecognized until `ripple-binary-codec` is updated. If you try to sign an unrecognized transaction type, this method throws an error similar to the following:
`Error: [TRANSACTION_TYPE] is not a valid name or ordinal for TransactionType`
### Parameters
<%- renderSchema("input/sign.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).

81
docs/src/txFlags.md.ejs Normal file
View File

@@ -0,0 +1,81 @@
## txFlags
`txFlags.TRANSACTION_TYPE.FLAG`
This object provides constants for use when creating or interpreting transaction flags. Most transactions have a set of bit-flags that represent various options that affect how a transaction should behave. These options are represented as binary values that can be combined with bitwise-or operations to encode multiple flags at once.
Most flags only have meaning for a specific transaction type. The same bitwise value may be reused for flags on different transaction types, so it is important to pay attention to the transaction type when setting and reading flags.
Bits that are not defined as flags MUST be 0.
### Global Flag
Applies globally to all transactions.
`txFlags.Universal.FullyCanonicalSig`: Require a fully-canonical signature. When preparing transactions, ripple-lib enables this flag for you.
### Payment Flags
`txFlags.Payment.NoRippleDirect`: Do not use the default path; only use specified paths. This is intended to force the transaction to take arbitrage opportunities. Most clients do not need this.
`txFlags.Payment.PartialPayment`: If the specified destination amount cannot be sent without spending more than the source maxAmount, reduce the received amount instead of failing outright. See [Partial Payments](https://developers.ripple.com/partial-payments.html) for more details.
`txFlags.Payment.LimitQuality`: 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`. See [Limit Quality](https://developers.ripple.com/payment.html#limit-quality) for details.
### OfferCreate Flags
`txFlags.OfferCreate.Passive`: If enabled, the offer does not consume offers that exactly match it, and instead becomes an Offer object in the ledger. It still consumes offers that cross it.
`txFlags.OfferCreate.ImmediateOrCancel`: Treat the offer as an Immediate or Cancel order. If enabled, the offer never becomes a ledger object: it only tries to match existing offers in the ledger.
`txFlags.OfferCreate.FillOrKill`: Treat the offer as a Fill or Kill order.
`txFlags.OfferCreate.Sell`: Treat the offer as a Sell order. With `order.direction = 'sell'`, exchange the entire `order.quantity`, even if it means obtaining more than the `order.totalPrice` amount in exchange. If using `prepareOrder`, ripple-lib sets this flag for you.
### TrustSet Flags
`txFlags.TrustSet.SetAuth`: Authorize the other party to hold issuances from this account. (No effect unless using the AccountSet.RequireAuth flag.) Cannot be unset.
`txFlags.TrustSet.NoRipple`: Obsolete.
`txFlags.TrustSet.SetNoRipple`: Blocks [rippling](https://developers.ripple.com/rippling.html) between two trustlines of the same currency, if this flag is set on both.
`txFlags.TrustSet.ClearNoRipple`: Clears the No-[Rippling](https://developers.ripple.com/rippling.html) flag.
`txFlags.TrustSet.SetFreeze`: Freeze the trustline. A non-XRP currency can be frozen by the exchange or gateway that issued it. XRP cannot be frozen.
`txFlags.TrustSet.ClearFreeze`: Unfreeze the trustline.
### AccountSet Flags
You can use the `prepareSettings` method to change your account flags. This method uses AccountSet flags internally.
In the rippled API, Account Flags can be enabled and disabled with the SetFlag and ClearFlag parameters. See [AccountSet Flags](https://developers.ripple.com/accountset.html#accountset-flags).
The AccountSet transaction type has some transaction flags, but their use is discouraged.
* `txFlags.AccountSet.RequireDestTag`
* `txFlags.AccountSet.OptionalDestTag`
* `txFlags.AccountSet.RequireAuth`
* `txFlags.AccountSet.OptionalAuth`
* `txFlags.AccountSet.DisallowXRP`
* `txFlags.AccountSet.AllowXRP`
### PaymentChannelClaim Flags
`txFlags.PaymentChannelClaim.Renew`: Clear the channel's Expiration time. (Expiration is different from the channel's immutable CancelAfter time.) Only the source address of the payment channel can use this flag.
`txFlags.PaymentChannelClaim.Close`: Request to close the channel. Only the channel source and destination addresses can use this flag. This flag closes the channel immediately if it has no more XRP allocated to it after processing the current claim, or if the destination address uses it. If the source address uses this flag when the channel still holds XRP, this schedules the channel to close after SettleDelay seconds have passed. (Specifically, this sets the Expiration of the channel to the close time of the previous ledger plus the channel's SettleDelay time, unless the channel already has an earlier Expiration time.) If the destination address uses this flag when the channel still holds XRP, any XRP that remains after processing the claim is returned to the source address.
### Other Transaction Types
The remaining transaction types do not have any flags at this time.
* OfferCancel
* SetRegularKey
* SignerListSet
* EscrowCreate
* EscrowFinish
* EscrowCancel
* PaymentChannelCreate
* PaymentChannelFund

View File

@@ -0,0 +1,47 @@
## xrpToDrops
`xrpToDrops(xrp: string | BigNumber): string`
Converts an XRP amount to drops. 1 XRP = 1,000,000 drops, so 1 drop = 0.000001 XRP. This method is useful when converting amounts for use with the rippled API, which requires XRP amounts to be specified in drops.
### Parameters
`xrp`: A string or BigNumber representing an amount of XRP. If `xrp` is a string, it may start with `-`, must contain at least one number, and may contain up to one `.`. This method throws a `ValidationError` for invalid input.
### Return Value
A string representing an equivalent amount of drops.
### Example
```javascript
return api.xrpToDrops('1');
```
```json
'1000000'
```
## dropsToXrp
`dropsToXrp(drops: string | BigNumber): string`
Converts an amount of drops to XRP. 1 drop = 0.000001 XRP, so 1 XRP = 1,000,000 drops. This method is useful when converting amounts from the rippled API, which describes XRP amounts in drops.
### Parameters
`drops`: A string or BigNumber representing an amount of drops. If `drops` is a string, it may start with `-` and must contain at least one number. This method throws a `ValidationError` for invalid input.
### Return Value
A string representing an equivalent amount of XRP.
### Example
```javascript
return api.dropsToXrp('1');
```
```json
'0.000001'
```

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-lib",
"version": "1.0.0",
"version": "1.1.0",
"license": "ISC",
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
"files": [
@@ -23,7 +23,7 @@
"jsonschema": "1.2.2",
"lodash": "^4.17.4",
"ripple-address-codec": "^2.0.1",
"ripple-binary-codec": "^0.1.13",
"ripple-binary-codec": "0.2.0",
"ripple-hashes": "^0.3.1",
"ripple-keypairs": "^0.10.1",
"ripple-lib-transactionparser": "0.7.1",
@@ -55,7 +55,7 @@
"tslint-eslint-rules": "^4.1.1",
"typescript": "2.9.2",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"webpack": "3.12.0",
"yargs": "^8.0.2"
},
"scripts": {

View File

@@ -0,0 +1,11 @@
const RippleAPI = require('../dist/npm').RippleAPI
const api = new RippleAPI({server: 'wss://s.altnet.rippletest.net:51233'})
parseAccountFlags()
async function parseAccountFlags() {
await api.connect()
const account_info = await api.request('account_info', {account: 'rKsdkGhyZH6b2Zzd5hNnEqSv2wpznn4n6N'})
const flags = api.parseAccountFlags(account_info.account_data.Flags)
console.log(JSON.stringify(flags, null, 2))
}

View File

@@ -23,7 +23,7 @@ import getBalanceSheet from './ledger/balance-sheet'
import getPaths from './ledger/pathfind'
import getOrders from './ledger/orders'
import getOrderbook from './ledger/orderbook'
import getSettings from './ledger/settings'
import {getSettings, parseAccountFlags} from './ledger/settings'
import getAccountInfo from './ledger/accountinfo'
import getAccountObjects from './ledger/accountobjects'
import getPaymentChannel from './ledger/payment-channel'
@@ -45,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'
@@ -301,6 +302,7 @@ class RippleAPI extends EventEmitter {
getAccountObjects = getAccountObjects
getPaymentChannel = getPaymentChannel
getLedger = getLedger
parseAccountFlags = parseAccountFlags
preparePayment = preparePayment
prepareTrustline = prepareTrustline
@@ -321,6 +323,8 @@ class RippleAPI extends EventEmitter {
submit = submit
generateAddress = generateAddressAPI
deriveKeypair = deriveKeypair
deriveAddress = deriveAddress
computeLedgerHash = computeLedgerHash
signPaymentChannelClaim = signPaymentChannelClaim
verifyPaymentChannelClaim = verifyPaymentChannelClaim
@@ -330,6 +334,9 @@ class RippleAPI extends EventEmitter {
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

@@ -160,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

@@ -9,7 +9,7 @@ export type GetServerInfoResponse = {
hostID: string,
ioLatencyMs: number,
load?: {
jobTypes: Array<Object>,
jobTypes: Array<object>,
threads: number
},
lastClose: {

View File

@@ -1,5 +1,3 @@
const txFlags = {
// Universal flags can apply to any transaction type
Universal: {

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

@@ -11,20 +11,21 @@ export type Signers = {
}
export type FormattedSettings = {
passwordSpent?: boolean,
requireDestinationTag?: boolean,
requireAuthorization?: boolean,
disallowIncomingXRP?: boolean,
disableMasterKey?: boolean,
enableTransactionIDTracking?: boolean,
noFreeze?: boolean,
globalFreeze?: boolean,
defaultRipple?: boolean,
emailHash?: string|null,
messageKey?: string,
depositAuth?: boolean,
disableMasterKey?: boolean,
disallowIncomingXRP?: boolean,
domain?: string,
transferRate?: number|null,
emailHash?: string|null,
enableTransactionIDTracking?: boolean,
globalFreeze?: boolean,
memos?: Memo[],
messageKey?: string,
noFreeze?: boolean,
passwordSpent?: boolean,
regularKey?: string,
requireAuthorization?: boolean,
requireDestinationTag?: boolean,
signers?: Signers,
memos?: Memo[]
transferRate?: number|null
}

View File

@@ -133,7 +133,7 @@ function rippleToUnixTimestamp(rpepoch: number): number {
/**
* @param {Number|Date} timestamp (ms since unix epoch)
* @return {Number} seconds since ripple epoch ( 1/1/2000 GMT)
* @return {Number} seconds since ripple epoch (1/1/2000 GMT)
*/
function unixToRippleTimestamp(timestamp: number): number {
return Math.round(timestamp / 1000) - 0x386D4380
@@ -143,6 +143,10 @@ function rippleTimeToISO8601(rippleTime: number): string {
return new Date(rippleToUnixTimestamp(rippleTime)).toISOString()
}
/**
* @param {string} iso8601 international standard date format
* @return {number} seconds since ripple epoch (1/1/2000 GMT)
*/
function iso8601ToRippleTime(iso8601: string): number {
return unixToRippleTimestamp(Date.parse(iso8601))
}

View File

@@ -25,5 +25,4 @@ async function getLedger(
return parseLedger(response.ledger)
}
export default getLedger

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

@@ -0,0 +1,21 @@
import * as assert from 'assert'
import {removeUndefined} from '../../common'
export type FormattedDepositPreauth = {
// account (address) of the sender to preauthorize
authorize: string,
// account (address) of the sender whose preauthorization should be revoked
unauthorize: string
}
function parseDepositPreauth(tx: any): FormattedDepositPreauth {
assert(tx.TransactionType === 'DepositPreauth')
return removeUndefined({
authorize: tx.Authorize,
unauthorize: tx.Unauthorize
})
}
export default parseDepositPreauth

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,7 +17,7 @@ export type FormattedLedger = {
parentCloseTime: string,
totalDrops: string,
transactionHash: string,
transactions?: Array<Object>,
transactions?: Array<object>,
transactionHashes?: Array<string>,
rawState?: string,
stateHashes?: Array<string>

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

@@ -18,7 +18,7 @@ function removeGenericCounterparty(amount, address) {
}
// Payment specification
function parsePayment(tx: any): Object {
function parsePayment(tx: any): object {
assert(tx.TransactionType === 'Payment')
const source = {

View File

@@ -1,4 +1,3 @@
import * as assert from 'assert'
import {parseOutcome} from './utils'
import {removeUndefined} from '../../common'
import parsePayment from './payment'
@@ -12,6 +11,7 @@ import parseEscrowCancellation from './escrow-cancellation'
import parseCheckCreate from './check-create'
import parseCheckCash from './check-cash'
import parseCheckCancel from './check-cancel'
import parseDepositPreauth from './deposit-preauth'
import parsePaymentChannelCreate from './payment-channel-create'
import parsePaymentChannelFund from './payment-channel-fund'
import parsePaymentChannelClaim from './payment-channel-claim'
@@ -19,29 +19,33 @@ import parseFeeUpdate from './fee-update'
import parseAmendment from './amendment'
function parseTransactionType(type) {
// Ordering matches https://developers.ripple.com/transaction-types.html
const mapping = {
Payment: 'payment',
TrustSet: 'trustline',
OfferCreate: 'order',
OfferCancel: 'orderCancellation',
AccountSet: 'settings',
SetRegularKey: 'settings',
CheckCancel: 'checkCancel',
CheckCash: 'checkCash',
CheckCreate: 'checkCreate',
DepositPreauth: 'depositPreauth',
EscrowCancel: 'escrowCancellation',
EscrowCreate: 'escrowCreation',
EscrowFinish: 'escrowExecution',
EscrowCancel: 'escrowCancellation',
CheckCreate: 'checkCreate',
CheckCash: 'checkCash',
CheckCancel: 'checkCancel',
OfferCancel: 'orderCancellation',
OfferCreate: 'order',
Payment: 'payment',
PaymentChannelClaim: 'paymentChannelClaim',
PaymentChannelCreate: 'paymentChannelCreate',
PaymentChannelFund: 'paymentChannelFund',
PaymentChannelClaim: 'paymentChannelClaim',
SetRegularKey: 'settings',
SignerListSet: 'settings',
SetFee: 'feeUpdate', // pseudo-transaction
EnableAmendment: 'amendment' // pseudo-transaction
TrustSet: 'trustline',
EnableAmendment: 'amendment', // pseudo-transaction
SetFee: 'feeUpdate' // pseudo-transaction
}
return mapping[type] || null
}
// includeRawTransaction: undefined by default (getTransaction)
function parseTransaction(tx: any, includeRawTransaction: boolean): any {
const type = parseTransactionType(tx.TransactionType)
const mapping = {
@@ -56,6 +60,7 @@ function parseTransaction(tx: any, includeRawTransaction: boolean): any {
'checkCreate': parseCheckCreate,
'checkCash': parseCheckCash,
'checkCancel': parseCheckCancel,
'depositPreauth': parseDepositPreauth,
'paymentChannelCreate': parsePaymentChannelCreate,
'paymentChannelFund': parsePaymentChannelFund,
'paymentChannelClaim': parsePaymentChannelClaim,
@@ -63,8 +68,15 @@ function parseTransaction(tx: any, includeRawTransaction: boolean): any {
'amendment': parseAmendment
}
const parser: Function = mapping[type]
assert(parser !== undefined, 'Unrecognized transaction type')
const specification = parser(tx)
const specification = parser ? parser(tx) : {
UNAVAILABLE: 'Unrecognized transaction type.',
SEE_RAW_TRANSACTION: 'Since this type is unrecognized, `rawTransaction` is included in this response.'
}
if (!parser) {
includeRawTransaction = true
}
const outcome = parseOutcome(tx)
return removeUndefined({
type: type,

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

@@ -10,11 +10,17 @@ export type SettingsOptions = {
ledgerVersion?: number
}
function parseFlags(value) {
export function parseAccountFlags(
value: number,
options: {excludeFalse?: boolean} = {}) {
const settings = {}
for (const flagName in AccountFlags) {
if (value & AccountFlags[flagName]) {
settings[flagName] = true
} else {
if (!options.excludeFalse) {
settings[flagName] = false
}
}
}
return settings
@@ -22,12 +28,12 @@ function parseFlags(value) {
function formatSettings(response: AccountInfoResponse) {
const data = response.account_data
const parsedFlags = parseFlags(data.Flags)
const parsedFlags = parseAccountFlags(data.Flags, {excludeFalse: true})
const parsedFields = parseFields(data)
return _.assign({}, parsedFlags, parsedFields)
}
async function getSettings(
export async function getSettings(
this: RippleAPI, address: string, options: SettingsOptions = {}
): Promise<FormattedSettings> {
// 1. Validate
@@ -41,5 +47,3 @@ async function getSettings(
// 3. Return Formatted Response
return formatSettings(response)
}
export default getSettings

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

@@ -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,

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

@@ -47,7 +47,8 @@ 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 {
@@ -85,7 +86,7 @@ function createMaximalAmount(amount: Amount): Amount {
}
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)

View File

@@ -8,7 +8,7 @@ import {xrpToDrops} from '../common'
import {RippleAPI} from '../api'
const validate = utils.common.validate
function computeSignature(tx: Object, privateKey: string, signAs?: string) {
function computeSignature(tx: object, privateKey: string, signAs?: string) {
const signingData = signAs
? binary.encodeForMultisigning(tx, signAs)
: binary.encodeForSigning(tx)
@@ -79,6 +79,12 @@ function sign(
options
)
} else {
if (!keypair && !secret) {
// Clearer message than 'ValidationError: instance is not exactly one from [subschema 0],[subschema 1]'
throw new utils.common.errors.ValidationError(
'sign: Missing secret or keypair.'
)
}
return signWithKeypair(
this,
txJSON,

View File

@@ -14,7 +14,7 @@ function convertQuality(quality) {
function createTrustlineTransaction(account: string,
trustline: FormattedTrustlineSpecification
): Object {
): object {
const limit = {
currency: trustline.currency,
issuer: trustline.counterparty,

View File

@@ -34,7 +34,7 @@ export type Submit = {
engineResultCode: number,
engineResultMessage?: string,
txBlob?: string,
txJson?: Object
txJson?: object
}
export interface OfferCreateTransaction {
@@ -66,13 +66,13 @@ export type Outcome = {
indexInLedger: number,
fee: string,
balanceChanges: {
[key: string]: [{
[key: string]: {
currency: string,
counterparty?: string,
value: string
}]
}[]
},
orderbookChanges: Object,
orderbookChanges: object,
timestamp?: string
}

View File

@@ -45,7 +45,7 @@ function prepareTransaction(txJSON: any, api: RippleAPI,
const account = txJSON.Account
setCanonicalFlag(txJSON)
function prepareMaxLedgerVersion(): Promise<Object> {
function prepareMaxLedgerVersion(): Promise<object> {
if (instructions.maxLedgerVersion !== undefined) {
if (instructions.maxLedgerVersion !== null) {
txJSON.LastLedgerSequence = instructions.maxLedgerVersion
@@ -60,7 +60,7 @@ function prepareTransaction(txJSON: any, api: RippleAPI,
})
}
function prepareFee(): Promise<Object> {
function prepareFee(): Promise<object> {
const multiplier = instructions.signersCount === undefined ? 1 :
instructions.signersCount + 1
if (instructions.fee !== undefined) {
@@ -94,7 +94,7 @@ function prepareTransaction(txJSON: any, api: RippleAPI,
})
}
async function prepareSequence(): Promise<Object> {
async function prepareSequence(): Promise<object> {
if (instructions.sequence !== undefined) {
txJSON.Sequence = instructions.sequence
return Promise.resolve(txJSON)

View File

@@ -270,6 +270,54 @@ describe('RippleAPI', function () {
}, /dropsToXrp:\ invalid\ value\ '\.\.\.'\,\ should\ be\ a\ number\ matching\ \(\^\-\?\[0\-9\]\*\.\?\[0\-9\]\*\$\)\./)
})
})
describe('isValidAddress', function () {
it('returns true for valid address', function () {
assert(this.api.isValidAddress('rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K'));
})
it('returns false for invalid address', function () {
assert(!this.api.isValidAddress('foobar'));
})
})
describe('isValidSecret', function () {
it('returns true for valid secret', function () {
assert(this.api.isValidSecret('snsakdSrZSLkYpCXxfRkS4Sh96PMK'));
})
it('returns false for invalid secret', function () {
assert(!this.api.isValidSecret('foobar'));
})
})
describe('deriveKeypair', function () {
it('returns keypair for secret', function () {
var keypair = this.api.deriveKeypair('snsakdSrZSLkYpCXxfRkS4Sh96PMK');
assert.equal(keypair.privateKey, '008850736302221AFD59FF9CA1A29D4975F491D726249302EE48A3078A8934D335');
assert.equal(keypair.publicKey, '035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06');
})
it('returns keypair for ed25519 secret', function () {
var keypair = this.api.deriveKeypair('sEdV9eHWbibBnTj7b1H5kHfPfv7gudx');
assert.equal(keypair.privateKey, 'ED5C2EF6C2E3200DFA6B72F47935C7F64D35453646EA34919192538F458C7BC30F');
assert.equal(keypair.publicKey, 'ED0805EC4E728DB87C0CA6C420751F296C57A5F42D02E9E6150CE60694A44593E5');
})
it('throws with an invalid secret', function (){
assert.throws(() => {
this.api.deriveKeypair('...');
}, /^Error\: Non\-base58 character$/)
})
})
describe('deriveAddress', function () {
it('returns address for public key', function () {
var address = this.api.deriveAddress('035332FBA71D705BD5D97014A833BE2BBB25BEFCD3506198E14AFEA241B98C2D06');
assert.equal(address, 'rLczgQHxPhWtjkaQqn3Q6UM8AbRbbRvs5K');
})
})
describe('pagination', function () {
describe('hasNextPage', function () {
@@ -347,6 +395,126 @@ describe('RippleAPI', function () {
responses.preparePayment.minAmountXRPXRP, 'prepare'));
});
it('preparePayment - XRP to XRP', function () {
const payment = {
"source": {
"address": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"maxAmount": {
"value": "1",
"currency": "XRP"
}
},
"destination": {
"address": "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo",
"amount": {
"value": "1",
"currency": "XRP"
}
}
}
return this.api.preparePayment(address, payment, instructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
});
it('preparePayment - XRP drops to XRP drops', function () {
const payment = {
"source": {
"address": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"maxAmount": {
"value": "1000000",
"currency": "drops"
}
},
"destination": {
"address": "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo",
"amount": {
"value": "1000000",
"currency": "drops"
}
}
}
return this.api.preparePayment(address, payment, instructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
});
it('preparePayment - XRP drops to XRP', function () {
const payment = {
"source": {
"address": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"maxAmount": {
"value": "1000000",
"currency": "drops"
}
},
"destination": {
"address": "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo",
"amount": {
"value": "1",
"currency": "XRP"
}
}
}
return this.api.preparePayment(address, payment, instructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
});
it('preparePayment - XRP to XRP drops', function () {
const payment = {
"source": {
"address": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"maxAmount": {
"value": "1",
"currency": "XRP"
}
},
"destination": {
"address": "rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo",
"amount": {
"value": "1000000",
"currency": "drops"
}
}
}
return this.api.preparePayment(address, payment, instructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"Payment","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Destination":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Amount":"1000000","Flags":2147483648,"LastLedgerSequence":8820051,"Sequence":23,"Fee":"12"}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
});
it('preparePayment - XRP to XRP no partial', function () {
assert.throws(() => {
this.api.preparePayment(address, requests.preparePayment.wrongPartial);
@@ -715,6 +883,54 @@ describe('RippleAPI', function () {
'prepare'));
});
it('prepareTransaction - DepositPreauth - Authorize', function () {
const localInstructions = _.defaults({
maxFee: '0.000012'
}, instructions)
const txJSON = {
TransactionType: 'DepositPreauth',
Account: address,
Authorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo'
}
return this.api.prepareTransaction(txJSON, localInstructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"DepositPreauth","Account":"' + address + '","Authorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
})
it('prepareTransaction - DepositPreauth - Unauthorize', function () {
const localInstructions = _.defaults({
maxFee: '0.000012'
}, instructions)
const txJSON = {
TransactionType: 'DepositPreauth',
Account: address,
Unauthorize: 'rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo'
}
return this.api.prepareTransaction(txJSON, localInstructions).then(response => {
const expected = {
txJSON: '{"TransactionType":"DepositPreauth","Account":"' + address + '","Unauthorize":"rpZc4mVfWUif9CRoHRKKcmhu1nx2xktxBo","Flags":2147483648,"LastLedgerSequence":8820051,"Fee":"12","Sequence":23}',
instructions: {
fee: '0.000012',
sequence: 23,
maxLedgerVersion: 8820051
}
}
return checkResult(expected, 'prepare', response)
})
})
describe('prepareTransaction - Payment', function () {
it('normal', function () {
@@ -1539,6 +1755,14 @@ describe('RippleAPI', function () {
'getTransaction'));
});
it('getTransaction - trustline add memo', function () {
const hash =
'9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220';
return this.api.getTransaction(hash).then(
_.partial(checkResult, responses.getTransaction.trustlineAddMemo,
'getTransaction'));
});
it('getTransaction - not validated', function () {
const hash =
'4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10';

View File

@@ -0,0 +1,34 @@
{
"type": "trustline",
"address": "r9nNHpMW4TfPnmWcRHi3Qmev2jjCJ2koi4",
"sequence": 40,
"id": "9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220",
"specification": {
"limit": "2000",
"currency": "USD",
"counterparty": "rkrbFLphJzLvyLE1obALNARQAnoVypoNX",
"memos": [
{
"type": "test",
"format": "plain/text",
"data": "test trust"
}
]
},
"outcome": {
"result": "tesSUCCESS",
"timestamp": "2018-09-18T03:36:51.000Z",
"fee": "0.000012",
"balanceChanges": {
"r9nNHpMW4TfPnmWcRHi3Qmev2jjCJ2koi4": [
{
"currency": "XRP",
"value": "-0.000012"
}
]
},
"orderbookChanges": {},
"ledgerVersion": 41608182,
"indexInLedger": 5
}
}

View File

@@ -43,6 +43,7 @@ module.exports = {
setRegularKey: require('./get-transaction-settings-set-regular-key.json'),
trustlineFrozenOff: require('./get-transaction-trust-set-frozen-off.json'),
trustlineNoQuality: require('./get-transaction-trust-no-quality.json'),
trustlineAddMemo: require('./get-transaction-trust-add-memo.json'),
notValidated: require('./get-transaction-not-validated.json'),
checkCreate:
require('./get-transaction-check-create.json'),

File diff suppressed because it is too large Load Diff

View File

@@ -75,6 +75,7 @@ module.exports = {
TrustSet: require('./tx/trust-set.json'),
TrustSetFrozenOff: require('./tx/trust-set-frozen-off.json'),
TrustSetNoQuality: require('./tx/trust-set-no-quality.json'),
TrustSetAddMemo: require('./tx/trust-set-add-memo.json'),
NotFound: require('./tx/not-found.json'),
NoLedgerIndex: require('./tx/no-ledger-index.json'),
NoLedgerFound: require('./tx/no-ledger-found.json'),

View File

@@ -0,0 +1,59 @@
{
"id": 1,
"status": "success",
"type": "response",
"result": {
"Account": "r9nNHpMW4TfPnmWcRHi3Qmev2jjCJ2koi4",
"Fee": "12",
"Flags": 2147483648,
"LastLedgerSequence": 41608183,
"LimitAmount": {
"currency": "USD",
"issuer": "rkrbFLphJzLvyLE1obALNARQAnoVypoNX",
"value": "2000"
},
"Memos": [
{
"Memo": {
"MemoData": "74657374207472757374",
"MemoFormat": "706C61696E2F74657874",
"MemoType": "74657374"
}
}
],
"Sequence": 40,
"SigningPubKey": "033FD06C0EEE1D865B21B9E1CF35E672912241C5730C631E3965B205F014C9CF5A",
"TransactionType": "TrustSet",
"TxnSignature": "3045022100FA2BEFAB78C7EC214AEDAD18B423E03BBC48FD6728D93EC25A213B4C84A5D38102205B618CD7A52CD4351381D2676E0A6044E4181118716DE98E8DEFA845C097ECB9",
"date": 590557011,
"hash": "9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220",
"inLedger": 41608182,
"ledger_index": 41608182,
"meta": {
"AffectedNodes": [
{
"ModifiedNode": {
"FinalFields": {
"Account": "r9nNHpMW4TfPnmWcRHi3Qmev2jjCJ2koi4",
"Balance": "119672499",
"Flags": 0,
"OwnerCount": 4,
"Sequence": 41
},
"LedgerEntryType": "AccountRoot",
"LedgerIndex": "9FD944BCDE2F599A59FE8E8D7A764B69F4B0F818385C9E54C6CC46405F1E1925",
"PreviousFields": {
"Balance": "119672511",
"Sequence": 40
},
"PreviousTxnID": "8E16AD23970715E212DE6208E11397E4E394430D40EBF560F5A80FB8716429CF",
"PreviousTxnLgrSeq": 41607559
}
}
],
"TransactionIndex": 5,
"TransactionResult": "tesSUCCESS"
},
"validated": true
}
}

View File

@@ -345,6 +345,9 @@ module.exports = function createMockRippled(port) {
'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002') {
conn.send(createResponse(request, fixtures.tx.TrustSetNoQuality));
} else if (request.transaction ===
'9D6AC5FD6545B2584885B85E36759EB6440CDD41B6C55859F84AFDEE2B428220') {
conn.send(createResponse(request, fixtures.tx.TrustSetAddMemo));
}else if (request.transaction ===
'4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10') {
conn.send(createResponse(request, fixtures.tx.NotValidated));
} else if (request.transaction === hashes.NOTFOUND_TRANSACTION_HASH) {

View File

@@ -57,7 +57,7 @@
"triple-equals": true,
"forin": false,
"handle-callback-err": true,
"ter-max-len": [true, 80],
"ter-max-len": [true, 120],
"new-parens": true,
"object-curly-spacing": [true, "never"],
"object-literal-shorthand": false,

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