Compare commits

..

8 Commits

Author SHA1 Message Date
Mayukha Vadari
1b857cee98 one more update 2021-12-01 15:16:03 -05:00
Mayukha Vadari
3793012acd update rbc 2021-12-01 14:06:32 -05:00
Mayukha Vadari
515407bdaf update keypairs 2021-12-01 13:54:58 -05:00
Mayukha Vadari
23a15e416c update beta version 2021-12-01 13:11:35 -05:00
Mayukha Vadari
8ff9ebe276 edit address-codec and keypairs versions 2021-12-01 13:11:22 -05:00
Elliot Lee
dcf3473f1c bump version to 1.9.8-storm.1 2021-12-01 09:51:33 -08:00
Elliot Lee
ac99b3e25c bump ripple-binary-codec to 1.1.4-beta.1 2021-12-01 09:50:05 -08:00
natenichols
d6da4f820e publish a branch for data team's legacy process 2021-12-01 10:46:48 -06:00
1333 changed files with 68986 additions and 88588 deletions

29
.eslintrc.json Normal file
View File

@@ -0,0 +1,29 @@
{
"env": {
"browser": true,
"es6": true,
"node": true,
"mocha": true
},
"extends": [
"eslint:recommended"
],
"globals": {
"NodeJS": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"no-useless-constructor": 0,
"no-unused-vars": 0,
"no-prototype-builtins": 0,
"require-atomic-updates": 0,
"no-dupe-class-members": 0
}
}

View File

@@ -6,3 +6,8 @@ updates:
interval: monthly
time: "15:00"
open-pull-requests-limit: 10
ignore:
- dependency-name: jsonschema
versions:
- "> 1.2.2"
- "< 2"

View File

@@ -5,32 +5,14 @@ name: Node.js CI
on:
push:
branches: [ develop, master, 2.0 ]
branches: [ develop, master ]
pull_request:
workflow_dispatch:
branches: [ develop ]
jobs:
build-and-lint:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install -g npm@7
- run: npm ci
- run: npm run build
- run: npm run lint
unit:
runs-on: ubuntu-latest
runs-on: ubuntu-latest
strategy:
matrix:
@@ -42,10 +24,10 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install -g npm@7
- run: npm ci
- run: npm run build
- run: npm test
- run: yarn install
- run: yarn test
- run: yarn lint
- run: yarn build
integration:
runs-on: ubuntu-latest
@@ -60,7 +42,7 @@ jobs:
ports:
- 6006:6006
options:
--health-cmd="wget localhost:6006 || exit 1" --health-interval=5s --health-retries=10 --health-timeout=2s
--health-cmd="wget localhost:6006 || exit 1" --health-interval=5s --health-retries=10 --health-timeout=2s
steps:
- uses: actions/checkout@v2
@@ -68,36 +50,8 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install -g npm@7
- run: npm ci
- run: npm run build
- run: npm run test:integration
- run: yarn install
- run: yarn test:integration
env:
HOST: localhost
PORT: ${{ job.services.rippled.ports['6006'] }}
browser:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x] # This just needs to be compatible w/ puppeteer
services:
rippled:
image: natenichols/rippled-standalone:latest
ports:
- 6006:6006
options:
--health-cmd="wget localhost:6006 || exit 1" --health-interval=5s --health-retries=10 --health-timeout=2s
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install -g npm@7
- run: npm ci
- run: npm run build
- run: npm run test:browser

10
.gitignore vendored
View File

@@ -1,7 +1,7 @@
# .gitignore
# Ignore package locks other than npm.
yarn.lock
# Ignore package locks other than Yarn.
package-lock.json
npm-shrinkwrap.json
# Ignore vim swap files.
@@ -68,9 +68,3 @@ scripts/cache
# nyc (istanbul)
.nyc_output
# browser tests
testCompiledForWeb
# lerna debug
lerna-debug.log

10
.prettierrc Normal file
View File

@@ -0,0 +1,10 @@
{
"parser": "typescript",
"printWidth": 80,
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"quoteProps": "consistent",
"bracketSpacing": false
}

9
.travis.yml Normal file
View File

@@ -0,0 +1,9 @@
language: node_js
node_js:
- 10
- 12
- 13
script:
- yarn test
- yarn build
- yarn lint

View File

@@ -1,6 +0,0 @@
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode"
]
}

38
.vscode/settings.json vendored
View File

@@ -1,38 +0,0 @@
{
"editor.tabSize": 2,
"cSpell.words": [
"secp256k1"
],
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"eslint.alwaysShowStatus": true,
"eslint.lintTask.enable": true,
"eslint.codeAction.showDocumentation": {
"enable": true
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"files.trimTrailingWhitespace": true,
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/.hg/store/**": true
},
}

View File

@@ -1,6 +1,6 @@
# Applications using xrpl.js
# Applications using ripple-lib (RippleAPI)
A curated list of some of the projects and apps that leverage `xrpl.js` in some way.
A curated list of some of the projects and apps that leverage `ripple-lib` in some way.
**Have one to add?** Please edit this file and open a PR!
@@ -53,7 +53,7 @@ Warning: Use at your own risk.
- **[XRP Scan - XRP Ledger explorer](https://xrpscan.com)**
XRP Ledger explorer, metrics and analytics.
- **[xrplorer](https://xrplorer.com)**
XRP Ledger explorer, API, metrics, and analytics using a graph database that is synchronized live with the XRPL.
@@ -132,7 +132,7 @@ Warning: Use at your own risk.
- **[XRP Faucets for Testnet and Devnet](https://xrpl.org/xrp-testnet-faucet.html)**
Get some test funds for development on the test network. The faucet uses `xrpl.js`.
Get some test funds for development on the test network. The faucet uses `ripple-lib`.
## Code samples and libraries
@@ -156,7 +156,7 @@ Warning: Use at your own risk.
For about $30 in parts (Raspberry Pi, 3.3V Relay board and a few wires) you can build your own power switch that will switch on if a streaming ILP payment comes in. When the payment stream stops, the power turns off.
## Related apps that do not appear to use xrpl.js
## Related apps that do not appear to use ripple-lib
- **[XRP Stats](https://ledger.exposed/)** (ledger.exposed)

View File

@@ -1,149 +0,0 @@
# Contributing
## Set up your dev environment
### Requirements
We use Node v14 for development - that is the version that our linters require.
You must also use `npm` v7. You can check your `npm` version with:
```bash
npm -v
```
If your `npm` version is too old, use this command to update it:
```bash
npm -g i npm@7
```
### Set up
1. Clone the repository
2. `cd` into the repository
3. Install dependencies with `npm install`
### Build
```bash
npm run build
```
## Run the linter
```bash
npm install
npm run build
npm run lint
```
## Running Tests
For integration and browser tests, we use a `rippled` node in standalone mode to test xrpl.js code against. To set this up, you can either run `rippled` locally, or set up the Docker container `natenichols/rippled-standalone:latest` for this purpose. The latter will require you to [install Docker](https://docs.docker.com/get-docker/).
### Unit Tests
```bash
npm install
npm run build
npm test
```
### Integration Tests
```bash
npm install
# sets up the rippled standalone Docker container - you can skip this step if you already have it set up
docker run -p 6006:6006 -it natenichols/rippled-standalone:latest
npm run build
npm run test:integration
```
### Browser Tests
There are two ways to run browser tests.
One is in the browser - run `npm run build:browserTests` and open `test/localIntegrationRunner.html` in your browser.
The other is in the command line (this is what we use for CI) -
```bash
npm run build
# sets up the rippled standalone Docker container - you can skip this step if you already have it set up
docker run -p 6006:6006 -it natenichols/rippled-standalone:latest
npm run test:browser
```
## Generate reference docs
You can see the complete reference documentation at [`xrpl.js` docs](js.xrpl.org). You can also generate them locally using `typedoc`:
```bash
npm run docgen
```
## Adding and removing packages
`xrpl.js` uses `lerna` and `npm`'s workspaces features to manage a monorepo.
Adding and removing packages requires a slightly different process than normal
as a result.
### Adding or removing development dependencies
`xrpl.js` strives to use the same development dependencies in all packages.
You may add and remove dev dependencies like normal:
```bash
### adding a new dependency
npm install --save-dev abbrev
### removing a dependency
npm uninstall --save-dev abbrev
```
### Adding or removing runtime dependencies
You need to specify which package is changing using the `-w` flag:
```bash
### adding a new dependency to `xrpl`
npm install abbrev -w xrpl
### adding a new dependency to `ripple-keypairs`
npm install abbrev -w ripple-keypairs
### removing a dependency
npm uninstall abbrev -w xrpl
```
## Release process
### Editing the Code
* Your changes should have unit and/or integration tests.
* Your changes should pass the linter.
* Your code should pass all the tests on Github (which check the linter, unit and integration tests on Node 12/14/16, and browser tests).
* Open a PR against `develop` and ensure that all CI passes.
* Get a full code review from one of the maintainers.
* Merge your changes.
### Release
1. Ensure that all tests passed on the last CI that ran on `develop`.
2. Open a PR to update the docs if docs were modified.
3. Create a branch off `develop` that ensures that `HISTORY.md` is updated appropriately for each package.
* Use `shasum -a 256 build/*` to get the SHA-256 checksums. Add these to `HISTORY.md` as well.
4. Merge this branch into `develop`.
5. If this is not a beta release: Merge `develop` into `master` (`--ff-only`) and push to github. This is important because we have docs telling developers to use master to get the latest release.
6. Create a new Github release/tag off of this branch.
7. Run `npm publish --dry-run` and make sure everything looks good.
8. Publish the release to `npm`.
* If this is a beta release, run `npm publish --tag beta`. This allows someone else to install this version of the package with `npm install xrpl@beta`.
* If this is a stable release, run `npm publish`.
* This will require entering `npm` login info.
9. Send an email to [xrpl-announce](https://groups.google.com/g/xrpl-announce).
## Mailing Lists
We have a low-traffic mailing list for announcements of new `xrpl.js` releases. (About 1 email every couple of weeks)
+ [Subscribe to xrpl-announce](https://groups.google.com/g/xrpl-announce)
If you're using the XRP Ledger in production, you should run a [rippled server](https://github.com/ripple/rippled) and subscribe to the ripple-server mailing list as well.
+ [Subscribe to ripple-server](https://groups.google.com/g/ripple-server)

1519
HISTORY.md

File diff suppressed because it is too large Load Diff

130
README.md
View File

@@ -1,81 +1,56 @@
# xrpl.js
# ripple-lib (RippleAPI)
A JavaScript/TypeScript library for interacting with the XRP Ledger
A JavaScript/TypeScript API for interacting with the XRP Ledger
[![NPM](https://nodei.co/npm/xrpl.png)](https://www.npmjs.org/package/xrpl)
![npm bundle size](https://img.shields.io/bundlephobia/min/xrpl)
[![NPM](https://nodei.co/npm/ripple-lib.png)](https://www.npmjs.org/package/ripple-lib)
This is the recommended library for integrating a JavaScript/TypeScript app with the XRP Ledger, especially if you intend to use advanced functionality such as IOUs, payment paths, the decentralized exchange, account settings, payment channels, escrows, multi-signing, and more.
## [➡️ Reference Documentation](http://js.xrpl.org)
## [➡️ Reference Documentation](https://xrpl.org/rippleapi-reference.html)
See the full reference documentation for all classes, methods, and utilities.
See the full reference documentation on the XRP Ledger Dev Portal.
## [➡️ Applications and Projects](https://github.com/XRPLF/xrpl.js/blob/master/APPLICATIONS.md)
## [➡️ Applications and Projects](APPLICATIONS.md)
What is `xrpl.js` used for? The applications on the list linked above use `xrpl.js`. Open a PR to add your app or project to the list!
What is ripple-lib used for? The applications on the list linked above use `ripple-lib`. Open a PR to add your app or project to the list!
### Features
+ Works in Node.js and in web browsers
+ Helpers for creating requests and parsing responses for the [XRP Ledger APIs](https://xrpl.org/rippled-api.html)
+ Connect to a `rippled` server from Node.js or a web browser
+ Helpers for creating requests and parsing responses for the [rippled API](https://developers.ripple.com/rippled-api.html)
+ Listen to events on the XRP Ledger (transactions, ledger, validations, etc.)
+ Sign and submit transactions to the XRP Ledger
+ Type definitions for TypeScript
### Requirements
+ **[Node.js v14](https://nodejs.org/)** is recommended. We also support v12 and v16. Other versions may work but are not frequently tested.
+ **[Node.js v14](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`.
## Getting Started
In an existing project (with `package.json`), install `xrpl.js`:
See also: [RippleAPI Beginners Guide](https://xrpl.org/get-started-with-rippleapi-for-javascript.html)
In an existing project (with `package.json`), install `ripple-lib`:
```
$ npm install --save xrpl
$ yarn add ripple-lib
```
Or with `yarn`:
Then see the [documentation](#documentation).
```
$ yarn add xrpl
```
### Using ripple-lib with React Native
Example usage:
If you want to use `ripple-lib` with React Native you will need to have some of the NodeJS modules available. To help with this you can use a module like [rn-nodeify](https://github.com/tradle/rn-nodeify).
```js
const xrpl = require("xrpl")
async function main() {
const client = new xrpl.Client("wss://s.altnet.rippletest.net:51233")
await client.connect()
const response = await client.request({
"command": "account_info",
"account": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
"ledger_index": "validated"
})
console.log(response)
client.disconnect()
}
main()
```
For more examples, see the [documentation](#documentation).
### Using xrpl.js with React Native
If you want to use `xrpl.js` with React Native you will need to install shims for core NodeJS modules. To help with this you can use a module like [rn-nodeify](https://github.com/tradle/rn-nodeify).
1. Install dependencies (you can use `yarn` as well):
1. Install dependencies (you can use `npm` as well):
```shell
npm install react-native-crypto
npm install xrpl
yarn add react-native-crypto
yarn add ripple-lib
# install peer deps
npm install react-native-randombytes
yarn add react-native-randombytes
# install latest rn-nodeify
npm install rn-nodeify@latest --dev
yarn add rn-nodeify@latest --dev
```
2. After that, run the following command:
@@ -104,15 +79,15 @@ If you want to use `xrpl.js` with React Native you will need to install shims fo
...
```
### Using xrpl.js with Deno
### Using ripple-lib with Deno
Until official support for [Deno](https://deno.land) is added, you can use the following work-around to use `xrpl.js` with Deno:
Until official support for [Deno](https://deno.land) is added, you can use the following work-around to use `ripple-lib` with Deno:
```javascript
import xrpl from 'https://dev.jspm.io/npm:xrpl';
import ripple from 'https://dev.jspm.io/npm:ripple-lib';
(async () => {
const api = new (xrpl as any).Client('wss://s.altnet.rippletest.net:51233');
const api = new (ripple as any).RippleAPI({ server: 'wss://s.altnet.rippletest.net:51233' });
const address = 'rH8NxV12EuV...khfJ5uw9kT';
api.connect().then(() => {
@@ -125,22 +100,57 @@ import xrpl from 'https://dev.jspm.io/npm:xrpl';
## Documentation
+ [Get Started in Node.js](https://xrpl.org/get-started-using-node-js.html)
+ [Full Reference Documentation](https://js.xrpl.org)
+ [Code Samples](https://github.com/XRPLF/xrpl.js/tree/develop/packages/xrpl/snippets/src)
+ [RippleAPI Beginners Guide](https://xrpl.org/get-started-with-rippleapi-for-javascript.html)
+ [RippleAPI Full Reference Documentation](https://xrpl.org/rippleapi-reference.html) ([in this repo](https://github.com/ripple/ripple-lib/blob/develop/docs/index.md))
+ [Code Samples](https://github.com/ripple/ripple-lib/tree/develop/docs/samples)
### Mailing Lists
We have a low-traffic mailing list for announcements of new `xrpl.js` releases. (About 1 email per week)
We have a low-traffic mailing list for announcements of new ripple-lib releases. (About 1 email per week)
+ [Subscribe to xrpl-announce](https://groups.google.com/g/xrpl-announce)
+ [Subscribe to ripple-lib-announce](https://groups.google.com/forum/#!forum/ripple-lib-announce)
If you're using the XRP Ledger in production, you should run a [rippled server](https://github.com/ripple/rippled) and subscribe to the ripple-server mailing list as well.
+ [Subscribe to ripple-server](https://groups.google.com/g/ripple-server)
+ [Subscribe to ripple-server](https://groups.google.com/forum/#!forum/ripple-server)
## Development
To build the library for Node.js and the browser:
```
$ yarn build
```
The TypeScript compiler will [output](./tsconfig.json#L7) the resulting JS files in `./dist/npm/`.
webpack will output the resulting JS files in `./build/`.
For details, see the `scripts` in `package.json`.
## Running Tests
### Unit Tests
1. Clone the repository
2. `cd` into the repository and install dependencies with `yarn install`
3. `yarn test`
### Linting
Run `yarn lint` to lint the code with `eslint`.
## Generating Documentation
Do not edit `./docs/index.md` directly because it is a generated file.
Instead, edit the appropriate `.md.ejs` files in `./docs/src/`.
If you make changes to the JSON schemas, fixtures, or documentation sources, update the documentation by running `yarn run docgen`.
## More Information
+ [xrpl-announce mailing list](https://groups.google.com/g/xrpl-announce) - subscribe for release announcements
+ [xrpl.js API Reference](https://js.xrpl.org)
+ [XRP Ledger Dev Portal](https://xrpl.org)
+ [ripple-lib-announce mailing list](https://groups.google.com/forum/#!forum/ripple-lib-announce) - subscribe for release announcements
+ [RippleAPI Reference](https://xrpl.org/rippleapi-reference.html) - XRP Ledger Dev Portal
+ [XRP Ledger Dev Portal](https://xrpl.org/)
[![Build Status](https://travis-ci.org/ripple/ripple-lib.svg?branch=master)](https://travis-ci.org/ripple/ripple-lib)

View File

@@ -2,11 +2,10 @@
## Supported Versions
This table shows which versions of xrpl.js are currently supported with security updates:
This table shows which versions of ripple-lib are currently supported with security updates:
| Version | Supported |
| ------- | ---------------------- |
| 2.x | :white_check_mark: Yes |
| 1.x | :white_check_mark: Yes |
| 0.x | :x: No |

18
circle.yml Normal file
View File

@@ -0,0 +1,18 @@
machine:
node:
version: 6.11.3
hosts:
testripple.circleci.com: 127.0.0.1
dependencies:
pre:
- wget https://s3-us-west-2.amazonaws.com/ripple-debs/rippled_0.30.1-b11-1.deb
- sudo dpkg -i rippled_0.30.1-b11-1.deb
test:
pre:
- rippled -a --start --conf "$HOME/$CIRCLE_PROJECT_REPONAME/test/integration/rippled.cfg":
background: true
override:
- scripts/ci.sh "$CIRCLE_NODE_INDEX" "$CIRCLE_NODE_TOTAL":
parallel: true
post:
- killall /usr/bin/rippled

6540
docs/index.md Normal file

File diff suppressed because it is too large Load Diff

5
docs/samples/README.md Normal file
View File

@@ -0,0 +1,5 @@
Usage:
babel-node balances.js
babel-node cancelall.js (requires setting address and secret in source file first)
babel-node payment.js (requires setting address and secret in source file first)
babel-node ticket.js (requires setting address and secret in source file first)

12
docs/samples/balances.js Normal file
View File

@@ -0,0 +1,12 @@
'use strict';
const RippleAPI = require('../../src').RippleAPI; // require('ripple-lib')
const api = new RippleAPI({server: 'wss://s1.ripple.com:443'});
const address = 'r3kmLJN5D28dHuH8vZNUZpMC43pEHpaocV';
api.connect().then(() => {
api.getBalances(address).then(balances => {
console.log(JSON.stringify(balances, null, 2));
process.exit();
});
});

38
docs/samples/cancelall.js Normal file
View File

@@ -0,0 +1,38 @@
'use strict';
const RippleAPI = require('../../dist/npm').RippleAPI; // require('ripple-lib')
const address = 'rLDYrujdKUfVx28T9vRDAbyJ7G2WVXKo4K';
const secret = '';
const api = new RippleAPI({server: 'wss://s1.ripple.com:443'});
const instructions = {maxLedgerVersionOffset: 5};
function fail(message) {
console.error(message);
process.exit(1);
}
function cancelOrder(orderSequence) {
console.log('Cancelling order: ' + orderSequence.toString());
return api.prepareOrderCancellation(address, {orderSequence}, instructions)
.then(prepared => {
const signing = api.sign(prepared.txJSON, secret);
return api.submit(signing.signedTransaction);
});
}
function cancelAllOrders(orderSequences) {
if (orderSequences.length === 0) {
return Promise.resolve();
}
const orderSequence = orderSequences.pop();
return cancelOrder(orderSequence).then(() => cancelAllOrders(orderSequences));
}
api.connect().then(() => {
console.log('Connected...');
return api.getOrders(address).then(orders => {
const orderSequences = orders.map(order => order.properties.sequence);
return cancelAllOrders(orderSequences);
}).then(() => process.exit(0));
}).catch(fail);

45
docs/samples/payment.js Normal file
View File

@@ -0,0 +1,45 @@
'use strict';
const RippleAPI = require('../../src').RippleAPI; // require('ripple-lib')
const address = 'INSERT ADDRESS HERE';
const secret = 'INSERT SECRET HERE';
const api = new RippleAPI({server: 'wss://s1.ripple.com:443'});
const instructions = {maxLedgerVersionOffset: 5};
const payment = {
source: {
address: address,
maxAmount: {
value: '0.01',
currency: 'XRP'
}
},
destination: {
address: 'rKmBGxocj9Abgy25J51Mk1iqFzW9aVF9Tc',
amount: {
value: '0.01',
currency: 'XRP'
}
}
};
function quit(message) {
console.log(message);
process.exit(0);
}
function fail(message) {
console.error(message);
process.exit(1);
}
api.connect().then(() => {
console.log('Connected...');
return api.preparePayment(address, payment, instructions).then(prepared => {
console.log('Payment transaction prepared...');
const {signedTransaction} = api.sign(prepared.txJSON, secret);
console.log('Payment transaction signed...');
api.submit(signedTransaction).then(quit, fail);
});
}).catch(fail);

31
docs/samples/ticket.js Normal file
View File

@@ -0,0 +1,31 @@
'use strict';
const RippleAPI = require('../../src').RippleAPI; // require('ripple-lib')
const address = 'INSERT ADDRESS HERE';
const secret = 'INSERT SECRET HERE';
const api = new RippleAPI({server: 'wss://s1.ripple.com:443'});
const instructions = {
maxLedgerVersionOffset: 5
};
const numberOfTickets = 1;
function quit(message) {
console.log(message);
process.exit(0);
}
function fail(message) {
console.error(message);
process.exit(1);
}
api.connect().then(() => {
console.log('Connected...');
return api.prepareTicketCreate(address, numberOfTickets, instructions).then(prepared => {
console.log('Ticket transaction prepared...');
const {signedTransaction} = api.sign(prepared.txJSON, secret);
console.log('Ticket transaction signed...');
api.submit(signedTransaction).then(quit, fail);
});
}).catch(fail);

View File

@@ -0,0 +1,67 @@
# Basic Types
## Address
```json
"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59"
```
```json
"X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ"
```
An *address* refers to a specific XRP Ledger account. It is a base-58 encoding of a hash of the account's public key. There are two kinds of addresses in common use:
### Classic Address
A *classic address* encodes a hash of the account's public key and a checksum. It has no other data. This kind of address always starts with the lowercase letter `r`.
### X-address
An *X-address* encodes a hash of the account's public key, a tag, and a checksum. This kind of address starts with the uppercase letter `X` if it is intended for use on the production XRP Ledger (mainnet). It starts with the uppercase letter `T` if it is intended for use on a test network such as Testnet or Devnet.
## Account Sequence Number
Every XRP Ledger account has a *sequence number* that is used to keep transactions in order. Every transaction must have a sequence or a ticketSequence number. A transaction can only be executed if it has the next sequence number in order, of the account sending it, or uses a previously generated ticketSequence number. This prevents one transaction from executing twice and transactions executing out of order. The sequence number starts at `1` and increments for each transaction that the account makes.
## Currency
Currencies are represented as either 3-character currency codes or 40-character uppercase hexadecimal strings. We recommend using uppercase [ISO 4217 Currency Codes](http://www.xe.com/iso4217.php) only. The string "XRP" is disallowed on trustlines because it is reserved for the XRP Ledger's native currency. The following characters are permitted: all uppercase and lowercase letters, digits, as well as the symbols `?`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `<`, `>`, `(`, `)`, `{`, `}`, `[`, `]`, and `|`.
## Value
A *value* is a quantity of a currency represented as a decimal string. Be careful: JavaScript's native number format does not have sufficient precision to represent all values. XRP has different precision from other currencies.
**XRP** has 6 significant digits past the decimal point. In other words, XRP cannot be divided into positive values smaller than `0.000001` (1e-6). This smallest unit is called a "drop". XRP has a maximum value of `100000000000` (1e11). Some RippleAPI methods accept XRP to maintain compatibility with older versions of the API. For consistency with the `rippled` APIs, we recommend formally specifying XRP values in *drops* in all API requests, and converting them to XRP for display. This is like Bitcoin's *satoshis* and Ethereum's *wei*. 1 XRP = 1,000,000 drops.
**Non-XRP values** have 16 decimal digits of precision, with a maximum value of `9999999999999999e80`. The smallest positive non-XRP value is `1e-81`.
## Amount
Example 100.00 USD amount:
```json
{
"currency": "USD",
"counterparty": "rMH4UxPrbuMa1spCBR98hLLyNJp4d8p4tM",
"value": "100"
}
```
Example 3.0 XRP amount, in drops:
```json
{
"currency": "drops",
"value": "3000000"
}
```
(Requires `ripple-lib` version 1.0.0 or higher.)
An *amount* is an object specifying a currency, a quantity of that currency, and the counterparty (issuer) on the trustline that holds the value. For XRP, there is no counterparty.
A *lax amount* allows the counterparty to be omitted for all currencies. If the counterparty is not specified in an amount within a transaction specification, then any counterparty may be used for that amount.
A *lax lax amount* allows either or both the counterparty and value to be omitted.
A *balance* is an amount than can have a negative value.
<%- renderSchema('objects/amountbase.json') %>

View File

@@ -0,0 +1,60 @@
## Boilerplate
Use the following [boilerplate code](https://en.wikipedia.org/wiki/Boilerplate_code) to wrap your custom code using RippleAPI.
```javascript
const RippleAPI = require('ripple-lib').RippleAPI;
const api = new RippleAPI({
server: 'wss://xrplcluster.com' // Public cluster
});
api.on('error', (errorCode, errorMessage) => {
console.log(errorCode + ': ' + errorMessage);
});
api.on('connected', () => {
console.log('connected');
});
api.on('disconnected', (code) => {
// code - [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) sent by the server
// the code is 1000 for a normal closure
console.log('disconnected, code:', code);
});
api.connect().then(() => {
/* insert code here */
}).then(() => {
return api.disconnect();
}).catch(console.error);
```
[Node.js v14](https://nodejs.org/) is recommended. Other versions may work but are not frequently tested.
<aside class="notice">
All the code snippets in this documentation assume that you have surrounded them with this boilerplate.
</aside>
<aside class="notice">
If you omit the "catch" section, errors may not be visible.
</aside>
<aside class="notice">
The API emits an "error" event whenever an error occurs that cannot be associated with a specific request. If there is no listener registered for this event, the API throws an exception whenever the event is emitted.
</aside>
### Parameters
The RippleAPI constructor optionally takes one argument, an object with the following options:
<%- renderSchema('input/api-options.json') %>
If you omit the `server` parameter, RippleAPI operates [offline](#offline-functionality).
### Installation ###
1. Install [Node.js](https://nodejs.org) and [Yarn](https://yarnpkg.com/en/docs/install). Most Linux distros have a package for Node.js; check that it's the version you want.
2. Use yarn to install RippleAPI:
`yarn add ripple-lib`
After you have installed ripple-lib, you can create scripts using the [boilerplate](#boilerplate) and run them using the Node.js executable, typically named `node`:
`node script.js`

24
docs/src/combine.md.ejs Normal file
View File

@@ -0,0 +1,24 @@
## combine
`combine(signedTransactions: Array<string>): {signedTransaction: string, id: string}`
Combines signed transactions from multiple accounts for a multisignature transaction into a form that can be [submitted](#submit).
### Parameters
<%- renderSchema("input/combine.json") %>
### Return Value
This method returns an object with the following structure:
<%- renderSchema("output/sign.json") %>
### Example
```javascript
const signedTransactions = <%- importFile('test/fixtures/requests/combine.json') %>;
return api.combine(signedTransactions);
```
<%- renderFixture("responses/combine.json") %>

View File

@@ -0,0 +1,28 @@
## computeLedgerHash
`computeLedgerHash(ledger: object): string`
Compute the hash of a ledger.
### Parameters
<aside class="notice">
The parameter to this method has the same structure as the return value of getLedger.
</aside>
<%- renderSchema('input/compute-ledger-hash.json') %>
### Return Value
This method returns an uppercase hexadecimal string representing the hash of the ledger.
### Example
```javascript
const ledger = <%- importFile('test/fixtures/requests/compute-ledger-hash.json') %>;
return api.computeLedgerHash(ledger);
```
```json
"F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349"
```

17
docs/src/connect.md.ejs Normal file
View File

@@ -0,0 +1,17 @@
## connect
`connect(): Promise<void>`
Tells the RippleAPI instance to connect to its rippled server.
### Parameters
This method has no parameters.
### Return Value
This method returns a promise that resolves with a void value when a connection is established.
### Example
See [Boilerplate](#boilerplate) for code sample.

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

@@ -0,0 +1,17 @@
## disconnect
`disconnect(): Promise<void>`
Tells the RippleAPI instance to disconnect from its rippled server.
### Parameters
This method has no parameters.
### Return Value
This method returns a promise that resolves with a void value when a connection is destroyed.
### Example
See [Boilerplate](#boilerplate) for code sample

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

@@ -0,0 +1,81 @@
# API Events
## ledger
This event is emitted whenever a new ledger version is validated on the connected server.
### Return Value
<%- renderSchema('output/ledger-event.json') %>
### Example
```javascript
api.on('ledger', ledger => {
console.log(JSON.stringify(ledger, null, 2));
});
```
<%- renderFixture('responses/ledger-event.json') %>
## error
This event is emitted when there is an error on the connection to the server that cannot be associated to a specific request.
### Return Value
The first parameter is a string indicating the error type:
* `badMessage` - rippled returned a malformed message
* `websocket` - the websocket library emitted an error
* one of the error codes found in the [`rippled` Universal Errors](https://xrpl.org/error-formatting.html#universal-errors).
The second parameter is a message explaining the error.
The third parameter is:
* the message that caused the error for `badMessage`
* the error object emitted for `websocket`
* the parsed response for rippled errors
### Example
```javascript
api.on('error', (errorCode, errorMessage, data) => {
console.log(errorCode + ': ' + errorMessage);
});
```
```
tooBusy: The server is too busy to help you now.
```
## connected
This event is emitted after connection successfully opened.
### Example
```javascript
api.on('connected', () => {
console.log('Connection is open now.');
});
```
## disconnected
This event is emitted when connection is closed.
### Return Value
The only parameter is a number containing the [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) send by the server.
### Example
```javascript
api.on('disconnected', (code) => {
if (code !== 1000) {
console.log('Connection is closed due to error.');
} else {
console.log('Connection is closed normally.');
}
});
```

View File

@@ -0,0 +1,254 @@
## formatBidsAndAsks
`formatBidsAndAsks(orderbookInfo: {base: Issue, counter: Issue}, offers: BookOffer[]): orderbook`
Returns formatted bids and asks, which make up an orderbook.
This is a static method on the `RippleAPI` class.
### Parameters
This method takes two parameters.
1. An `OrderbookInfo` object: `{ base: Issue, counter: Issue }`.
2. An array of `BookOffer` objects.
### Return Value
This method returns an object with two properties: `bids` and `asks`, each of which is an array of bids (buy orders) or asks (sell orders), respectively. Both `bids` and `asks` are formatted the same way.
Object structure:
<%- renderSchema('output/get-orderbook.json') %>
**Raw order data:** The response includes a `data` property containing the raw order data. This may include `owner_funds`, `Flags`, and other fields.
For details, see the `rippled` [book_offers method](https://xrpl.org/book_offers.html).
### Example
```javascript
const orderbookInfo = {
"base": {
"currency": "USD",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"counter": {
"currency": "BTC",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
};
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return Promise.all(
[
this.api.request('book_offers', {
taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base),
taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter),
ledger_index: 'validated',
limit: 20,
taker: address
}),
this.api.request('book_offers', {
taker_gets: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter),
taker_pays: RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base),
ledger_index: 'validated',
limit: 20,
taker: address
})
]
).then((directOfferResults, reverseOfferResults) => {
const directOffers = (directOfferResults ? directOfferResults : []).reduce((acc, res) => acc.concat(res.offers), [])
const reverseOffers = (reverseOfferResults ? reverseOfferResults : []).reduce((acc, res) => acc.concat(res.offers), [])
const orderbook = RippleAPI.formatBidsAndAsks(orderbookInfo, [...directOffers, ...reverseOffers]);
console.log(JSON.stringify(orderbook, null, 2));
});
```
```
{
"bids": [
{
"specification": {
"direction": "buy",
"quantity": {
"currency": "USD",
"value": "0.71800168",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"totalPrice": {
"currency": "BTC",
"value": "0.00016708342",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
},
"properties": {
"maker": "rUKoQ1Zhn6c8EfPsaVa2Yx5NqaKN1JQSvq",
"sequence": 262660,
"makerExchangeRate": "4297.264683713081"
},
"data": {
"Account": "rUKoQ1Zhn6c8EfPsaVa2Yx5NqaKN1JQSvq",
"BookDirectory": "6EAB7C172DEFA430DBFAD120FDC373B5F5AF8B191649EC98580F4456E6FA8239",
"BookNode": "0000000000000000",
"Flags": 0,
"LedgerEntryType": "Offer",
"OwnerNode": "000000000000001D",
"PreviousTxnID": "16D75506C6317723FC03543130B5E0AAB13E8AD22514C1DB098BE05771C90447",
"PreviousTxnLgrSeq": 43127860,
"Sequence": 262660,
"TakerGets": {
"currency": "BTC",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.00016708342"
},
"TakerPays": {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.71800168"
},
"index": "DE877FB94EF892A4BCC58DB8CDE063D97AB5133201905DE6C8650B5DEA19E11B",
"owner_funds": "0.03358376764081196",
"quality": "4297.264683713081"
}
},
{
"specification": {
"direction": "buy",
"quantity": {
"currency": "USD",
"value": "1.6770875",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"totalPrice": {
"currency": "BTC",
"value": "0.00038681218",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
},
"properties": {
"maker": "rpmL45YbZWKgp8AH8EjBSknWo5c8dNuuBM",
"sequence": 231459,
"makerExchangeRate": "4335.663628792661"
},
"data": {
"Account": "rpmL45YbZWKgp8AH8EjBSknWo5c8dNuuBM",
"BookDirectory": "6EAB7C172DEFA430DBFAD120FDC373B5F5AF8B191649EC98580F67435A75B355",
"BookNode": "0000000000000000",
"Flags": 0,
"LedgerEntryType": "Offer",
"OwnerNode": "0000000000000001",
"PreviousTxnID": "F049EAFDDDA7B99970F77533743D95C9E12A16FE6C56215A0B09C32C4D23163F",
"PreviousTxnLgrSeq": 43127094,
"Sequence": 231459,
"TakerGets": {
"currency": "BTC",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.00038681218"
},
"TakerPays": {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "1.6770875"
},
"index": "3B314A51BD57601CA1509834DF9462037BF4B05AFCC1E1EFD334DB4E2D7B2AA6",
"owner_funds": "0.03906802968738533",
"quality": "4335.663628792661"
}
},
// ... trimmed for brevity ...
],
"asks": [
{
"specification": {
"direction": "sell",
"quantity": {
"currency": "USD",
"value": "0.71085738",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"totalPrice": {
"currency": "BTC",
"value": "0.00016876265",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
},
"properties": {
"maker": "rUKoQ1Zhn6c8EfPsaVa2Yx5NqaKN1JQSvq",
"sequence": 262664,
"makerExchangeRate": "0.0002374071856720401"
},
"data": {
"Account": "rUKoQ1Zhn6c8EfPsaVa2Yx5NqaKN1JQSvq",
"BookDirectory": "20294C923E80A51B487EB9547B3835FD483748B170D2D0A451086F34ADB0EA11",
"BookNode": "0000000000000000",
"Flags": 0,
"LedgerEntryType": "Offer",
"OwnerNode": "000000000000001D",
"PreviousTxnID": "54CE0B2783AF973718FAFA35E864A3C172BE488EBBB6F2852611C6DAC8893BDF",
"PreviousTxnLgrSeq": 43127875,
"Sequence": 262664,
"TakerGets": {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.71085738"
},
"TakerPays": {
"currency": "BTC",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.00016876265"
},
"index": "2D4ED103D6B3FEFA21BC385C53B63359F5678E5AA5429DDE6E1D8FE8B41CD6A8",
"owner_funds": "142.8821425048244",
"quality": "0.0002374071856720401"
}
},
{
"specification": {
"direction": "sell",
"quantity": {
"currency": "USD",
"value": "1.6438778",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"totalPrice": {
"currency": "BTC",
"value": "0.00039462656",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
},
"properties": {
"maker": "rpmL45YbZWKgp8AH8EjBSknWo5c8dNuuBM",
"sequence": 231483,
"makerExchangeRate": "0.0002400583303698121"
},
"data": {
"Account": "rpmL45YbZWKgp8AH8EjBSknWo5c8dNuuBM",
"BookDirectory": "20294C923E80A51B487EB9547B3835FD483748B170D2D0A4510887515B1216C9",
"BookNode": "0000000000000000",
"Flags": 0,
"LedgerEntryType": "Offer",
"OwnerNode": "0000000000000001",
"PreviousTxnID": "6FA370F52C45F6149482156FF7B4226713AECE991FB7D053F74172CB0B8F24E9",
"PreviousTxnLgrSeq": 43127158,
"Sequence": 231483,
"TakerGets": {
"currency": "USD",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "1.6438778"
},
"TakerPays": {
"currency": "BTC",
"issuer": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B",
"value": "0.00039462656"
},
"index": "735F9661AD006BA0776859BE371D445555FC0815604603AC056469C16AC84AE3",
"owner_funds": "166.0316626329364",
"quality": "0.0002400583303698121"
}
},
// ... trimmed for brevity ...
]
}
```

View File

@@ -0,0 +1,25 @@
## generateAddress
`generateAddress(options?: object): {address: string, secret: string}`
Deprecated: This method returns a classic address. If you do not need the classic address, use `generateXAddress` instead.
Generate a new XRP Ledger address and corresponding secret.
### Parameters
<%- renderSchema('input/generate-address.json') %>
### Return Value
This method returns an object with the following structure:
<%- renderSchema('output/generate-address.json') %>
### Example
```javascript
return api.generateAddress();
```
<%- renderFixture('responses/generate-address.json') %>

View File

@@ -0,0 +1,23 @@
## generateXAddress
`generateXAddress(options?: object): {address: string, secret: string}`
Generate a new XRP Ledger address and corresponding secret.
### Parameters
<%- renderSchema('input/generate-x-address.json') %>
### Return Value
This method returns an object with the following structure:
<%- renderSchema('output/generate-x-address.json') %>
### Example
```javascript
return api.generateXAddress();
```
<%- renderFixture('responses/generate-x-address.json') %>

View File

@@ -0,0 +1,25 @@
## getAccountInfo
`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).
### Parameters
<%- renderSchema('input/get-account-info.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-account-info.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getAccountInfo(address).then(info =>
{/* ... */});
```
<%- renderFixture('responses/get-account-info.json') %>

View File

@@ -0,0 +1,34 @@
## getAccountObjects
`getAccountObjects(address: string, options: object): Promise<AccountObjectsResponse>`
Returns objects owned by an account. For an account's trust lines and balances, see `getTrustlines` and `getBalances`.
### Parameters
<%- renderSchema('input/get-account-objects.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-account-objects.json') %>
The types of objects that may be returned include:
* `Offer` objects for orders that are currently live, unfunded, or expired but not yet removed.
* `RippleState` objects for trust lines where this account's side is not in the default state.
* A `SignerList` object if the account has multi-signing enabled.
* `Escrow` objects for held payments that have not yet been executed or canceled.
* `PayChannel` objects for open payment channels.
* `Check` objects for pending checks.
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getAccountObjects(address: address).then(objects =>
{/* ... */});
```
<%- renderFixture('responses/get-account-objects.json') %>

View File

@@ -0,0 +1,25 @@
## getBalanceSheet
`getBalanceSheet(address: string, options: object): Promise<object>`
Returns aggregate balances by currency plus a breakdown of assets and obligations for a specified account.
### Parameters
<%- renderSchema('input/get-balance-sheet.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-balance-sheet.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getBalanceSheet(address).then(balanceSheet =>
{/* ... */});
```
<%- renderFixture('responses/get-balance-sheet.json') %>

View File

@@ -0,0 +1,25 @@
## getBalances
`getBalances(address: string, options: object): Promise<Array<object>>`
Returns balances for a specified account.
### Parameters
<%- renderSchema('input/get-balances.json') %>
### Return Value
This method returns a promise that resolves with an array of objects with the following structure:
<%- renderSchema('output/get-balances.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getBalances(address).then(balances =>
{/* ... */});
```
<%- renderFixture('responses/get-balances.json') %>

25
docs/src/getFee.md.ejs Normal file
View File

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

24
docs/src/getLedger.md.ejs Normal file
View File

@@ -0,0 +1,24 @@
## getLedger
`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.
### Parameters
<%- renderSchema('input/get-ledger.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-ledger.json') %>
### Example
```javascript
return api.getLedger()
.then(ledger => {/* ... */});
```
<%- renderFixture('responses/get-ledger.json') %>

View File

@@ -0,0 +1,26 @@
## getLedgerVersion
`getLedgerVersion(): Promise<number>`
Returns the most recent validated ledger version number known to the connected server.
### Parameters
This method has no parameters.
### Return Value
This method returns a promise that resolves with a positive integer representing the most recent validated ledger version number known to the connected server.
### Example
```javascript
return api.getLedgerVersion().then(ledgerVersion => {
/* ... */
});
```
```json
16869039
```

View File

@@ -0,0 +1,34 @@
## getOrderbook
`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.
**Breaking change:** In ripple-lib 1.1.0 and earlier, orders returned by this method were not sorted correctly. Orders are now sorted correctly, from best to worst.
**See also:** An alternative way to get orderbooks is with `request` and [`formatBidsAndAsks`](#formatbidsandasks).
### Parameters
<%- renderSchema('input/get-orderbook.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure Both `bids` and `asks` have the same format:
<%- renderSchema('output/get-orderbook.json') %>
**Raw order data:** The response includes a `data` property containing the raw order data. This may include `owner_funds`, `Flags`, and other fields.
For details, see the `rippled` [book_offers method](https://xrpl.org/book_offers.html).
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const orderbook = <%- importFile('test/fixtures/requests/get-orderbook.json') %>;
return api.getOrderbook(address, orderbook)
.then(orderbook => {/* ... */});
```
<%- renderFixture('responses/get-orderbook.json') %>

25
docs/src/getOrders.md.ejs Normal file
View File

@@ -0,0 +1,25 @@
## getOrders
`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.
### Parameters
<%- renderSchema('input/get-orders.json') %>
### Return Value
This method returns a promise that resolves with an array of objects with the following structure:
<%- renderSchema('output/get-orders.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getOrders(address).then(orders =>
{/* ... */});
```
<%- renderFixture('responses/get-orders.json') %>

25
docs/src/getPaths.md.ejs Normal file
View File

@@ -0,0 +1,25 @@
## getPaths
`getPaths(pathfind: object): Promise<Array<object>>`
Finds paths to send a payment. Paths are options for how to route a payment.
### Parameters
<%- renderSchema("input/get-paths.json") %>
### Return Value
This method returns a promise that resolves with an array of objects with the following structure:
<%- renderSchema("output/get-paths.json") %>
### Example
```javascript
const pathfind = <%- importFile('test/fixtures/requests/getpaths/normal.json') %>;
return api.getPaths(pathfind)
.then(paths => {/* ... */});
```
<%- renderFixture("responses/get-paths.json") %>

View File

@@ -0,0 +1,26 @@
## getPaymentChannel
`getPaymentChannel(id: string): Promise<object>`
Returns specified payment channel.
### Parameters
<%- renderSchema('input/get-payment-channel.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-payment-channel.json') %>
### Example
```javascript
const channelId =
'E30E709CF009A1F26E0E5C48F7AA1BFB79393764F15FB108BDC6E06D3CBD8415';
return api.getPaymentChannel(channelId).then(channel =>
{/* ... */});
```
<%- renderFixture('responses/get-payment-channel.json') %>

View File

@@ -0,0 +1,23 @@
## getServerInfo
`getServerInfo(): Promise<object>`
Get status information about the server that the RippleAPI instance is connected to.
### Parameters
This method has no parameters.
### Return Value
This method returns a promise that resolves with an object with the following structure:
<%- renderSchema('output/get-server-info.json') %>
### Example
```javascript
return api.getServerInfo().then(info => {/* ... */});
```
<%- renderFixture('responses/get-server-info.json') %>

View File

@@ -0,0 +1,25 @@
## getSettings
`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).
### Parameters
<%- renderSchema('input/get-settings.json') %>
### Return Value
This method returns a promise that resolves with an array of objects with the following structure. All fields are optional, and are omitted if they are set to their default value.
<%- renderSchema('output/get-settings.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getSettings(address).then(settings =>
{/* ... */});
```
<%- renderFixture('responses/get-settings.json') %>

View File

@@ -0,0 +1,26 @@
## getTransaction
`getTransaction(id: string, options: object): Promise<object>`
Retrieves a transaction by its [Transaction ID](#transaction-id).
### Parameters
<%- renderSchema('input/get-transaction.json') %>
### Return Value
This method returns a promise that resolves with a transaction object containing the following fields.
<%- renderSchema('output/get-transaction.json') %>
### Example
```javascript
const id = '01CDEAA89BF99D97DFD47F79A0477E1DCC0989D39F70E8AACBFE68CC83BD1E94';
return api.getTransaction(id).then(transaction => {
/* ... */
});
```
<%- renderFixture('responses/get-transaction-payment.json') %>

View File

@@ -0,0 +1,24 @@
## getTransactions
`getTransactions(address: string, options: object): Promise<Array<object>>`
Retrieves historical transactions of an account.
### Parameters
<%- renderSchema('input/get-transactions.json') %>
### Return Value
This method returns a promise that resolves with an array of transaction object in the same format as [getTransaction](#gettransaction).
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getTransactions(address).then(transaction => {
/* ... */
});
```
<%- renderFixture('responses/get-transactions.json') %>

View File

@@ -0,0 +1,25 @@
## getTrustlines
`getTrustlines(address: string, options: object): Promise<Array<object>>`
Returns trustlines for a specified account.
### Parameters
<%- renderSchema("input/get-trustlines.json") %>
### Return Value
This method returns a promise that resolves with an array of objects with the following structure.
<%- renderSchema("output/get-trustlines.json") %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.getTrustlines(address).then(trustlines =>
{/* ... */});
```
<%- renderFixture("responses/get-trustlines.json") %>

View File

@@ -0,0 +1,27 @@
## hasNextPage
`hasNextPage(currentResponse): boolean`
Returns `true` when there are more pages available.
When there are more results than contained in the response, the response includes a `marker` field. You can use this convenience method, or check for `marker` yourself.
See [Markers and Pagination](https://xrpl.org/markers-and-pagination.html).
### Return Value
This method returns `true` if `currentResponse` includes a `marker`.
### Example
```javascript
return api.request('ledger_data', {
ledger_index: 'validated'
}).then(response => {
/* Do something useful with response */
if (api.hasNextPage(response)) {
/* There are more pages available */
}
}).catch(console.error);
```

70
docs/src/index.md.ejs Normal file
View File

@@ -0,0 +1,70 @@
<%- include('introduction.md.ejs') %>
<%- include('boilerplate.md.ejs') %>
<%- include('offline.md.ejs') %>
<%- include('basictypes.md.ejs') %>
<%- include('transactions.md.ejs') %>
<%- include('specifications.md.ejs') %>
<%- include('rippledAPIs.md.ejs') %>
<%- include('request.md.ejs') %>
<%- include('hasNextPage.md.ejs') %>
<%- include('requestNextPage.md.ejs') %>
<%- include('staticMethods.md.ejs') %>
<%- include('renameCounterpartyToIssuer.md.ejs') %>
<%- include('formatBidsAndAsks.md.ejs') %>
<%- include('methods.md.ejs') %>
<%- include('connect.md.ejs') %>
<%- include('disconnect.md.ejs') %>
<%- include('isConnected.md.ejs') %>
<%- include('getServerInfo.md.ejs') %>
<%- include('getFee.md.ejs') %>
<%- include('getLedgerVersion.md.ejs') %>
<%- include('getTransaction.md.ejs') %>
<%- include('getTransactions.md.ejs') %>
<%- include('getTrustlines.md.ejs') %>
<%- include('getBalances.md.ejs') %>
<%- include('getBalanceSheet.md.ejs') %>
<%- include('getPaths.md.ejs') %>
<%- include('getOrders.md.ejs') %>
<%- include('getOrderbook.md.ejs') %>
<%- include('getSettings.md.ejs') %>
<%- include('getAccountInfo.md.ejs') %>
<%- 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') %>
<%- include('prepareOrderCancellation.md.ejs') %>
<%- include('prepareSettings.md.ejs') %>
<%- include('prepareEscrowCreation.md.ejs') %>
<%- include('prepareEscrowCancellation.md.ejs') %>
<%- include('prepareEscrowExecution.md.ejs') %>
<%- include('preparePaymentChannelCreate.md.ejs') %>
<%- include('preparePaymentChannelClaim.md.ejs') %>
<%- include('preparePaymentChannelFund.md.ejs') %>
<%- include('prepareCheckCreate.md.ejs') %>
<%- include('prepareCheckCancel.md.ejs') %>
<%- include('prepareCheckCash.md.ejs') %>
<%- include('prepareTicketCreate.md.ejs') %>
<%- include('sign.md.ejs') %>
<%- include('combine.md.ejs') %>
<%- include('submit.md.ejs') %>
<%- include('generateXAddress.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('rippleTimeToISO8601.md.ejs') %>
<%- include('txFlags.md.ejs') %>
<%- include('schemaValidator.md.ejs') %>
<%- include('events.md.ejs') %>

View File

@@ -0,0 +1,15 @@
# Introduction
RippleAPI (ripple-lib) is the official client library to the XRP Ledger. Currently, RippleAPI is only available in JavaScript/TypeScript.
Using RippleAPI, you can:
* [Query transactions from the XRP Ledger history](#gettransaction)
* [Sign](#sign) transactions securely without connecting to any server
* [Submit](#submit) transactions to the XRP Ledger, including [Payments](#payment), [Orders](#order), [Settings changes](#settings), and [other types](#transaction-types)
* [Generate a new XRP Ledger Address](#generateaddress)
* ... and [much more](#api-methods).
This page contains documentation for ripple-lib. To use ripple-lib with npm/yarn, begin with the [Getting Started](https://github.com/ripple/ripple-lib#getting-started) steps.
**What is ripple-lib used for?** Here's a [list of applications that use `ripple-lib`](https://github.com/ripple/ripple-lib/blob/develop/APPLICATIONS.md). Open a PR to add your app or project to the list!

View File

@@ -0,0 +1,23 @@
## isConnected
`isConnected(): boolean`
Checks if the RippleAPI instance is connected to its rippled server.
### Parameters
This method has no parameters.
### Return Value
This method returns `true` if connected and `false` if not connected.
### Example
```javascript
return api.isConnected();
```
```json
true
```

View File

@@ -0,0 +1,19 @@
## isValidAddress
`isValidAddress(address: string): boolean`
Checks if the specified string contains a valid address. X-addresses are considered valid with ripple-lib v1.4.0 and higher.
### 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
```

1
docs/src/methods.md.ejs Normal file
View File

@@ -0,0 +1 @@
# API Methods

27
docs/src/offline.md.ejs Normal file
View File

@@ -0,0 +1,27 @@
## Offline functionality
RippleAPI can also function without internet connectivity, so you can generate secrets and sign transactions from a secure, isolated machine.
To instantiate RippleAPI in offline mode, use the following code:
```javascript
const RippleAPI = require('ripple-lib').RippleAPI;
const api = new RippleAPI();
/* insert code here */
```
Methods that depend on the state of the XRP Ledger are unavailable in offline mode. To prepare transactions offline, you **must** specify the `fee`, `sequence`, and `maxLedgerVersion` parameters in the [transaction instructions](#transaction-instructions). You can use the following methods while offline:
* [preparePayment](#preparepayment)
* [prepareTrustline](#preparetrustline)
* [prepareOrder](#prepareorder)
* [prepareOrderCancellation](#prepareordercancellation)
* [prepareSettings](#preparesettings)
* [prepareEscrowCreation](#prepareescrowcreation)
* [prepareEscrowCancellation](#prepareescrowcancellation)
* [prepareEscrowExecution](#prepareescrowexecution)
* [sign](#sign)
* [generateAddress](#generateaddress)
* [generateXAddress](#generatexaddress)
* [computeLedgerHash](#computeledgerhash)

View File

@@ -0,0 +1,35 @@
## parseAccountFlags
`parseAccountFlags(Flags: number): object`
Parse an `AccountRoot` object's [`Flags`](https://xrpl.org/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

@@ -0,0 +1,30 @@
## prepareCheckCancel
`prepareCheckCancel(address: string, checkCancel: object, instructions: object): Promise<object>`
Prepare a Check cancellation transaction. This type of transaction cancels an unredeemed Check, removing it from the ledger without sending any money. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-check-cancel.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const checkCancel = <%- importFile('test/fixtures/requests/prepare-check-cancel.json') %>;
return api.prepareCheckCancel(address, checkCancel).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-check-cancel.json') %>

View File

@@ -0,0 +1,30 @@
## prepareCheckCash
`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 can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-check-cash.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const checkCash = <%- importFile('test/fixtures/requests/prepare-check-cash-amount.json') %>;
return api.prepareCheckCash(address, checkCash).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-check-cash-amount.json') %>

View File

@@ -0,0 +1,30 @@
## prepareCheckCreate
`prepareCheckCreate(address: string, checkCreate: object, instructions: object): Promise<object>`
Prepare a Check creation transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-check-create.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const checkCreate = <%- importFile('test/fixtures/requests/prepare-check-create.json') %>;
return api.prepareCheckCreate(address, checkCreate).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-check-create.json') %>

View File

@@ -0,0 +1,30 @@
## prepareEscrowCancellation
`prepareEscrowCancellation(address: string, escrowCancellation: object, instructions: object): Promise<object>`
Prepare an escrow cancellation transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-escrow-cancellation.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const escrowCancellation = <%- importFile('test/fixtures/requests/prepare-escrow-cancellation.json') %>;
return api.prepareEscrowCancellation(address, escrowCancellation).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-escrow-cancellation.json') %>

View File

@@ -0,0 +1,36 @@
## prepareEscrowCreation
`prepareEscrowCreation(address: string, escrowCreation: object, instructions: object): Promise<object>`
Prepare an escrow creation transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-escrow-creation.json') %>
This is a convenience method for generating the EscrowCreate JSON used by rippled, so the same restrictions apply.
Field mapping: `allowCancelAfter` is equivalent to rippled's `CancelAfter`; `allowExecuteAfter` is equivalent to `FinishAfter`. At the `allowCancelAfter` time, the escrow is considered expired. This means that the funds can only be returned to the sender. At the `allowExecuteAfter` time, the escrow is permitted to be released to the recipient (if the `condition` is fulfilled).
Note that `allowCancelAfter` must be chronologically later than `allowExecuteAfter`.
### Return Value
This method returns a promise that resolves with an object with the following structure:
<aside class="notice">
All "prepare*" methods have the same return type.
</aside>
<%- renderSchema('output/prepare.json') %>
### Example
```javascript
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const escrowCreation = <%- importFile('test/fixtures/requests/prepare-escrow-creation.json') %>;
return api.prepareEscrowCreation(address, escrowCreation).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-escrow-creation.json') %>

View File

@@ -0,0 +1,30 @@
## prepareEscrowExecution
`prepareEscrowExecution(address: string, escrowExecution: object, instructions: object): Promise<object>`
Prepare an escrow execution transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-escrow-execution.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const escrowExecution = <%- importFile('test/fixtures/requests/prepare-escrow-execution.json') %>;
return api.prepareEscrowExecution(address, escrowExecution).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-escrow-execution.json') %>

View File

@@ -0,0 +1,32 @@
## prepareOrder
`prepareOrder(address: string, order: object, instructions: object): Promise<object>`
Prepare an order transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-order.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
// Buy 10.10 USD (of the specified issuer) for 2.0 XRP (2000000 drops), fill or kill.
const order = <%- importFile('test/fixtures/requests/prepare-order.json') %>;
return api.prepareOrder(address, order)
.then(prepared => {/* ... */});
```
<%- renderFixture('responses/prepare-order.json') %>

View File

@@ -0,0 +1,30 @@
## prepareOrderCancellation
`prepareOrderCancellation(address: string, orderCancellation: object, instructions: object): Promise<object>`
Prepare an order cancellation transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema("input/prepare-order-cancellation.json") %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const orderCancellation = {orderSequence: 123};
return api.prepareOrderCancellation(address, orderCancellation)
.then(prepared => {/* ... */});
```
<%- renderFixture("responses/prepare-order-cancellation.json") %>

View File

@@ -0,0 +1,33 @@
## preparePayment
`preparePayment(address: string, payment: object, instructions: object): Promise<object>`
Prepare a payment transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema("input/prepare-payment.json") %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const payment = <%- importFile('test/fixtures/requests/prepare-payment.json') %>;
return api.preparePayment(address, payment).then(prepared => {
/* ... */
}).catch(error => {
/* ... as with all prepare* methods, use a Promise catch block to handle errors ... */
})
```
<%- renderFixture("responses/prepare-payment.json") %>

View File

@@ -0,0 +1,30 @@
## preparePaymentChannelClaim
`preparePaymentChannelClaim(address: string, paymentChannelClaim: object, instructions: object): Promise<object>`
Prepare a payment channel claim transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-payment-channel-claim.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const paymentChannelClaim = <%- importFile('test/fixtures/requests/prepare-payment-channel-claim.json') %>;
return api.preparePaymentChannelClaim(address, paymentChannelClaim).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-payment-channel-claim.json') %>

View File

@@ -0,0 +1,30 @@
## preparePaymentChannelCreate
`preparePaymentChannelCreate(address: string, paymentChannelCreate: object, instructions: object): Promise<object>`
Prepare a payment channel creation transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-payment-channel-create.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const paymentChannelCreate = <%- importFile('test/fixtures/requests/prepare-payment-channel-create.json') %>;
return api.preparePaymentChannelCreate(address, paymentChannelCreate).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-payment-channel-create.json') %>

View File

@@ -0,0 +1,30 @@
## preparePaymentChannelFund
`preparePaymentChannelFund(address: string, paymentChannelFund: object, instructions: object): Promise<object>`
Prepare a payment channel fund transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-payment-channel-fund.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const paymentChannelFund = <%- importFile('test/fixtures/requests/prepare-payment-channel-fund.json') %>;
return api.preparePaymentChannelFund(address, paymentChannelFund).then(prepared =>
{/* ... */});
```
<%- renderFixture('responses/prepare-payment-channel-fund.json') %>

View File

@@ -0,0 +1,30 @@
## prepareSettings
`prepareSettings(address: string, settings: object, instructions: object): Promise<object>`
Prepare a settings transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema('input/prepare-settings.json') %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const settings = <%- importFile('test/fixtures/requests/prepare-settings.json') %>;
return api.prepareSettings(address, settings)
.then(prepared => {/* ... */});
```
<%- renderFixture('requests/prepare-settings.json') %>

View File

@@ -0,0 +1,34 @@
## prepareTicketCreate
`prepareTicketCreate(address: string, ticketCount: number, instructions: object): Promise<object>`
Prepare a ticket transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
Ticket functionality requires the [TicketBatch amendment](https://github.com/ripple/xrpl-dev-portal/issues/898). As of 2020-11-24, this amendment is not activated on the Mainnet, Testnet, or Devnet.
### Parameters
<%- renderSchema("input/prepare-ticket-create.json") %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
return api.prepareTicketCreate(address, 2).then(prepared => {
/* ... */
}).catch(error => {
/* ... as with all prepare* methods, use a Promise catch block to handle errors ... */
})
```
<%- renderFixture("responses/prepare-ticket-create.json") %>

View File

@@ -0,0 +1,50 @@
## prepareTransaction
`prepareTransaction(transaction: object, instructions: object): Promise<object>`
Prepare a transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
This method works with any of [the transaction types supported by rippled](https://xrpl.org/transaction-types.html).
Notably, this is the preferred method for preparing `DepositPreauth` or `AccountDelete` transactions.
### Parameters
Name | Type | Description
---- | ---- | -----------
transaction | [Transaction](https://xrpl.org/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

@@ -0,0 +1,30 @@
## prepareTrustline
`prepareTrustline(address: string, trustline: object, instructions: object): Promise<object>`
Prepare a trustline transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
### Parameters
<%- renderSchema("input/prepare-trustline.json") %>
### 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
const address = 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59';
const trustline = <%- importFile('test/fixtures/requests/prepare-trustline.json') %>;
return api.prepareTrustline(address, trustline).then(prepared =>
{/* ... */});
```
<%- renderFixture("responses/prepare-trustline.json") %>

View File

@@ -0,0 +1,37 @@
## renameCounterpartyToIssuer
`renameCounterpartyToIssuer(issue: {currency: string, counterparty: address}): {currency: string, issuer: address}`
Returns an object with the `counterparty` field renamed to `issuer`. This is useful because RippleAPI generally uses the name `counterparty` while the rippled API generally uses the name `issuer`.
This is a static method on the `RippleAPI` class.
### Parameters
This method takes one parameter, an object with a `counterparty` field.
### Return Value
This method returns a new object based on the source object, but with `issuer` instead of `counterparty`.
### Example
```javascript
const orderbookInfo = {
"base": {
"currency": "USD",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
},
"counter": {
"currency": "BTC",
"counterparty": "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B"
}
};
console.log(RippleAPI.renameCounterpartyToIssuer(orderbookInfo.base))
console.log(RippleAPI.renameCounterpartyToIssuer(orderbookInfo.counter))
```
```
{ currency: 'USD', issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' }
{ currency: 'BTC', issuer: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B' }
```

27
docs/src/request.md.ejs Normal file
View File

@@ -0,0 +1,27 @@
## request
`request(command: string, options: object): Promise<object>`
Returns the response from invoking the specified command, with the specified options, on the connected rippled server.
Refer to [HTTP / WebSocket APIs](https://xrpl.org/rippled-api.html) for commands and options. All XRP amounts must be specified in drops. One drop is equal to 0.000001 XRP. See [Specifying Currency Amounts](https://xrpl.org/basic-data-types.html#specifying-currency-amounts).
Most commands return data for the `current` (in-progress, open) ledger by default. Do not rely on this. Always specify a ledger version in your request. In the example below, the 'validated' ledger is requested, which is the most recent ledger that has been validated by the whole network. See [Specifying Ledgers](https://xrpl.org/basic-data-types.html#specifying-ledgers).
### Return Value
This method returns a promise that resolves with the response from rippled.
### Example
```javascript
// Replace 'ledger' with your desired rippled command
return api.request('ledger', {
ledger_index: 'validated'
}).then(response => {
/* Do something useful with response */
console.log(JSON.stringify(response, null, 2))
}).catch(console.error);
```
<%- renderFixture('responses/ledger.json') %>

View File

@@ -0,0 +1,29 @@
## requestNextPage
`requestNextPage(command: string, params: object = {}, currentResponse: object): Promise<object>`
Requests the next page of data.
You can use this convenience method, or include `currentResponse.marker` in `params` yourself, when using `request`.
See [Markers and Pagination](https://xrpl.org/markers-and-pagination.html).
### Return Value
This method returns a promise that resolves with the next page of data from rippled.
If the response does not have a next page, the promise rejects with `new errors.NotFoundError('response does not have a next page')`.
### Example
```javascript
const command = 'ledger_data'
const params = {
ledger_index: 'validated'
}
return api.request(command, params).then(response => {
return api.requestNextPage(command, params, response)
}).then(response_page_2 => {
/* Do something useful with second page of response */
}).catch(console.error);
```

View File

@@ -0,0 +1,27 @@
## rippleTimeToISO8601
`rippleTimeToISO8601(rippleTime: number): string`
This method takes the number of seconds since the "Ripple Epoch" of January 1, 2000 (00:00 UTC) and returns a string representation of a date.
The Ripple Epoch is 946684800 seconds after the Unix Epoch.
This method is useful for interpreting timestamps returned by the rippled APIs. The rippled APIs represent time as an unsigned integer of the number of seconds since the Ripple Epoch.
### Parameters
`rippleTime`: A number of seconds since the Ripple Epoch.
### Return Value
A string representing a date and time, created by calling a `Date` object's `toISOString()` method.
### Example
```javascript
api.rippleTimeToISO8601(540659097);
```
```json
'2017-02-17T15:04:57.000Z'
```

View File

@@ -0,0 +1,71 @@
# rippled APIs
ripple-lib uses the XRP Ledger's [WebSocket API](https://xrpl.org/rippled-api.html) for online functionality. You can use ripple-lib to call these APIs directly. Use the `request()`, `hasNextPage()`, and `requestNextPage()` methods:
* Use `request()` to issue any `rippled` command, including `account_currencies`, `subscribe`, and `unsubscribe`. [Full list of API Methods](https://xrpl.org/public-rippled-methods.html).
* Use `hasNextPage()` to determine whether a response has more pages. This is true when the response includes a [`marker` field](https://xrpl.org/markers-and-pagination.html).
* Use `requestNextPage()` to request the next page of data.
When using rippled APIs:
* [Specify XRP amounts in drops](https://xrpl.org/basic-data-types.html#specifying-currency-amounts).
* [Specify timestamps as the number of seconds since the "Ripple Epoch"](https://xrpl.org/basic-data-types.html#specifying-time).
* Instead of `counterparty`, use `issuer`.
## Listening to streams
The `rippled` server can push updates to your client when various events happen.
Refer to [Subscriptions in the `rippled` API docs](https://xrpl.org/subscribe.html) for details.
Note that the `streams` parameter for generic streams takes an array. For example, to subscribe to the `validations` stream, use `{ streams: [ 'validations' ] }`.
The string names of some generic streams to subscribe to are in the table below. (Refer to `rippled` for an up-to-date list of streams.)
Type | Description
---- | -----------
`server` | Sends a message whenever the status of the `rippled` server (for example, network connectivity) changes.
`ledger` | Sends a message whenever the consensus process declares a new validated ledger.
`transactions` | Sends a message whenever a transaction is included in a closed ledger.
`transactions_proposed` | Sends a message whenever a transaction is included in a closed ledger, as well as some transactions that have not yet been included in a validated ledger and may never be. Not all proposed transactions appear before validation. Even some transactions that don't succeed are included in validated ledgers because they take the anti-spam transaction fee.
`validations` | Sends a message whenever the server receives a validation message, also called a validation vote, regardless of whether the server trusts the validator.
`manifests` | Sends a message whenever the server receives a manifest.
`peer_status` | (Admin-only) Information about connected peer `rippled` servers, especially with regards to the consensus process.
When you subscribe to a stream, you must also listen to the relevant message type(s). Some of the available message types are in the table below. (Refer to `rippled` for an up-to-date list of message types.)
Type | Description
---- | -----------
`ledgerClosed` | Sent by the `ledger` stream when the consensus process declares a new fully validated ledger. The message identifies the ledger and provides some information about its contents.
`validationReceived` | Sent by the `validations` stream when the server receives a validation message, also called a validation vote, regardless of whether the server trusts the validator.
`manifestReceived` | Sent by the `manifests` stream when the server receives a manifest.
`transaction` | Sent by many subscriptions including `transactions`, `transactions_proposed`, `accounts`, `accounts_proposed`, and `book` (Order Book). See [Transaction Streams](https://xrpl.org/subscribe.html#transaction-streams) for details.
`peerStatusChange` | (Admin-only) Reports a large amount of information on the activities of other `rippled` servers to which the server is connected.
`path_find` | Asynchronous follow-up response to the currently open path\_find request. See [rippled path\_find method](https://xrpl.org/path_find.html) for details.
To register your listener function, use `connection.on(type, handler)`.
Here is an example of listening for transactions on given account(s):
```
const account = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn' // Replace with the account you want notifications for
api.connect().then(() => {
// 'transaction' can be replaced with the relevant `type` from the table above
api.connection.on('transaction', (event) => {
// Do something useful with `event`
console.log(JSON.stringify(event, null, 2))
})
api.request('subscribe', {
accounts: [ account ]
}).then(response => {
console.log('Successfully subscribed')
}).catch(error => {
// Handle `error`
})
})
```
The subscription ends when you unsubscribe or the WebSocket connection is closed.
For full details, see the [subscribe method](https://xrpl.org/subscribe.html).

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 throws a `ValidationError` if the object does not conform to the schema.
### Example
```javascript
RippleAPI.schemaValidator.schemaValidate('sign', {
signedTransaction: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8744630440220680070A157682D9EB510E8AD58C35DC9C8346B155077D73792E88120B7A3B6B1022079537D3300C9B4D2D3D62ACCE1E66CDA893F9612CB2577ADEC8154B933765336770B6578616D706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '10B54D31384A49336C36A5907E3C28227139E282D3C7F734FEA351DE446F3674'
})
```
```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: '12000322800000002400000017201B0086955368400000000000000C732102F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8744630440220680070A157682D9EB510E8AD58C35DC9C8346B155077D73792E88120B7A3B6B1022079537D3300C9B4D2D3D62ACCE1E66CDA893F9612CB2577ADEC8154B933765336770B6578616D706C652E636F6D81145E7B112523F68D2F5E879DB4EAC51C6698A69304',
id: '123'
})
```
```
[ValidationError(instance.id does not match pattern "^[A-F0-9]{64}$")]
```

128
docs/src/sign.md.ejs Normal file
View File

@@ -0,0 +1,128 @@
## sign
```
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 can then 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 is unrecognized until `ripple-binary-codec` is updated. If you try to sign an unrecognized transaction type, this method throws an error like the following:
`Error: [TRANSACTION_TYPE] is not a valid name or ordinal for TransactionType`
### Parameters
<%- renderSchema("input/sign.json") %>
When this method is used for multi-signing, the `options` parameter is required. See the multi-signing example in this section for more details.
### Return Value
This method returns an object with the following structure:
<%- renderSchema("output/sign.json") %>
### Example
```javascript
// AccountSet transaction that sets Domain to example.com:
const txJSON = '{"Flags":2147483648,"TransactionType":"AccountSet","Account":"r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59","Domain":"6578616D706C652E636F6D","LastLedgerSequence":8820051,"Fee":"12","Sequence":23}';
const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV';
const keypair = { privateKey: '00ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A', publicKey: '02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8' };
return api.sign(txJSON, secret); // or: api.sign(txJSON, keypair);
```
<%- renderFixture("responses/sign.json") %>
### Example (multi-signing)
```javascript
const RippleAPI = require('ripple-lib').RippleAPI;
// jon's address will have a multi-signing setup with a quorum of 2
const jon = {
account: 'rJKpme4m2zBQceBuU89d7vLMzgoUw2Ptj',
secret: 'sh4Va7b1wQof8knHFV2sxwX12fSgK'
};
const aya = {
account: 'rnrPdBjs98fFFfmRpL6hM7exT788SWQPFN',
secret: 'snaMuMrXeVc2Vd4NYvHofeGNjgYoe'
};
const bran = {
account: 'rJ93RLnT1t5A8fCr7HTScw7WtfKJMRXodH',
secret: 'shQtQ8Um5MS218yvEU3Ehy1eZQKqH'
};
// Setup the signers list with a quorum of 2
const multiSignSetupTransaction = {
"Flags": 0,
"TransactionType": "SignerListSet",
"Account": "rJKpme4m2zBQceBuU89d7vLMzgoUw2Ptj",
"Fee": "120",
"SignerQuorum": 2,
"SignerEntries": [
{
"SignerEntry": {
"Account": "rnrPdBjs98fFFfmRpL6hM7exT788SWQPFN",
"SignerWeight": 2
}
},
{
"SignerEntry": {
"Account": "rJ93RLnT1t5A8fCr7HTScw7WtfKJMRXodH",
"SignerWeight": 1
}
},
]
};
// a transaction which requires multi signing
const multiSignPaymentTransaction = {
TransactionType: 'Payment',
Account: 'rJKpme4m2zBQceBuU89d7vLMzgoUw2Ptj',
Destination: 'rJ93RLnT1t5A8fCr7HTScw7WtfKJMRXodH',
Amount: '88000000'
};
const multiSignPaymentInstruction = {
signersCount: 2
};
const api = new RippleAPI({
server: 'wss://s.altnet.rippletest.net:51233'
});
api.connect().then(() => {
// adding the multi signing feature to jon's account
api.prepareTransaction(multiSignSetupTransaction).then((prepared) => {
console.log(prepared);
jonSign = api.sign(prepared.txJSON, jon.secret).signedTransaction;
api.submit(jonSign).then( response => {
console.log(response.resultCode, response.resultMessage);
// multi sign a transaction
api.prepareTransaction(multiSignPaymentTransaction, multiSignPaymentInstruction).then(prepared => {
console.log(prepared);
// Aya and Bran sign it too but with 'signAs' set to their own account
let ayaSign = api.sign(prepared.txJSON, aya.secret, {'signAs': aya.account}).signedTransaction;
let branSign = api.sign(prepared.txJSON, bran.secret, {'signAs': bran.account}).signedTransaction;
// signatures are combined and submitted
let combinedTx = api.combine([ayaSign, branSign]);
api.submit(combinedTx.signedTransaction).then(response => {
console.log(response.tx_json.hash);
return api.disconnect();
}).catch(console.error);
}).catch(console.error);
}).catch(console.error)
}).catch(console.error);
}).catch(console.error);
```
If the multi-signing account was setup properly, the above example logs `resultCode: 'tesSUCCESS'` and the hash for the transaction. If any of `{signAs: some_address}` options were missing, the code returns a validation error such as:
```
[ValidationError(txJSON is not the same for all signedTransactions)]
```

View File

@@ -0,0 +1,28 @@
## signPaymentChannelClaim
`signPaymentChannelClaim(channel: string, amount: string, privateKey: string): string`
Sign a payment channel claim. A [PaymentChannelClaim](#preparepaymentchannelclaim) transaction can use the resulting signature to withdraw XRP from a payment channel.
### Parameters
<%- renderSchema("input/sign-payment-channel-claim.json") %>
### Return Value
This method returns a signature string:
<%- renderSchema("output/sign-payment-channel-claim.json") %>
### Example
```javascript
const channel =
'3E18C05AD40319B809520F1A136370C4075321B285217323396D6FD9EE1E9037';
const amount = '.00001';
const privateKey =
'ACCD3309DB14D1A4FC9B1DAE608031F4408C85C73EE05E035B7DC8B25840107A';
return api.signPaymentChannelClaim(channel, amount, privateKey);
```
<%- renderFixture("responses/sign-payment-channel-claim.json") %>

View File

@@ -0,0 +1,185 @@
# Transaction Specifications
A *transaction specification* specifies what a transaction should do. Each [Transaction Type](#transaction-types) has its own type of specification, which corresponds to the [native XRP Ledger transaction types](https://xrpl.org/transaction-types.html).
## Account Delete
Delete your account and send the remaining XRP elsewhere. (Native transaction type: [AccountDelete](https://xrpl.org/accountdelete.html))
<%- renderSchema('specifications/account-delete.json') %>
> **Note:** To prepare an Account Delete transaction, use [`prepareTransaction()`](#preparetransaction) with the [native transaction format](https://xrpl.org/accountdelete.html).
## Check Cancel
Cancel a Check that has not been redeemed. (Native transaction type: [CheckCancel](https://xrpl.org/checkcancel.html))
<%- renderSchema('specifications/check-cancel.json') %>
#### Example
<%- renderFixture('requests/prepare-check-cancel.json') %>
## Check Cash
Redeem a Check for up to its stated value. (Native transaction type: [CheckCash](https://xrpl.org/checkcash.html))
<%- renderSchema('specifications/check-cash.json') %>
#### Example
<%- renderFixture('requests/prepare-check-cash-amount.json') %>
## Check Create
Create a Check, a deferred payment that can be redeemed by the destination. (Native transaction type: [CheckCreate](https://xrpl.org/checkcreate.html))
<%- renderSchema('specifications/check-create.json') %>
#### Example
<%- renderFixture('requests/prepare-check-create.json') %>
## Deposit Preauth
Preauthorize an sender to deposit money at an account using [Deposit Authorization](https://xrpl.org/depositauth.html). (Native transaction type: [DepositPreauth](https://xrpl.org/depositpreauth.html))
<%- renderSchema('specifications/deposit-preauth.json') %>
> **Note:** To prepare a Deposit Preauth transaction, use [`prepareTransaction()`](#preparetransaction) with the [native transaction format](https://xrpl.org/depositpreauth.html).
## Escrow Cancellation
Cancel an Escrow that has passed its expiration. (Native transaction type: [EscrowCancel](https://xrpl.org/escrowcancel.html))
<%- renderSchema('specifications/escrow-cancellation.json') %>
#### Example
<%- renderFixture('requests/prepare-escrow-cancellation.json') %>
## Escrow Creation
Create an Escrow that locks up XRP until a given time or condition is met. (Native transaction type: [EscrowCreate](https://xrpl.org/escrowcreate.html))
<%- renderSchema('specifications/escrow-creation.json') %>
#### Example
<%- renderFixture('requests/prepare-escrow-creation.json') %>
## Escrow Execution
Deliver XRP from an Escrow after its conditions have been met. (Native transaction type: [EscrowFinish](https://xrpl.org/escrowfinish.html))
<%- renderSchema('specifications/escrow-execution.json') %>
#### Example
<%- renderFixture('requests/prepare-escrow-execution.json') %>
## Order
Create and execute a limit order in the decentralized exchange. (Native transaction type: [OfferCreate](https://xrpl.org/offercreate.html))
<%- renderSchema('specifications/order.json') %>
The following invalid flag combination causes a `ValidationError`: `immediateOrCancel` and `fillOrKill`. These fields are mutually exclusive, and cannot both be set at the same time.
#### Example
<%- renderFixture('requests/prepare-order.json') %>
## Order Cancellation
Cancel an order in the decentralized exchange. (Native transaction type: [OfferCancel](https://xrpl.org/offercancel.html))
<%- renderSchema('specifications/order-cancellation.json') %>
#### Example
<%- renderFixture('requests/prepare-order-cancellation.json') %>
## Payment
Send value from one account to another. (Native transaction type: [Payment](https://xrpl.org/payment.html))
<%- renderSchema('specifications/payment.json') %>
#### Example
<%- renderFixture('requests/prepare-payment.json') %>
## Payment Channel Claim
Redeem XRP from a Payment Channel. (Native transaction type: [PaymentChannelClaim](https://xrpl.org/paymentchannelclaim.html))
<%- renderSchema('specifications/payment-channel-claim.json') %>
#### Example
<%- renderFixture('requests/prepare-payment-channel-claim.json') %>
## Payment Channel Create
Create a Payment Channel with XRP set aside for asynchronous payments. (Native transaction type: [PaymentChannelCreate](https://xrpl.org/paymentchannelcreate.html))
<%- renderSchema('specifications/payment-channel-create.json') %>
#### Example
<%- renderFixture('requests/prepare-payment-channel-create.json') %>
## Payment Channel Fund
Add XRP to a Payment Channel. (Native transaction type: [PaymentChannelFund](https://xrpl.org/paymentchannelfund.html))
<%- renderSchema('specifications/payment-channel-fund.json') %>
#### Example
<%- renderFixture('requests/prepare-payment-channel-fund.json') %>
## Settings
Change account settings. (Native transaction types: [AccountSet](https://xrpl.org/accountset.html), [SetRegularKey](https://xrpl.org/setregularkey.html), [SignerListSet](https://xrpl.org/signerlistset.html))
<%- renderSchema('output/get-settings.json') %>
#### Example
<%- renderFixture('requests/prepare-settings.json') %>
## Ticket Create
Set aside account Sequence numbers as Tickets to be used by later transactions.
> **Caution:** As of 2021-01-22, Tickets are not yet available on the XRP Ledger.
> **Note:** To prepare a Ticket Create transaction, use [`prepareTransaction()`](#preparetransaction) with the native transaction format. <!-- Future link: https://xrpl.org/ticketcreate.html -->
## Trustline
Create or modify a trust line between two accounts, for an issued currency. (Native transaction type: [TrustSet](https://xrpl.org/trustset.html))
<%- renderSchema('specifications/trustline.json') %>
#### Example
<%- renderFixture('requests/prepare-trustline.json') %>

View File

@@ -0,0 +1,100 @@
# Static Methods
You can access static methods directly on the `RippleAPI` class. For example, `RippleAPI.computeBinaryTransactionHash(...)`.
A few of the most commonly-used methods are documented below.
For a full list, refer to these docs:
- [XRP Ledger Hashes](https://github.com/ripple/ripple-lib/blob/develop/src/common/hashes/README.md)
- [ripple-address-codec API](https://github.com/ripple/ripple-address-codec/blob/master/README.md#api)
## computeBinaryTransactionHash
`computeBinaryTransactionHash(txBlobHex: string): string`
Returns the hash (id) of a binary transaction blob.
This is a static method on the `RippleAPI` class.
### Parameters
This method takes one parameter, a string containing a binary transaction in hex.
### Return Value
This method returns a string representing the transaction's id (hash).
### Example
```javascript
const signed_blob = '120000228000000024000B2E5A201B0066374B61400000003B9ACA0068400000000000000C732102356E89059A75438887F9FEE2056A2890DB82A68353BE9C0C0C8F89C0018B37FC74473045022100B3721EEB1ED6DFF29FB8B209E2DE6B54A0A6E44D52D926342F3D334BE98F08640220367A74107AD5DEAEFA3AB2984C161FC23F30B2704BB5CC984358BA262177A4568114F667B0CA50CC7709A220B0561B85E53A48461FA883142B71D8B09B4EE8DAA68FB936C23E3A974713BDAC'
if (typeof signed_blob === 'string' && signed_blob.match(/^[A-F0-9]+$/)) {
const id = RippleAPI.computeBinaryTransactionHash(signed_blob)
console.log('Transaction hash:', id')
}
```
```
Transaction hash: 80C5E11E1A21A626759D6CB944B33DBAAC66BD704A289C86E330B847904F5C13
```
[RunKit Example: computeBinaryTransactionHash](https://runkit.com/intelliot/computebinarytransactionhash-example)
## classicAddressToXAddress
`classicAddressToXAddress(classicAddress: string, tag: number | false[, test: boolean]): string`
Convert a classic address and tag to an X-address.
If `test` is `true`, the address starts with `T` to show that the address is intended for use on a test network.
### Example: Encode an X-address with tag 4294967295
```javascript
const RippleAPI = require('ripple-lib').RippleAPI
const xAddress = RippleAPI.classicAddressToXAddress('rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 4294967295)
console.log(xAddress)
```
```
XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi
```
### Example: Encode a test address for use with Testnet or Devnet
```javascript
const RippleAPI = require('ripple-lib').RippleAPI
const address = RippleAPI.classicAddressToXAddress('r3SVzk8ApofDJuVBPKdmbbLjWGCCXpBQ2g', 123, true)
console.log(address)
```
```
T7oKJ3q7s94kDH6tpkBowhetT1JKfcfdSCmAXbS75iATyLD
```
## xAddressToClassicAddress
`xAddressToClassicAddress(xAddress: string): {classicAddress: string, tag: number | false, test: boolean}`
Convert an X-address to a classic address and tag.
Since `0` is a valid tag, use `if (tag !== false)` to you want to check for a tag.
If the address is intended for use on a test network, `test === true`. Otherwise, `test === false`.
### Example
```javascript
const RippleAPI = require('ripple-lib').RippleAPI
const address = RippleAPI.xAddressToClassicAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi')
console.log(address)
```
```
{
classicAddress: 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf',
tag: 4294967295,
test: false
}
```

83
docs/src/submit.md.ejs Normal file
View File

@@ -0,0 +1,83 @@
## submit
`request('submit', {tx_blob: string, fail_hard: boolean}): Promise<object>`
The `submit` method applies a transaction and sends it to the network to be confirmed and included in future ledgers.
This method takes a signed, serialized transaction as a binary blob, and submits it to the network as-is. Since signed transaction objects are immutable, no part of the transaction can be modified or automatically filled in after submission.
To send a transaction as robustly as possible, you should construct and sign it in advance, persist it somewhere that you can access even after a power outage, then `submit` it as a `tx_blob`. After submission, monitor the network with the `tx` method to see if the transaction was successfully applied; if a restart or other problem occurs, you can safely re-submit the `tx_blob` transaction: it won't be applied twice since it has the same sequence number as the old transaction.
### Parameters
| `Field` | Type | Description |
|:------------|:--------|:-----------------------------------------------------|
| `tx_blob` | String | Hex representation of the signed transaction to submit. This can be a multi-signed transaction. |
| `fail_hard` | Boolean | (Optional, defaults to false) If true, and the transaction fails locally, do not retry or relay the transaction to other servers |
### Return Value
When successful, this method returns an object containing the following fields:
| `Field` | Type | Description |
|:------------------------|:--------|:-----------------------------------------|
| `engine_result` | String | Text [result code](https://xrpl.org/transaction-results.html) indicating the preliminary result of the transaction, for example `tesSUCCESS` |
| `engine_result_code` | Integer | Numeric version of the [result code](https://xrpl.org/transaction-results.html). **Not recommended.** |
| `engine_result_message` | String | Human-readable explanation of the transaction's preliminary result |
| `tx_blob` | String | The complete transaction in hex string format |
| `tx_json` | Object | The complete transaction in JSON format |
| `accepted` | Boolean | The value `true` indicates that the transaction was applied, queued, broadcast, or kept for later. The value `false` indicates that none of those happened, so the transaction cannot possibly succeed as long as you do not submit it again and have not already submitted it another time. [New in: rippled 1.5.0] |
| `account_sequence_available` | Number | The next [Sequence Number](https://xrpl.org/basic-data-types.html#account-sequence) available for the sending account after all pending and [queued](https://xrpl.org/transaction-queue.html) transactions. [New in: rippled 1.5.0] |
| `account_sequence_next` | number | The next [Sequence Number](https://xrpl.org/basic-data-types.html#account-sequence) for the sending account after all transactions that have been provisionally applied, but not transactions in the [queue](https://xrpl.org/transaction-queue.html). [New in: rippled 1.5.0] |
| `applied` | Boolean | The value `true` indicates that this transaction was applied to the open ledger. In this case, the transaction is likely, but not guaranteed, to be validated in the next ledger version. [New in: rippled 1.5.0] |
| `broadcast` | Boolean | The value `true` indicates this transaction was broadcast to peer servers in the peer-to-peer XRP Ledger network. (Note: if the server has no peers, such as in [stand-alone mode](https://xrpl.org/rippled-server-modes.html#reasons-to-run-a-rippled-server-in-stand-alone-mode), the server uses the value `true` for cases where it _would_ have broadcast the transaction.) The value `false` indicates the transaction was not broadcast to any other servers. [New in: rippled 1.5.0] |
| `kept` | Boolean | The value `true` indicates that the transaction was kept to be retried later. [New in: rippled 1.5.0] |
| `queued` | Boolean | The value `true` indicates the transaction was put in the [Transaction Queue](https://xrpl.org/transaction-queue.html), which means it is likely to be included in a future ledger version. [New in: rippled 1.5.0] |
| `open_ledger_cost` | String | The current [open ledger cost](https://xrpl.org/transaction-cost.html#open-ledger-cost) before processing this transaction. Transactions with a lower cost are likely to be [queued](https://xrpl.org/transaction-queue.html). [New in: rippled 1.5.0] |
| `validated_ledger_index` | Integer | The [ledger index](https://xrpl.org/basic-data-types.html#ledger-index) of the newest validated ledger at the time of submission. This provides a lower bound on the ledger versions that the transaction can appear in as a result of this request. (The transaction could only have been validated in this ledger version or earlier if it had already been submitted before.) |
Note: Many situations can prevent a transaction from processing successfully, such as a lack of trust lines connecting the two accounts in a payment, or changes in the state of the ledger since the time the transaction was constructed. Even if nothing is wrong, it may take several seconds to close and validate the ledger version that includes the transaction. Do not consider the transaction's results final until they appear in a validated ledger version.
### Example
```javascript
const signedTransaction = '12000022800000002400000007201B007008BC61400000000754D4C068400000000000000C732103E8110048477E60F292DEDA67CF518511E70A15E1E3771B3C024026E1F824832874473045022100D659C836C24FF346A87054E463078D805B19EFE9F10348FD4C6ED6C3F3C4D750022060BE0BFD5E2C4963A1B0E0F21D5BA800969863BA486F71E75C08D76D77C45B22811492F80A3F3849DBB5714A4F2C691CE7D47BEED58083141266204CFBC657E65D9B4D30301FF98644693935';
const failHard = false;
const result = await api.request('submit', {
tx_blob: signedTransaction,
fail_hard: failHard // optional
});
```
```json
{
"accepted": true,
"account_sequence_available": 8,
"account_sequence_next": 8,
"applied": true,
"broadcast": true,
"engine_result": "tesSUCCESS",
"engine_result_code": 0,
"engine_result_message": "The transaction was applied. Only final in a validated ledger.",
"kept": true,
"open_ledger_cost": "10",
"queued": false,
"tx_blob": "12000022800000002400000007201B007008BC61400000000754D4C068400000000000000C732103E8110048477E60F292DEDA67CF518511E70A15E1E3771B3C024026E1F824832874473045022100D659C836C24FF346A87054E463078D805B19EFE9F10348FD4C6ED6C3F3C4D750022060BE0BFD5E2C4963A1B0E0F21D5BA800969863BA486F71E75C08D76D77C45B22811492F80A3F3849DBB5714A4F2C691CE7D47BEED58083141266204CFBC657E65D9B4D30301FF98644693935",
"tx_json": {
"Account": "rNQao3Z1irwRjKWSs8heL4a8WKLPKfLrXs",
"Amount": "123000000",
"Destination": "rpgHWJdXkSvvzikdJCpuMzU7zWnuqsJRCZ",
"Fee": "12",
"Flags": 2147483648,
"LastLedgerSequence": 7342268,
"Sequence": 7,
"SigningPubKey": "03E8110048477E60F292DEDA67CF518511E70A15E1E3771B3C024026E1F8248328",
"TransactionType": "Payment",
"TxnSignature": "3045022100D659C836C24FF346A87054E463078D805B19EFE9F10348FD4C6ED6C3F3C4D750022060BE0BFD5E2C4963A1B0E0F21D5BA800969863BA486F71E75C08D76D77C45B22",
"hash": "FE8D68D7FF5805EB07AF15A1ADF07FB5463CCD2C6C0A15981EB3D26A02E1551C"
},
"validated_ledger_index": 7341775
}
```
(In ripple-lib 1.8.0, [the old `submit` method](https://github.com/ripple/ripple-lib/blob/1.7.0/docs/index.md#submit) was deprecated.)

View File

@@ -0,0 +1,76 @@
# Transaction Overview
## Transaction Types
A transaction type is specified by the strings in the first column in the table below.
Type | Description
---- | -----------
[payment](#payment) | A `payment` transaction represents a transfer of value from one account to another. Depending on the [path](https://xrpl.org/paths.html) taken, additional exchanges of value may occur atomically to enable the payment.
[order](#order) | An `order` transaction creates a limit order. It defines an intent to exchange currencies, and creates an order in the XRP Ledger's order book if not completely fulfilled when placed. Orders can be partially fulfilled.
[orderCancellation](#order-cancellation) | An `orderCancellation` transaction cancels an order in the XRP Ledger's order book.
[trustline](#trustline) | A `trustline` transaction creates or modifies a trust line between two accounts.
[settings](#settings) | A `settings` transaction modifies the settings of an account in the XRP Ledger.
[escrowCreation](#escrow-creation) | An `escrowCreation` transaction creates an escrow on the ledger, which locks XRP until a cryptographic condition is met or it expires. It is like an escrow service where the XRP Ledger acts as the escrow agent.
[escrowCancellation](#escrow-cancellation) | An `escrowCancellation` transaction unlocks the funds in an escrow and sends them back to the creator of the escrow, if the escrow has expired.
[escrowExecution](#escrow-execution) | An `escrowExecution` transaction unlocks the funds in an escrow and sends them to the destination of the escrow, if the conditions for the escrow are met.
[checkCreate](#check-create) | A `checkCreate` transaction creates a check on the ledger, which is a deferred payment that can be cashed by its intended destination.
[checkCancel](#check-cancel) | A `checkCancel` transaction cancels an unredeemed Check, removing it from the ledger without sending any money.
[checkCash](#check-cash) | A `checkCash` transaction redeems a Check to receive up to the amount authorized by the corresponding `checkCreate` transaction. Only the `destination` address of a Check can cash it.
[paymentChannelCreate](#payment-channel-create) | A `paymentChannelCreate` transaction opens a payment channel between two addresses with XRP set aside for asynchronous payments.
[paymentChannelFund](#payment-channel-fund) | A `paymentChannelFund` transaction adds XRP to a payment channel and optionally sets a new expiration for the channel.
[paymentChannelClaim](#payment-channel-claim) | A `paymentChannelClaim` transaction withdraws XRP from a channel and optionally requests to close it.
[ticketCreate](#ticket-create) | A successful `ticketCreate` transaction adds a Ticket in the directory of the owning account.
## Transaction Flow
Executing a transaction with `RippleAPI` requires the following four steps:
1. Prepare - Create an unsigned transaction based on a [specification](#transaction-specifications) and [instructions](#transaction-instructions). There is a method to prepare each type of transaction:
* [preparePayment](#preparepayment)
* [prepareTrustline](#preparetrustline)
* [prepareOrder](#prepareorder)
* [prepareOrderCancellation](#prepareordercancellation)
* [prepareSettings](#preparesettings)
* [prepareEscrowCreation](#prepareescrowcreation)
* [prepareEscrowCancellation](#prepareescrowcancellation)
* [prepareEscrowExecution](#prepareescrowexecution)
* [prepareCheckCreate](#preparecheckcreate)
* [prepareCheckCancel](#preparecheckcancel)
* [prepareCheckCash](#preparecheckcash)
* [prepareTicketCreate](#prepareticketcreate)
2. [Sign](#sign) - Cryptographically sign the transaction locally and save the [transaction ID](#transaction-id). Signing is how the owner of an account authorizes a transaction to take place. For multisignature transactions, the `signedTransaction` fields returned by `sign` must be collected and passed to the [combine](#combine) method.
3. [Submit](#submit) - Submit the transaction to the connected server.
4. Verify - Verify that the transaction got validated by querying with [getTransaction](#gettransaction). This is necessary because transactions may fail even if they were successfully submitted.
## Transaction Fees
Every transaction must destroy a small amount of XRP as a cost to apply the transaction to the ledger. This is also called a *transaction fee*. The transaction cost is designed to increase along with the load on the XRP Ledger, making it very expensive to deliberately or inadvertently overload the peer-to-peer network that powers the XRP Ledger.
You can choose the size of the fee you want to pay or let a default be used. You can get an estimate of the fee required to be included in the next ledger closing with the [getFee](#getfee) method.
For a multi-signed transaction, ripple-lib automatically multiplies the `fee` by (1 + Number of Signatures Provided). For example, if you set `instructions.fee = '0.000020'` and `instructions.signersCount = 2`, the prepared transaction's `Fee` is 20 drops × (1 + 2 Signatures) = 60 drops. See [Transaction Cost](https://xrpl.org/transaction-cost.html).
## Transaction Instructions
Transaction instructions indicate how to execute a transaction, complementary with the [transaction specification](#transaction-specifications).
<%- renderSchema("objects/instructions.json") %>
We recommend that you specify a `maxLedgerVersion` so that you can quickly determine that a failed transaction can never succeed in the future. It is impossible for a transaction to succeed after the XRP Ledger's consensus-validated ledger version exceeds the transaction's `maxLedgerVersion`. If you omit `maxLedgerVersion`, the "prepare\*" method automatically supplies a `maxLedgerVersion` equal to the current ledger plus 3, which it includes in the return value from the "prepare\*" method.
## Transaction ID
```json
"F4AB442A6D4CBB935D66E1DA7309A5FC71C7143ED4049053EC14E3875B0CF9BF"
```
A transaction ID is a 64-bit hexadecimal string that uniquely identifies the transaction. The transaction ID is derived from the transaction instruction and specifications, using a strong hash function.
You can look up a transaction by ID using the [getTransaction](#gettransaction) method.
## Transaction Memos
Every transaction can optionally have an array of memos for user applications. The `memos` field in each [transaction specification](#transaction-specifications) is an array of objects with the following structure:
<%- renderSchema('objects/memos.json') %>

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://xrpl.org/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://xrpl.org/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://xrpl.org/rippling.html) between two trustlines of the same currency, if this flag is set on both.
`txFlags.TrustSet.ClearNoRipple`: Clears the No-[Rippling](https://xrpl.org/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://xrpl.org/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,31 @@
## verifyPaymentChannelClaim
`verifyPaymentChannelClaim(channel: string, amount: string, signature: string, publicKey: string): boolean`
Verify a payment channel claim signature.
### Parameters
<%- renderSchema("input/verify-payment-channel-claim.json") %>
### Return Value
This method returns `true` if the claim signature is valid.
<%- renderSchema("output/verify-payment-channel-claim.json") %>
### Example
```javascript
const channel =
'3E18C05AD40319B809520F1A136370C4075321B285217323396D6FD9EE1E9037';
const amount = '.00001';
const signature = <%- importFile("test/fixtures/responses/sign-payment-channel-claim.json") %>;
const publicKey =
'02F89EAEC7667B30F33D0687BBA86C3FE2A08CCA40A9186C5BDE2DAA6FA97A37D8';
return api.verifyPaymentChannelClaim(channel, amount, signature, publicKey);
```
```json
true
```

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,5 +0,0 @@
{
"version": "independent",
"useWorkspaces": true,
"npmClient": "npm"
}

32277
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,76 +1,94 @@
{
"name": "xrpl.js",
"private": true,
"scripts": {
"test": "lerna run test --stream",
"test:browser": "lerna run test:browser --stream",
"test:integration": "lerna run test:integration --stream",
"lint": "lerna run lint --stream",
"clean": "lerna run clean --stream",
"build": "lerna run build --stream",
"docgen": "lerna run docgen --stream"
"name": "ripple-lib",
"version": "1.9.8-storm.4",
"license": "ISC",
"description": "A TypeScript/JavaScript API for interacting with the XRP Ledger in Node.js and the browser",
"files": [
"dist/npm/*",
"build/ripple-latest-min.js",
"build/ripple-latest.js"
],
"main": "dist/npm/",
"unpkg": "build/ripple-latest-min.js",
"jsdelivr": "build/ripple-latest-min.js",
"types": "dist/npm/index.d.ts",
"browser": {
"ws": "./dist/npm/common/wswrapper.js",
"https-proxy-agent": false
},
"directories": {
"test": "test"
},
"dependencies": {
"ripple-address-codec": "file:packages/ripple-address-codec",
"ripple-binary-codec": "file:packages/ripple-binary-codec",
"ripple-keypairs": "file:packages/ripple-keypairs",
"xrpl": "file:packages/xrpl"
"@types/lodash": "^4.14.136",
"@types/ws": "^7.2.0",
"bignumber.js": "^9.0.0",
"https-proxy-agent": "^5.0.0",
"jsonschema": "1.2.2",
"lodash": "^4.17.4",
"ripple-address-codec": "4.1.3",
"ripple-binary-codec": "1.1.4-beta.2",
"ripple-keypairs": "1.0.4-storm.2",
"ripple-lib-transactionparser": "0.8.2",
"ws": "^7.2.0"
},
"resolutions": {
"elliptic": "^6.5.4"
},
"devDependencies": {
"@types/chai": "^4.2.21",
"@types/lodash": "^4.14.136",
"@types/mocha": "^9.0.0",
"@types/mocha": "^8.2.1",
"@types/node": "^16.4.3",
"@types/puppeteer": "5.4.4",
"@types/ws": "^8.2.0",
"@typescript-eslint/eslint-plugin": "^4.30.0",
"@typescript-eslint/parser": "^4.0.0",
"@xrplf/eslint-config": "^1.6.0",
"@xrplf/prettier-config": "^1.5.0",
"@typescript-eslint/eslint-plugin": "^2.3.3",
"@typescript-eslint/parser": "^2.27.0",
"assert": "^2.0.0",
"assert-diff": "^3.0.0",
"buffer": "^6.0.2",
"chai": "^4.3.4",
"crypto-browserify": "^3.12.0",
"doctoc": "^2.0.0",
"ejs": "^3.0.1",
"eslint": "^7.5.0",
"eslint-plugin-array-func": "^3.1.7",
"eslint-plugin-consistent-default-export-name": "^0.0.13",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-import": "^2.24.1",
"eslint-plugin-jsdoc": "^36.0.0",
"eslint-plugin-mocha": "^9.0.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-tsdoc": "^0.2.14",
"eslint": "^6.5.1",
"eventemitter2": "^6.0.0",
"https-browserify": "^1.0.0",
"jest": "^26.0.1",
"lerna": "^4.0.0",
"json-schema-to-markdown-table": "^0.4.0",
"mocha": "^9",
"npm-run-all": "^4.1.5",
"nyc": "^15",
"path-browserify": "1.0.1",
"prettier": "^2.3.2",
"prettier": "^2.0.5",
"process": "^0.11.10",
"puppeteer": "10.4.0",
"source-map-support": "^0.5.16",
"stream-browserify": "^3.0.0",
"stream-http": "3.2.0",
"ts-jest": "^26.4.4",
"ts-loader": "^9.2.5",
"ts-node": "^10.2.1",
"typedoc": "^0.22.5",
"typescript": "^4.4.2",
"ts-node": "^10.1.0",
"typescript": "^3.9.9",
"url": "^0.11.0",
"webpack": "^5.6.0",
"webpack-bundle-analyzer": "^4.1.0",
"webpack-cli": "^4.2.0"
},
"workspaces": [
"packages/*"
],
"scripts": {
"build:schemas": "mkdir -p dist/npm/common && cp -r src/common/schemas dist/npm/common/",
"build:lib": "tsc --build",
"build:web": "webpack",
"build": "yarn build:schemas && yarn build:lib && yarn build:web",
"analyze": "yarn build:web --analyze",
"watch": "yarn build:lib --watch",
"clean": "rm -rf dist/npm",
"doctoc": "doctoc docs/index.md --title '# RippleAPI Reference' --github --maxlevel 2",
"docgen": "node --harmony scripts/build_docs.js",
"prepublish": "yarn clean && yarn build",
"test": "TS_NODE_PROJECT=src/tsconfig.json nyc mocha --config=test/.mocharc.json --exit",
"test:integration": "TS_NODE_PROJECT=src/tsconfig.json nyc mocha ./test/integration/*.ts",
"test:watch": "TS_NODE_PROJECT=src/tsconfig.json mocha --config=test/.mocharc.json --watch --reporter dot",
"format": "prettier --write '{src,test}/**/*.ts'",
"lint": "eslint 'src/**/*.ts' 'test/*-test.{ts,js}'",
"perf": "./scripts/perf_test.sh",
"compile:snippets": "tsc -p snippets/tsconfig.json",
"start:snippet": "npm run compile:snippets && node ./snippets/dist/start.js",
"inspect:snippet": "npm run compile:snippets && node inspect ./snippets/dist/start.js"
},
"repository": {
"type": "git",
"url": "git://github.com/ripple/ripple-lib.git"
},
"readmeFilename": "README.md",
"engines": {
"node": ">=10.0.0",
"npm": ">=7.0.0 < 8.0.0"
"node": ">=10.13.0",
"yarn": "^1.15.2"
}
}

View File

@@ -1,12 +0,0 @@
# Don't ever lint node_modules
node_modules
# Don't lint build output
dist
# don't lint nyc coverage output
coverage
.nyc_output
# Don't lint NYC configuration
nyc.config.js

View File

@@ -1,85 +0,0 @@
module.exports = {
root: true,
parser: '@typescript-eslint/parser', // Make ESLint compatible with TypeScript
parserOptions: {
// Enable linting rules with type information from our tsconfig
tsconfigRootDir: __dirname,
project: ['./tsconfig.json'],
sourceType: 'module', // Allow the use of imports / ES modules
ecmaFeatures: {
impliedStrict: true, // Enable global strict mode
},
},
// Specify global variables that are predefined
env: {
browser: true, // Enable browser global variables
node: true, // Enable node global variables & Node.js scoping
es2020: true, // Add all ECMAScript 2020 globals and automatically set the ecmaVersion parser option to ES2020
},
plugins: [],
extends: ['@xrplf/eslint-config/base'],
rules: {
// ** TODO **
// all of the below are turned off for now during the migration to a
// monorepo. They need to actually be addressed!
// **
'@typescript-eslint/no-for-in-array': 'off',
'@typescript-eslint/consistent-type-assertions': 'off',
'@typescript-eslint/no-unnecessary-condition': 'off',
'@typescript-eslint/prefer-for-of': 'off',
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-magic-numbers': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-unsafe-return': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/explicit-member-accessibility': 'off',
'@typescript-eslint/promise-function-async': 'off',
'@typescript-eslint/prefer-nullish-coalescing': 'off',
'@typescript-eslint/naming-convention': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/array-type': 'off',
'@typescript-eslint/restrict-plus-operands': 'off',
'@typescript-eslint/no-unnecessary-type-assertion': 'off',
'jsdoc/require-returns': 'off',
'jsdoc/check-param-names': 'off',
'jsdoc/require-throws': 'off',
'jsdoc/require-hyphen-before-param-description': 'off',
'jsdoc/require-jsdoc': 'off',
'jsdoc/require-description-complete-sentence': 'off',
'jsdoc/require-param': 'off',
'jsdoc/no-types': 'off',
'tsdoc/syntax': 'off',
'import/no-commonjs': 'off',
'import/order': 'off',
'no-restricted-syntax': 'off',
'guard-for-in': 'off',
'object-shorthand': 'off',
'no-negated-condition': 'off',
'no-loop-func': 'off',
'id-length': 'off',
'no-inline-comments': 'off',
'max-lines-per-function': 'off',
'max-len': 'off',
'no-nested-ternary': 'off',
'no-param-reassign': 'off',
'no-bitwise': 'off',
'multiline-comment-style': 'off',
'id-blacklist': 'off',
'func-names': 'off',
'max-params': 'off',
'prefer-template': 'off',
'no-else-return': 'off',
},
}

View File

@@ -1,61 +0,0 @@
# .gitignore
# Ignore vim swap files.
*.swp
# Ignore SCons support files.
.sconsign.dblite
# Ignore python compiled files.
*.pyc
# Ignore Macintosh Desktop Services Store files.
.DS_Store
# Ignore backup/temps
*~
# Ignore object files.
*.o
build/
tags
bin/rippled
Debug/*.*
Release/*.*
# Ignore locally installed node_modules
node_modules
!test/node_modules
# Ignore tmp directory.
tmp
# Ignore database directory.
db/*.db
db/*.db-*
# Ignore customized configs
rippled.cfg
validators.txt
test/config.js
# Ignore coverage files
/lib-cov
/src-cov
/coverage.html
/coverage
# Ignore IntelliJ files
.idea
# Ignore npm-debug
npm-debug.log
# Ignore dist folder
dist/
# Ignore flow output directory
out/
# Ignore perf test cache
scripts/cache

View File

@@ -1,64 +0,0 @@
# ripple-address-cod
## 4.1.3 (2021-05-10)
* Update dependencies
* Add `build` script as an alias for `compile`
* Update README
## 4.1.2 (2021-01-11)
* Internal dependencies
* Update jest, ts-jest, typescript, lodash
* Fix potential moderate severity vulnerabilities
* Update @types/node, @types/jest, base-x
* Docs
* Update example for encoding test address
* Document functions (#73)
* xAddressToClassicAddress when there is no tag (#114)
* Add README badges (#120)
* Add LICENSE (#138)
* Cleanup and polish
* Add GitHub CI (#115)
* Fix linting
## 4.1.1 (2020-04-03)
* Require node v10+
* CI: Drop node 6 & 8 and add node 13
* Update dependencies
* Bump @types/node to 13.7.7 (#60)
* Bump jest and ts-jest (#40)
* Bump @types/jest to 25.1.2 (#51)
* Bump ts-jest from 25.0.0 to 25.2.0 (#50)
* Bump typescript from 3.7.5 to 3.8.3 (#61)
* Update all dependencies in yarn.lock
## 4.1.0 (2020-01-22)
* Throwable 'unexpected_payload_length' error: The message has been expanded with ' Ensure that the bytes are a Buffer.'
* Docs (readme): Correct X-address to classic address example (#15) (thanks @RareData)
### New Features
* `encodeAccountPublic` - Encode a public key, as for payment channels
* `decodeAccountPublic` - Decode a public key, as for payment channels
* Internal
* Update dependencies: ts-jest, @types/jest, @types/node, typescript, tslint,
base-x
## 4.0.0 (2019-10-08)
### Breaking Changes
* `decodeAddress` has been renamed to `decodeAccountID`
* `isValidAddress` has been renamed to `isValidClassicAddress`
### New Features
* `classicAddressToXAddress` - Derive X-address from classic address, tag, and network ID
* `encodeXAddress` - Encode account ID, tag, and network ID as an X-address
* `xAddressToClassicAddress` - Decode an X-address to account ID, tag, and network ID
* `decodeXAddress` - Convert X-address to classic address, tag, and network ID
* `isValidXAddress` - Check whether an X-address (X...) is valid

View File

@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Ripple Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,196 +0,0 @@
# ripple-address-codec
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Functions for encoding and decoding XRP Ledger addresses and seeds.
Also includes support for encoding/decoding [rippled validator (node) public keys](https://xrpl.org/run-rippled-as-a-validator.html).
[![NPM](https://nodei.co/npm/ripple-address-codec.png)](https://www.npmjs.org/package/ripple-address-codec)
## X-address Conversion
All tools and apps in the XRP Ledger ecosystem are encouraged to adopt support for the X-address format. The X-address format is a single Base58 string that encodes an 'Account ID', a (destination) tag, and whether the address is intended for a test network. This prevents users from unintentionally omitting the destination tag when sending and receiving payments and other transactions.
## API
### classicAddressToXAddress(classicAddress: string, tag: number | false, test: boolean): string
Convert a classic address and (optional) tag to an X-address. If `tag` is `false`, the returned X-address explicitly indicates that the recipient does not want a tag to be used. If `test` is `true`, consumers of the address will know that the address is intended for use on test network(s) and the address will start with `T`.
```js
> const api = require('ripple-address-codec')
> api.classicAddressToXAddress('rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf', 4294967295)
'XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi'
```
Encode a test address e.g. for use with [Testnet or Devnet](https://xrpl.org/xrp-testnet-faucet.html):
```js
> const api = require('ripple-address-codec')
> api.classicAddressToXAddress('r3SVzk8ApofDJuVBPKdmbbLjWGCCXpBQ2g', 123, true)
'T7oKJ3q7s94kDH6tpkBowhetT1JKfcfdSCmAXbS75iATyLD'
```
### xAddressToClassicAddress(xAddress: string): {classicAddress: string, tag: number | false, test: boolean}
Convert an X-address to a classic address and tag. If the X-address did not have a tag, the returned object's `tag` will be `false`. (Since `0` is a valid tag, instead of `if (tag)`, use `if (tag !== false)` if you want to check for a tag.) If the X-address is intended for use on test network(s), `test` will be `true`; if it is intended for use on the main network (mainnet), `test` will be `false`.
```js
> const api = require('ripple-address-codec')
> api.xAddressToClassicAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi')
{
classicAddress: 'rGWrZyQqhTp9Xu7G5Pkayo7bXjH4k4QYpf',
tag: 4294967295,
test: false
}
```
### isValidXAddress(xAddress: string): boolean
Returns `true` if the provided X-address is valid, or `false` otherwise.
```js
> const api = require('ripple-address-codec')
> api.isValidXAddress('XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi')
true
```
Returns `false` for classic addresses (starting with `r`). To validate a classic address, use `isValidClassicAddress`.
### isValidClassicAddress(address: string): boolean
Check whether a classic address (starting with `r`...) is valid.
Returns `false` for X-addresses (extended addresses). To validate an X-address, use `isValidXAddress`.
### encodeSeed(entropy: Buffer, type: 'ed25519' | 'secp256k1'): string
Encode the given entropy as an XRP Ledger seed (secret). The entropy must be exactly 16 bytes (128 bits). The encoding includes which elliptic curve digital signature algorithm (ECDSA) the seed is intended to be used with. The seed is used to produce the private key.
### decodeSeed(seed: string): object
Decode a seed into an object with its version, type, and bytes.
Return object type:
```
{
version: number[],
bytes: Buffer,
type: string | null
}
```
### encodeAccountID(bytes: Buffer): string
Encode bytes as a classic address (starting with `r`...).
### decodeAccountID(accountId: string): Buffer
Decode a classic address (starting with `r`...) to its raw bytes.
### encodeNodePublic(bytes: Buffer): string
Encode bytes to the XRP Ledger "node public key" format (base58).
This is useful for rippled validators.
### decodeNodePublic(base58string: string): Buffer
Decode an XRP Ledger "node public key" (in base58 format) into its raw bytes.
### encodeAccountPublic(bytes: Buffer): string
Encode a public key, as for payment channels.
### decodeAccountPublic(base58string: string): Buffer
Decode a public key, as for payment channels.
### encodeXAddress(accountId: Buffer, tag: number | false, test: boolean): string
Encode account ID, tag, and network ID to X-address.
`accountId` must be 20 bytes because it is a RIPEMD160 hash, which is 160 bits (160 bits = 20 bytes).
At this time, `tag` must be <= MAX_32_BIT_UNSIGNED_INT (4294967295) as the XRP Ledger only supports 32-bit tags.
If `test` is `true`, this address is intended for use with a test network such as Testnet or Devnet.
### decodeXAddress(xAddress: string): {accountId: Buffer, tag: number | false, test: boolean}
Convert an X-address to its classic address, tag, and network ID.
### Other functions
```js
> var api = require('ripple-address-codec');
> api.decodeSeed('sEdTM1uX8pu2do5XvTnutH6HsouMaM2')
{ version: [ 1, 225, 75 ],
bytes: [ 76, 58, 29, 33, 63, 189, 251, 20, 199, 194, 141, 96, 148, 105, 179, 65 ],
type: 'ed25519' }
> api.decodeSeed('sn259rEFXrQrWyx3Q7XneWcwV6dfL')
{ version: 33,
bytes: [ 207, 45, 227, 120, 251, 221, 126, 46, 232, 125, 72, 109, 251, 90, 123, 255 ],
type: 'secp256k1' }
> api.decodeAccountID('rJrRMgiRgrU6hDF4pgu5DXQdWyPbY35ErN')
[ 186,
142,
120,
98,
110,
228,
44,
65,
180,
109,
70,
195,
4,
141,
243,
161,
195,
200,
112,
114 ]
```
## Tests
Run unit tests with:
npm test
Use `--watch` to run in watch mode, so that when you modify the tests, they are automatically re-run:
npm test -- --watch
Use `--coverage` to generate and display code coverage information:
npm test -- --coverage
This tells jest to output code coverage info in the `./coverage` directory, in addition to showing it on the command line.
## Releases
Use the [ripple-lib release checklist](https://github.com/ripple/ripple-lib/wiki/Release-Checklist), but just use `master` instead of `develop` as this project does not use a develop branch.
## Acknowledgements
This library references and adopts code and standards from the following sources:
- [XLS-5d Standard for Tagged Addresses](https://github.com/xrp-community/standards-drafts/issues/6) by @nbougalis
- [XRPL Tagged Address Codec](https://github.com/xrp-community/xrpl-tagged-address-codec) by @WietseWind
- [X-Address transaction functions](https://github.com/codetsunami/xrpl-tools/tree/master/xaddress-functions) by @codetsunami
[coveralls-image]: https://badgen.net/coveralls/c/github/ripple/ripple-address-codec/master
[coveralls-url]: https://coveralls.io/r/ripple/ripple-address/codec?branch=master
[npm-downloads-image]: https://badgen.net/npm/dm/ripple-address-codec
[npm-url]: https://npmjs.org/package/ripple-address-codec
[npm-version-image]: https://badgen.net/npm/v/ripple-address-codec
[travis-image]: https://badgen.net/travis/ripple/ripple-address-codec/master
[travis-url]: https://travis-ci.org/github/ripple/ripple-address-codec

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