Compare commits

...

75 Commits
1.0.2 ... 1.3.3

Author SHA1 Message Date
Elliot Lee
ae2aed675a v1.3.3 2019-09-10 19:30:11 -07:00
Elliot Lee
1d7cb41218 Add rippleTimeToISO8601.md.ejs 2019-09-04 00:31:02 -07:00
Elliot Lee
76db002eb5 Expand node version compatibility
Previously the library could not be installed with node 12:

https://github.com/ripple/ripple-binary-codec/pull/33
2019-09-04 00:17:53 -07:00
Elliot Lee
ebb64ba177 v1.3.2 2019-09-03 16:43:31 -07:00
Elliot Lee
1a685e2b68 Fix #1032 (#1033)
* Update ripple-address-codec@latest

* Export and document rippleTimeToISO8601
2019-09-03 16:38:56 -07:00
Rome Reginelli
9c561885a1 Docs: update recommended Node ver. (#1031) 2019-08-29 20:34:25 -07:00
Elliot Lee
612e98b198 Release 1.3.1 2019-08-26 13:58:09 -07:00
Elliot Lee
0a41d5ccf1 Upgrade to gulp 4; remove http server (#1030)
* Update gulp version to ^4.0.2 and Gulpfile.js

* Remove http server
2019-08-26 13:50:36 -07:00
Elliot Lee
ba8fe1f32c Update HISTORY - rippled 1.3.1 2019-08-16 21:28:32 -07:00
Elliot Lee
0f840876a5 Update HISTORY 2019-08-16 21:11:02 -07:00
Elliot Lee
ac3900b6f4 Release 1.2.5 and 1.3.0 2019-08-16 21:09:08 -07:00
Elliot Lee
5e138b9937 Sign method - verify accurate encoding (#1026)
* Decode signed transactions and check field integrity

* Add tests (including signing a tx without Flags)

* Update tests to output more descriptive errors on failure

* Update ripple-binary-codec to 0.2.2
2019-08-16 16:22:25 -07:00
Elliot Lee
82d50cd903 Document setCanonicalFlag and export from src/transaction/utils 2019-08-09 10:16:33 -07:00
Elliot Lee
c5b1d4daac Update lodash to ^4.14.136, fix docs typo, update HISTORY.md 2019-08-07 12:20:56 -07:00
Namrata
b4a30d49d8 Support removing a signer list (#1021)
* Make weights an optional field
* Fix #971
2019-07-30 16:48:30 -07:00
Elliot Lee
229360d1b9 README - Update link 2019-07-18 21:50:58 -07:00
Rome Reginelli
d627d362af Merge pull request #1023 from mDuo13/doc_cleanup
Phrasing cleanup in schema descriptions
2019-07-16 15:11:01 -07:00
mDuo13
7ca7a07942 Phrasing cleanup in schema descriptions
- Change 'Ripple address'→'XRP Ledger address'
- Change 'is exclusive with'→'cannot be used with'
2019-07-15 14:26:43 -07:00
dependabot[bot]
09f81fa3cd Bump lodash from 4.17.11 to 4.17.13
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.11 to 4.17.13.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.11...4.17.13)

Signed-off-by: dependabot[bot] <support@github.com>
2019-07-13 13:26:48 -07:00
The XRP Scan Project
b03bf9c7f1 Updated APPLICATIONS.md and added xrpscan
Added xrpscan.com under Data and Visualization section.
2019-06-24 02:03:21 -07:00
Elliot Lee
4d696369fe APIOptions: extend ConnectionOptions (#1018)
Fix #1017
2019-06-21 01:45:47 -07:00
Elliot Lee
bcb80ea5f5 Fix getServerInfo (#1012)
* Return array for serverInfo.load.jobTypes

* Include start/end in invalid range assertion error
2019-06-14 14:57:36 -07:00
Elliot Lee
1be2ee5875 Docs: fix #574 (#1011)
destination.address
2019-06-14 14:57:14 -07:00
Elliot Lee
3554e807df Release 1.2.4 2019-06-06 16:01:24 -07:00
Elliot Lee
5ffbd6e86d Update dependencies (#1007)
* Update dependencies: @types/lodash@4.14.133, mocha-junit-reporter@1.22.0, tslint@5.17.0, nyc

Fix type errors
2019-06-06 15:56:29 -07:00
Elliot Lee
e2572c61cf Add details about transaction fees, master keys, and multi-signing 2019-06-05 00:27:25 -07:00
Elliot Lee
7df2b74d43 Update get-server-info.json 2019-05-27 14:37:38 -07:00
Elliot Lee
f51a69f080 Fix typo 2019-05-22 10:04:43 -07:00
Elliot Lee
c0a2d9fc2b Update README.md 2019-05-16 22:51:22 -07:00
Elliot Lee
51dad19f88 Release 1.2.3 2019-04-30 15:01:54 -07:00
Elliot Lee
3d1a530796 Fix browser builds (#1006)
tsconfig:
- Must set composite: false
- Must set declarationMap: false in order to use declaration: false

json-loader:
- Not needed with webpack >= v2.0.0 and in fact does not work

https-proxy-agent cannot be used in the browser
2019-04-29 23:19:05 -07:00
Elliot Lee
f6a22d2121 No working browser version for 1.2.2
Using `"noEmitOnError": true` in `tsconfig.json` prevents the browser build from being created
2019-04-18 00:53:28 -07:00
Elliot Lee
6f2d448059 Release 1.2.2 2019-04-15 12:30:20 -07:00
Elliot Lee
0d5103a3f3 Use TypeScript project reference (#1002)
* Add *.tsbuildinfo to .gitignore

* Bump versions of dependencies, nyc and yargs

* Drop support for node 9 (EOL 2018-06-30)

https://github.com/nodejs/Release

* Add getTransaction snippet
2019-04-15 11:06:31 -07:00
Elliot Lee
4da80028bf Prevent prepareTransaction from overwriting values in txJSON (#1000)
Fix #997
2019-04-13 11:33:16 -07:00
Daniel Chan
bb40dbde9d Add deliveredAmount as optional field for type Outcome (#996) 2019-04-11 17:13:42 -07:00
Elliot Lee
50fc36ec3e Add "strict": true to tsconfig.json (#994)
- Remove process.browser
2019-04-11 15:48:23 -07:00
Elliot Lee
1abcef73a0 Merge pull request #993 from adrianhopebailie/patch-1
fix: build fails with strict checks
2019-04-08 13:04:27 -07:00
Adrian Hope-Bailie
0d7879b25c fix: build fails with strict checks 2019-03-29 11:48:13 +02:00
Elliot Lee
8278dc5b5b Release 1.2.1 2019-03-23 15:50:26 -07:00
Elliot Lee
c90d486454 Update ripple-binary-codec to 0.2.1 to support tecKILLED 2019-03-23 15:12:22 -07:00
Elliot Lee
35f9b7ec8d Release 1.2.0 2019-03-19 01:28:42 -07:00
Elliot Lee
69e621af86 Remove coveralls from devDependencies 2019-03-19 01:21:36 -07:00
Elliot Lee
0e92e696d4 Remove unused http-server from devDependencies 2019-03-18 16:51:08 -07:00
Elliot Lee
0b1445bfe9 Remove sauce runner 2019-03-18 16:14:21 -07:00
Elliot Lee
db2d7ba1f5 Update mocha to 6.0.2 2019-03-18 16:09:26 -07:00
Elliot Lee
d82703f41b prepareTransaction should not overwrite Sequence (#990)
* Cleans up some code and fixes some type errors

* Clarify how null settings work

* Document updated RippledError

* Updates per review by @mDuo13
2019-03-18 15:55:42 -07:00
Elliot Lee
8213861ab7 Update HISTORY.md 2019-03-13 14:34:31 -07:00
Kincaid O'Neil
a842c380cf fix: add amount to FormattedPaymentChannel type (#989)
* fix: add amount to FormattedPaymentChannel type

* fix: ignore package-lock.json
2019-03-12 16:58:30 -07:00
Elliot Lee
5bf6f1849a Fix typos in docs 2019-03-12 15:27:19 -07:00
Elliot Lee
bfe4877f73 Merge remote-tracking branch 'origin/master' into develop 2019-03-12 15:12:58 -07:00
Elliot Lee
63dcddf6f4 [Docs] Update transaction responses link
List of transaction responses
2019-03-11 12:14:41 -07:00
Rome Reginelli
68735ddb35 Docs: Fix prepareTransaction method specification (#986) 2019-02-11 23:39:41 -08:00
Elliot Lee
1fd9ca7ef2 Use Buffer.from and clean up a few things (#985) 2019-02-07 00:29:59 -08:00
Elliot Lee
2445004333 Change prepare* methods to reject Promise on error (#984)
* Reject Promise on error, update docs, and add tests:
  * preparePayment
  * prepareTrustline
  * prepareOrder
  * prepareOrderCancellation
  * prepareSettings
  * prepareEscrowCreation
  * prepareEscrowExecution
  * prepareCheckCreate
  * prepareCheckCash
  * prepareCheckCancel
  * preparePaymentChannelCreate
  * preparePaymentChannelFund
  * preparePaymentChannelClaim

Note that we can't update mocha to ^5.2.0 because it causes testing to hang indefinitely; this needs to be investigated.
2019-01-29 15:22:18 -08:00
Elliot Lee
dc148bf954 Update HISTORY.md 2018-12-12 17:38:34 -08:00
Elliot Lee
f3c34bd75a Release 1.1.2 2018-12-12 14:55:15 -08:00
Alexandru Chiriac
5419e67dbc GetLedger by hash option (#980)
* update ledger input schema
* include ledgerHash option
2018-12-12 11:02:50 -08:00
Alexandru Chiriac
8d37da0952 Update Submit Response (#978)
* update submit output schema
* update submit response object
2018-12-04 15:35:07 -08:00
Elliot Lee
a8075d98df Add list of applications using ripple-lib (#976) 2018-11-29 16:39:48 -08:00
Elliot Lee
fcc205b85a Release 1.1.1 2018-11-27 15:17:42 -08:00
Elliot Lee
0f5056221f Fix getOrderbook (#970)
* Fix `getOrderbook` (Fix #766)
* Add `formatBidsAndAsks` as a recommended alternative to `getOrderbook`
* Add `renameCounterpartyToIssuer`
2018-11-26 15:25:15 -08:00
Elliot Lee
8384ace746 Add return type for generateAddress (#968)
For TypeScript apps
2018-11-20 15:35:34 -08:00
Elliot Lee
040cabece0 Add comments for accountRootFlags (#962) 2018-11-16 22:34:41 -08:00
Elliot Lee
319a8d6ab2 Fix book-offers test fixture by swapping bids/asks (#966) 2018-10-31 22:48:27 -07:00
Elliot Lee
50a7320886 Release 1.1.0 2018-10-31 16:36:20 -07:00
Elliot Lee
418987476e Add DepositPreauth (#958)
* Expose parseAccountFlags() and add docs
* Add example snippet
* Default to node v10 for nvm
* Maintain existing behavior for getSettings
* Increase max line length from 80 to 120 (ter-max-len)
2018-10-31 16:27:32 -07:00
Elliot Lee
89e4ff328c Apply formatting to book-offers fixture 2018-10-31 16:07:25 -07:00
Elliot Lee
04bf49cb43 Support node 10 (#964)
* Update webpack from 3.11.0 to 3.12.0 and upath from 1.0.4 to 1.1.0
* Run: yarn upgrade gulp
  * See https://github.com/gulpjs/gulp/issues/2162
* Update README
* Travis: test node 10
2018-10-30 14:15:42 -07:00
Elliot Lee
1c017df2a3 Merge pull request #955 from jcperkins12/feature/balanceChanges-TypeCorrection
Type balanceChanges should be array of changes not array with one change
2018-10-24 20:34:03 -07:00
Elliot Lee
5fed1f08e4 Document xrpToDrops, dropsToXrp, iso8601ToRippleTime, schemaValidator, and more
The following methods are available directly under the RippleAPI object,
not under schemaValidator:

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

7
.gitignore vendored
View File

@@ -1,5 +1,9 @@
# .gitignore
# Ignore package locks other than Yarn.
package-lock.json
npm-shrinkwrap.json
# Ignore vim swap files.
*.swp
@@ -54,6 +58,9 @@ npm-debug.log
# Ignore dist folder, built from tsc
dist/
# TypeScript incremental compilation cache
*.tsbuildinfo
# Ignore perf test cache
scripts/cache

2
.nvmrc
View File

@@ -1 +1 @@
v8
v10

View File

@@ -2,7 +2,8 @@ language: node_js
node_js:
- 6
- 8
- 9
- 10
- 11
script:
- yarn compile
- yarn test

123
APPLICATIONS.md Normal file
View File

@@ -0,0 +1,123 @@
# Applications using ripple-lib (RippleAPI)
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!
## Notice (disclaimer)
These sites are independent of Ripple and have not been authorized, endorsed, sponsored or otherwise approved by Ripple or its affiliates.
Warning: Use at your own risk.
## Data and visualizations
- **[Wipple - XRP Intelligence](https://wipple.devnull.network/)**
Monitor the XRP Network in real time and explore historical statistics.
- **[XRP Charts](https://xrpcharts.ripple.com/)** (xrpcharts.ripple.com)
XRP Charts provides information based on public data, including trade volume, top markets, metrics, transactions, and more.
- **[Ripple Live](https://gatehub.net/live)** (gatehub.net/live)
Visualize XRP network transactions.
- **[XRPL Dev. Dashboard](https://xrp.fans/)** (xrp.fans)
Debugging dashboard for `rippled-ws-client-pool`, transaction and query explorer, and transaction signing and submission tool.
- **[XRP Value](http://xrpvalue.com/)**
Real-time XRP price, trades, and orderbook data from the XRP Ledger.
- **[Bithomp - XRPL validators](https://bithomp.com/validators)**
List of XRPL validators, nodes, and testnet validators.
- **[XRP Scan - XRP Ledger explorer](https://http://xrpscan.com)**
XRP Ledger explorer, metrics and analytics.
## Send and request payments
- **[XRP Tip Bot](https://www.xrptipbot.com/)**
A bot that enables users on reddit, Twitter and Discord to send XRP to each other through reddit comments and Twitter tweets.
- **[XRP Text](https://xrptext.com/)**
Send XRP using SMS text messages.
- **[XRParrot](https://xrparrot.com/)** (uses `ripple-address-codec`)
Easy EUR (SEPA) to XRP transfer (currency conversion).
- **[XRP Payment](https://xrpayments.co/)** (xrpayments.co)
Tool for generating a XRP payment request URI in a QR code, with currency converter.
## Wallets and wallet tools
- **[Toast Wallet](https://toastwallet.com/)**
A free, open source XRP Wallet for iOS, Android, Windows, Mac and Linux.
- **[Toastify Ledger](https://github.com/WietseWind/toastify-ledger)** (uses `ripple-keypairs`)
Add a Regular Key to a mnemonic XRP Wallet (e.g. Ledger Nano S) to use the account with a Family Seed (secret).
- **[Bithomp-submit](https://github.com/Bithomp/bithomp-submit)** (GitHub)
A tool to submit an offline-signed XRPL transaction.
- **[Kyte](https://kyteapp.co/)** (kyteapp.co) ([Source](https://github.com/WietseWind/Zerp-Wallet)) (Deprecated)
Web-based XRP wallet.
- **[XRP Vanity Address Generator](https://github.com/WietseWind/xrp-vanity-generator)** (Node.js)
A vanity address is a wallet address containing a few characters you like at the beginning or the end of the wallet address.
- **[XRP Account Mnemonic Recovery](https://github.com/WietseWind/xrp-mnemonic-recovery)** (uses `ripple-keypairs`)
Recover a 24 word mnemonic if one word is wrong or one word is missing.
## Development tools
- **[XRP Test Net Faucet](https://developers.ripple.com/xrp-test-net-faucet.html)**
Get some test funds for development on the test network. The faucet was built using `ripple-lib`.
## Code samples and libraries
- **[ilp-plugin-xrp-paychan](https://github.com/interledgerjs/ilp-plugin-xrp-paychan)**
Send ILP payments using XRP and payment channels (PayChan).
- **[RunKit: WietseWind](https://runkit.com/wietsewind/)**
XRP Ledger code samples for Node.js.
- **[GitHub Gist: WietseWind](https://gist.github.com/WietseWind)**
XRP Ledger code samples for Node.js and the web (mostly).
- **[rippled-ws-client-sign](https://github.com/WietseWind/rippled-ws-client-sign)**
Sign transactions, with support for MultiSign.
- **[ILP-enabled power switch](https://xrpcommunity.blog/raspberry-pi-interledger-xp-powerswitch-howto/)** ([video](https://www.youtube.com/watch?v=c-eS0HQUuJg)) (uses [`moneyd-uplink-xrp`](https://github.com/interledgerjs/moneyd-uplink-xrp))
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 ripple-lib
- **[XRP Stats](https://ledger.exposed/)** (ledger.exposed)
Rich list, live ledger stats and XRP distribution. Visualize escrows and flow of funds.
- **[XRP Vanity](https://xrpvanity.com/)** (xrpvanity.com)
Custom XRP addresses for sale, delivered by SetRegularKey.

View File

@@ -6,15 +6,12 @@ const fs = require('fs');
const path = require('path');
const assert = require('assert');
const gulp = require('gulp');
const rename = require('gulp-rename');
const webpack = require('webpack');
const bump = require('gulp-bump');
const argv = require('yargs').argv;
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var pkg = require('./package.json');
const pkg = require('./package.json');
var uglifyOptions = {
const uglifyOptions = {
mangle: {
reserved: ['_', 'RippleError', 'RippledError', 'UnexpectedError',
'LedgerVersionError', 'ConnectionError', 'NotConnectedError',
@@ -36,7 +33,7 @@ function getWebpackConfig(extension, overrides) {
output: {
library: 'ripple',
path: path.join(__dirname, 'build/'),
filename: ['ripple-', extension].join(pkg.version)
filename: `ripple-${pkg.version}${extension}`
},
plugins: [
new webpack.NormalModuleReplacementPlugin(/^ws$/, './wswrapper'),
@@ -53,12 +50,13 @@ function getWebpackConfig(extension, overrides) {
use: [{
loader: 'ts-loader',
options: {
compilerOptions: {declaration: false}
compilerOptions: {
composite: false,
declaration: false,
declarationMap: false
}
},
}],
}, {
test: /\.json/,
use: 'json-loader',
}]
},
resolve: {
@@ -68,7 +66,7 @@ function getWebpackConfig(extension, overrides) {
return _.assign({}, defaults, overrides);
}
function webpackConfigForWebTest(testFileName, path) {
function webpackConfigForWebTest(testFileName) {
var match = testFileName.match(/\/?([^\/]*)-test.js$/);
if (!match) {
assert(false, 'wrong filename:' + testFileName);
@@ -82,28 +80,13 @@ function webpackConfigForWebTest(testFileName, path) {
entry: testFileName,
output: {
library: match[1].replace(/-/g, '_'),
path: './test-compiled-for-web/' + (path ? path : ''),
path: path.join(__dirname, 'test-compiled-for-web/'),
filename: match[1] + '-test.js'
}
};
return getWebpackConfig('.js', configOverrides);
}
gulp.task('build-tests', function(callback) {
var times = 0;
function done() {
if (++times >= 5) {
callback();
}
}
webpack(webpackConfigForWebTest('./test/rangeset-test.js'), done);
webpack(webpackConfigForWebTest('./test/connection-test.js'), done);
webpack(webpackConfigForWebTest('./test/api-test.js'), done);
webpack(webpackConfigForWebTest('./test/broadcast-api-test.js'), done);
webpack(webpackConfigForWebTest('./test/integration/integration-test.js',
'integration/'), done);
});
function createLink(from, to) {
if (fs.existsSync(to)) {
fs.unlinkSync(to);
@@ -119,11 +102,22 @@ function createBuildLink(callback) {
};
}
gulp.task('build', function(callback) {
webpack(getWebpackConfig('.js'), createBuildLink(callback));
});
function watch(callback) {
gulp.watch('src/*', gulp.series(buildDebug));
callback();
}
gulp.task('build-min', function(callback) {
function build(callback) {
webpack(getWebpackConfig('.js'), createBuildLink(callback));
}
function buildDebug(callback) {
const webpackConfig = getWebpackConfig('-debug.js', {devtool: 'eval'});
webpackConfig.plugins.unshift(new webpack.LoaderOptionsPlugin({debug: true}));
webpack(webpackConfig, callback);
}
function buildMin(callback) {
const webpackConfig = getWebpackConfig('-min.js');
webpackConfig.plugins.push(new UglifyJsPlugin({uglifyOptions}));
webpack(webpackConfig, function() {
@@ -131,86 +125,27 @@ gulp.task('build-min', function(callback) {
'./build/ripple-latest-min.js');
callback();
});
});
gulp.task('build-debug', function(callback) {
const webpackConfig = getWebpackConfig('-debug.js', {devtool: 'eval'});
webpackConfig.plugins.unshift(new webpack.LoaderOptionsPlugin({debug: true}));
webpack(webpackConfig, callback);
});
/**
* Generate a WebPack external for a given unavailable module which replaces
* that module's constructor with an error-thrower
*/
function buildUseError(cons) {
return ('var {<CONS>:function(){throw new Error('
+ '"Class is unavailable in this build: <CONS>")}}')
.replace(new RegExp('<CONS>', 'g'), cons);
}
gulp.task('build-core', function(callback) {
var configOverrides = {
cache: false,
entry: './src/remote.ts',
externals: [{
'./transaction': buildUseError('Transaction'),
'./orderbook': buildUseError('OrderBook'),
'./account': buildUseError('Account'),
'./serializedobject': buildUseError('SerializedObject')
}],
plugins: [
new UglifyJsPlugin()
]
};
webpack(getWebpackConfig('-core.js', configOverrides), callback);
});
gulp.task('bower-build', ['build'], function() {
return gulp.src(['./build/ripple-', '.js'].join(pkg.version))
.pipe(rename('ripple.js'))
.pipe(gulp.dest('./dist/bower'));
});
gulp.task('bower-build-min', ['build-min'], function() {
return gulp.src(['./build/ripple-', '-min.js'].join(pkg.version))
.pipe(rename('ripple-min.js'))
.pipe(gulp.dest('./dist/bower'));
});
gulp.task('bower-build-debug', ['build-debug'], function() {
return gulp.src(['./build/ripple-', '-debug.js'].join(pkg.version))
.pipe(rename('ripple-debug.js'))
.pipe(gulp.dest('./dist/bower'));
});
gulp.task('bower-version', function() {
gulp.src('./dist/bower/bower.json')
.pipe(bump({version: pkg.version}))
.pipe(gulp.dest('./dist/bower'));
});
gulp.task('bower', ['bower-build', 'bower-build-min', 'bower-build-debug',
'bower-version']);
gulp.task('watch', function() {
gulp.watch('src/*', ['build-debug']);
});
gulp.task('version-bump', function() {
if (!argv.type) {
throw new Error('No type found, pass it in using the --type argument');
function buildTests(callback) {
var times = 0;
function done() {
if (++times >= 5) {
callback();
}
}
webpack(webpackConfigForWebTest('./test/rangeset-test.js'), done);
webpack(webpackConfigForWebTest('./test/connection-test.js'), done);
webpack(webpackConfigForWebTest('./test/api-test.js'), done);
webpack(webpackConfigForWebTest('./test/broadcast-api-test.js'), done);
webpack(webpackConfigForWebTest('./test/integration/integration-test.js',
'integration/'), done);
}
gulp.src('./package.json')
.pipe(bump({type: argv.type}))
.pipe(gulp.dest('./'));
});
exports.watch = watch;
exports.build = build;
exports.buildDebug = buildDebug;
exports.buildMin = buildMin;
exports.buildTests = buildTests;
gulp.task('version-beta', function() {
gulp.src('./package.json')
.pipe(bump({version: pkg.version + '-beta'}))
.pipe(gulp.dest('./'));
});
gulp.task('default', ['build', 'build-debug', 'build-min']);
exports.default = gulp.parallel(build, buildDebug, buildMin);

View File

@@ -1,5 +1,351 @@
# ripple-lib Release History
## 1.3.3 (2019-09-10)
* Expand node version compatibility to support Node.js 12 ([ripple-binary-codec#32](https://github.com/ripple/ripple-binary-codec/issues/32))
## 1.3.2 (2019-09-03)
* Export and document `rippleTimeToISO8601()` method
* Add type for isValidAddress (fixes error TS7016, #1032)
* Docs: update recommended Node.js version (#1031)
When using this release with [rippled](https://github.com/ripple/rippled), we recommend using [rippled version 1.3.1](https://github.com/ripple/rippled/releases/tag/1.3.1) or later.
## 1.3.1 (2019-08-26)
* Upgrade to gulp 4 (#1030)
* Remove http server (unused)
* Update dependencies
There are no changes in the browser version with this release. The npm package for Node.js should be slightly smaller.
When using this release with [rippled](https://github.com/ripple/rippled), we recommend using [rippled version 1.3.1](https://github.com/ripple/rippled/releases/tag/1.3.1).
## 1.3.0 (2019-08-16)
### Bug fixes:
* Breaking change: Fix `getServerInfo` (#1012)
Before:
```
{
// ...
"load": {
"jobTypes": {
"0": {"jobType": "untrustedValidation", "perSecond": 10},
"1": {"jobType": "ledgerData", "peakTime": 2, "perSecond": 2},
"2": {"inProgress": 1, "jobType": "clientCommand", "perSecond": 1},
"3": {"jobType": "transaction", "perSecond": 1},
// ...
},
"threads": 6
},
// ...
}
```
After:
```
{
// ...
"load": {
"jobTypes": [
{
"jobType": "untrustedValidation",
"perSecond": 8
},
{
"avgTime": 2,
"jobType": "ledgerData",
"peakTime": 72,
"perSecond": 2
},
{
"inProgress": 1,
"jobType": "clientCommand",
"perSecond": 1
},
{
"jobType": "transaction",
"perSecond": 1
},
// ...
],
"threads": 6
},
// ...
}
```
* Sign method - verify accurate encoding (#1026)
* In previous versions, the following could be encoded incorrectly:
* Amounts of XRP with more than 6 decimal places
* Amounts of XRP drops with any decimal places
* In versions 1.2.5 and 1.3.0, amounts that are invalid in this way will throw an error
* Expand `APIOptions` by extending `ConnectionOptions` (#1018, fixes #1017)
* Fix docs for destination.address (#1011)
### New features:
* Support removing a signer list (#1021)
* Export `setCanonicalFlag` method from `src/transaction/utils`
### Improvements:
* Clean up phrasing in schema descriptions (#1023)
* Improve docs
* Update dependencies
Since this release fixes a bug that could cause transactions to be serialized incorrectly during the signing process, it has also been simultaneously released as version 1.2.5 (patch release).
When using this release with [rippled](https://github.com/ripple/rippled), we recommend using [rippled version 1.3.1](https://github.com/ripple/rippled/releases/tag/1.3.1).
## 1.2.4 (2019-06-06)
* Update README.md
* Clarify docs
* Update dependencies
* Fix typos
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
4f09c056ccc51bc6cf17b128b559112e9c5adf19cc96ac8f9a06faee185697a7 ripple-1.2.4-debug.js
5da1c75a02d76b0b105d98355ee4561f5d5036e8d5d0237efd5960812dcaa1fd ripple-1.2.4-min.js
e147f303e880a65db149d2a5b9183b75814bd8145cd00740bcc4679d867192c8 ripple-1.2.4.js
```
## 1.2.3 (2019-04-30)
* Fix browser builds
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
efb0f29cde94534a015d8a2171abb11b9a4345ba01418bf5b6ab6042a6d51dde ripple-1.2.3-debug.js
b86145c0e30099b966ed8d3830ba25988d72877f1f87044d9954d6707be098ac ripple-1.2.3-min.js
e027d91c7321d41ba94bb1bdc77dcff0107a5fd9eb833c6dbd06f1bbedef3900 ripple-1.2.3.js
```
## 1.2.2 (2019-04-15)
* Prevent `prepareTransaction` from overwriting `Fee` and/or `LastLedgerSequence` (#997)
* Add `deliveredAmount` as optional field for type `Outcome` (#996)
* Fix build failure with TS strict checks (#993)
Minor changes:
* Use TypeScript project references
* Travis: Drop node 9 and add node 11 for testing
* Bump versions of devDependencies
Note: There is no browser version of this release.
## 1.2.1 (2019-03-23)
* Update `ripple-binary-codec` to 0.2.1 to support `tecKILLED`
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
531c2a8f4bf6d6b5bd4afe6a40b6a68a77179a343902cfa4210d7e35b5697af0 ripple-1.2.1-debug.js
201ee99922b16b7e32afb5317ef4bb9facc23b20c272bb5c4ed7010f5d996cab ripple-1.2.1-min.js
c1b984581299bf00e0e3c8ac4e62eadfc9b190bd78a2458a76e59ceb56046148 ripple-1.2.1.js
```
## 1.2.0 (2019-03-19)
This release:
* changes the way you handle errors for the `prepare*` methods.
* improves the `message` field of `RippledError`s.
* allows `Sequence` to be set in the transaction JSON provided to
`prepareTransaction`.
For details, continue reading:
### [BREAKING CHANGE] `prepare*` methods reject the Promise on error
The `prepare*` methods now always reject the Promise when an error occurs, instead of throwing.
Previously, the methods would synchronously throw on validation errors, despite being asynchronous methods that return Promises.
In other words, to handle errors in the past, you would need to use a try/catch block:
```
// OBSOLETE - no need for try/catch anymore
try {
api.preparePayment(address, payment, instructions).then(prepared => {
res.send(prepared.txJSON);
}).catch(error => {
// Handle asynchronous error
});
} catch (error) {
// Handle synchronous error
}
```
Now, you can rely on the Promise's `catch` handler, which is called with the error when the Promise is rejected:
```
api.preparePayment(address, payment, instructions).then(prepared => {
res.send(prepared.txJSON);
}).catch(error => {
// Handle error
});
```
This applies to:
* preparePayment
* prepareTrustline
* prepareOrder
* prepareOrderCancellation
* prepareSettings
* prepareEscrowCreation
* prepareEscrowExecution
* prepareCheckCreate
* prepareCheckCash
* prepareCheckCancel
* preparePaymentChannelCreate
* preparePaymentChannelClaim
* preparePaymentChannelFund
### Improved `RippledError` `message`
Previously, `RippledErrors` (errors from rippled) used rippled's `error` field as the `message`.
Now, the `error_message` field is used as the `message`.
This helps to surface the specific cause of an error.
For example, before:
```
[RippledError(invalidParams, { error: 'invalidParams',
error_code: 31,
error_message: 'Missing field \'account\'.',
id: 3,
request: { command: 'account_info', id: 3 },
status: 'error',
type: 'response' })]
```
After:
```
[RippledError(Missing field 'account'., { error: 'invalidParams',
error_code: 31,
error_message: 'Missing field \'account\'.',
id: 3,
request: { command: 'account_info', id: 3 },
status: 'error',
type: 'response' })]
```
In this case, you can see at a glance that `account` is the missing field.
The `error` field is still available in `errorObject.data.error`.
When `error_message` is not set (as with e.g. error 'entryNotFound'), the `error` field is used as the `message`.
### [BUG FIX] `prepareTransaction` does not overwrite the `Sequence` field
The `prepareTransaction` method now allows `Sequence` to be set in the Transaction JSON object, instead of overwriting it with the account's expected sequence based on the state of the ledger.
Previously, you had to use the `sequence` field in the `instructions` object to manually set a transaction's sequence number.
### New in rippled 1.2.1
As this is the first release of ripple-lib following the release of rippled 1.2.1, we would like to highlight the following API improvements:
1. The [`delivered_amount` field](https://developers.ripple.com/partial-payments.html#the-delivered-amount-field) has been added to the `ledger` method, and to transaction subscriptions.
api.getLedger({includeTransactions: true, includeAllData: true, ledgerVersion: 17718771}).then(...)
You can also call `ledger` directly:
request('ledger', {...}).then(...)
2. [Support for Ed25519 seeds encoded using ripple-lib](https://github.com/ripple/rippled/pull/2734)
You have access to these improvements when you use a rippled server running version 1.2.1 or later. At the time of writing, we recommend using rippled version **1.2.2** or later.
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
13021fe3efbdd59faf68597b0b18204b39847b285cca82f84c737e3d19922cc2 ripple-1.2.0-debug.js
0070225e731afd8c2c0a0976111ebf326c19a96ee1549368de9f016abdd53d2f ripple-1.2.0-min.js
d440268397c03ad5137a3294e53a07b959ef93cd23b1990d6f82621c4776ba9f ripple-1.2.0.js
```
## 1.1.2 (2018-12-12)
+ Update `submit` response (#978)
+ Includes the full object returned by rippled, while keeping the existing
fields for backward compatibility
+ Add `getLedger` option for ledger hash (#980)
+ Use the `ledgerHash` option to get a specific ledger by hash
Thanks to @alexchiriac for the contributions in this release.
When using `ripple-lib` with `rippled`, we recommend using `rippled` version
1.1.2 or later.
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
e6cc52395d0c3e205263777ba2e528e50f4d1f84bb4b16763a3bf7f5fcc290f5 ripple-1.1.2-debug.js
82df879bc2970e0e4fd161975a99448b4859b0cde751d8ea34e9f51d672090b9 ripple-1.1.2-min.js
12f56330dc71bba8ac3004025cbc9698413a0c619df302dda105b31228a67319 ripple-1.1.2.js
```
## 1.1.1 (2018-11-27)
+ Fix `getOrderbook` offer sorting (#970)
+ **BREAKING CHANGE:** The ordering of offers returned by `getOrderbook` has
been changed so that offers with the best quality are sorted first
+ Add new helper methods for working with the `rippled` APIs:
+ `formatBidsAndAsks`: Takes offers and returns a formatted order book object
with bids and asks
+ `renameCounterpartyToIssuer`: Takes an object and renames the `counterparty`
field to `issuer`
+ TypeScript: Add return type for `generateAddress` (#968)
When using `ripple-lib` with `rippled`, we recommend using `rippled` version 1.1.1 or
later.
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
e151900e49bb5482b02bef5b0b1542ea586076363b072ae616f6d4d2f7f5b8a1 ripple-1.1.1-debug.js
6aee3757b29de285f361e20862261090033c07a13fd09f4a3cc4c097b6e84b55 ripple-1.1.1-min.js
bea4a889fb9ee4092324c6667490ea66469bdde869ddc1aaddf5e9d12b0cf091 ripple-1.1.1.js
```
## 1.1.0 (2018-10-31)
+ Add support for Node.js v10 LTS (#964)
+ Add [DepositPreauth](https://developers.ripple.com/depositauth.html) ([#958](https://github.com/ripple/ripple-lib/pull/958))
+ In `FormattedTransactionType`, the `Outcome`'s `balanceChanges` property had
the wrong type. This is now fixed (#955)
+ Add/fix docs for: xrpToDrops, dropsToXrp, iso8601ToRippleTime, schemaValidator, isValidAddress, isValidSecret, deriveKeypair, deriveAddress
The SHA-256 checksums for the browser version of this release can be found
below.
```
% shasum -a 256 *
e1d742092b3c0fcee97a875e18db4baeab3bbc82f08b96e883ee188c5f0cfb37 ripple-1.1.0-debug.js
f28921f57a133678dcb3cb54c497626bd76b1f953d22d61f3ddca31c8947d552 ripple-1.1.0-min.js
3696871a80c1102635699994adcaf00cdfdfcff5014fc2eba3d8f8d8437c8f91 ripple-1.1.0.js
```
## 1.0.2 (2018-10-16)
+ Fix #954: Exclude SendMax from all XRP to XRP payments (thanks @jefftrudeau)
@@ -273,6 +619,9 @@ below.
## 0.19.0 (2018-03-02)
+ [Add support for Checks](https://github.com/ripple/ripple-lib/pull/853)
+ **CheckCreate** adds a check entry to the ledger. The check is a promise from the source of the check that the destination of the check may cash the check and receive up to the SendMax specified on the check. The check may have an (optional) expiration, after which the check may no longer be cashed.
+ **CheckCancel** removes the check from the ledger without transferring funds. Either the check's source or destination can cancel the check at any time. After a check has expired, any account can cancel the check.
+ **CheckCash** is a request by the destination of the check to transfer a requested amount of funds, up to the check's SendMax, from the source to the destination. The destination may receive less than the SendMax due to transfer fees.
+ [Add support for the Deposit Authorization account root flag](https://github.com/ripple/ripple-lib/pull/852)
+ [Generate .ts.d TypeScript declaration files](https://github.com/ripple/ripple-lib/pull/851)
+ [Improve documentation of getTransactions params](https://github.com/ripple/ripple-lib/pull/856)

View File

@@ -2,32 +2,36 @@
A JavaScript API for interacting with the XRP Ledger
[![Circle CI](https://circleci.com/gh/ripple/ripple-lib/tree/develop.svg?style=svg)](https://circleci.com/gh/ripple/ripple-lib/tree/develop) [![Coverage Status](https://coveralls.io/repos/ripple/ripple-lib/badge.png?branch=develop)](https://coveralls.io/r/ripple/ripple-lib?branch=develop)
[![NPM](https://nodei.co/npm/ripple-lib.png)](https://www.npmjs.org/package/ripple-lib)
### Features
+ Connect to a `rippled` server from Node.js or a web browser
+ Issue [rippled API](https://ripple.com/build/rippled-apis/) requests
+ Listen to events on the XRP Ledger (transaction, ledger, etc.)
+ 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
## Getting Started
See also: [RippleAPI Beginners Guide](https://ripple.com/build/rippleapi-beginners-guide/)
See also: [RippleAPI Beginners Guide](https://xrpl.org/get-started-with-rippleapi-for-javascript.html)
You can use `npm`, but we recommend using `yarn` for the added assurance provided by `yarn.lock`.
### Requirements
+ [Yarn Installation Instructions](https://yarnpkg.com/en/docs/install)
+ **[Node v10](https://nodejs.org/)** is recommended. Other versions may work but are not frequently tested.
+ **[Yarn](https://yarnpkg.com/)** is recommended. `npm` may work but we use `yarn.lock`.
Install `ripple-lib`:
### Install
In an existing project (with `package.json`), install `ripple-lib`:
```
$ yarn add ripple-lib
```
Then see the [documentation](https://github.com/ripple/ripple-lib/blob/develop/docs/index.md) and [code samples](https://github.com/ripple/ripple-lib/tree/develop/docs/samples).
**What is ripple-lib used for?** Here's a [list of applications](APPLICATIONS.md) that use `ripple-lib`. Open a PR to add your app or project to the list!
### Mailing Lists
We have a low-traffic mailing list for announcements of new ripple-lib releases. (About 1 email per week)
@@ -54,7 +58,7 @@ $ yarn build
Gulp will [output](./Gulpfile.js) the resulting JS files in `./build/`.
For more details, see the `scripts` in `package.json`.
For details, see the `scripts` in `package.json`.
## Running Tests
@@ -62,12 +66,13 @@ For more details, see the `scripts` in `package.json`.
2. `cd` into the repository and install dependencies with `yarn install`
3. `yarn test`
Also, run `yarn lint` to lint the code with `tslint`.
## Generating Documentation
The continuous integration tests require that the documentation stays up-to-date. If you make changes to the JSON schemas, fixtures, or documentation sources, you must update the documentation by running `yarn run docgen`.
`npm` may be used instead of `yarn` in the commands above.
## More Information
+ [Ripple Developer Center](https://ripple.com/build/)
+ [RippleAPI Reference](https://developers.ripple.com/rippleapi-reference.html) - XRP Ledger Dev Portal
+ [XRP Ledger Dev Portal](https://developers.ripple.com/)

View File

@@ -1,9 +0,0 @@
/**
* This is an extension of Node's `process` object to include the browser
* property, which is added by webpack.
*/
interface AmbiguousProcess extends NodeJS.Process {
browser?: true
}
declare var process: AmbiguousProcess;

File diff suppressed because it is too large Load Diff

View File

@@ -26,7 +26,7 @@ api.connect().then(() => {
}).catch(console.error);
```
RippleAPI is designed to work in [Node.js](https://nodejs.org) version **6.11.3**. RippleAPI may work on older Node.js versions if you use [Babel](https://babeljs.io/) for [ECMAScript 6](https://babeljs.io/docs/learn-es2015/) support.
RippleAPI is designed to work in [Node.js](https://nodejs.org) version 6 or higher. Ripple recommends Node.js v10 LTS.
The code samples in this documentation are written with ECMAScript 6 (ES6) features, but `RippleAPI` also works with ECMAScript 5 (ES5). Regardless of whether you use ES5 or ES6, the methods that return Promises return [ES6-style promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

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. (Note: the structures of `bids` and `asks` are identical.)
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 method [book_offers](https://ripple.com/build/rippled-apis/#book-offers).
### 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

@@ -4,6 +4,10 @@
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') %>
@@ -14,9 +18,7 @@ This method returns a promise that resolves with an object with the following st
<%- renderSchema('output/get-orderbook.json') %>
### Raw order data
(Requires ripple-lib 0.22.0 or higher.) The response includes a `data` property containing the raw order data. This may include `owner_funds`, `Flags`, and other fields.
**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 method [book_offers](https://ripple.com/build/rippled-apis/#book-offers).

View File

@@ -8,6 +8,11 @@
<% 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 %>
@@ -28,6 +33,8 @@
<% include getAccountObjects.md.ejs %>
<% include getPaymentChannel.md.ejs %>
<% include getLedger.md.ejs %>
<% include parseAccountFlags.md.ejs %>
<% include prepareTransaction.md.ejs %>
<% include preparePayment.md.ejs %>
<% include prepareTrustline.md.ejs %>
<% include prepareOrder.md.ejs %>
@@ -53,4 +60,9 @@
<% 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,27 @@
## iso8601ToRippleTime
`iso8601ToRippleTime(iso8601: string): number`
This method parses a string representation of a date, and returns the number of seconds since the "Ripple Epoch" of January 1, 2000 (00:00 UTC).
The Ripple Epoch is 946684800 seconds after the Unix Epoch.
This method is useful for creating timestamps to use with the rippled APIs. The rippled APIs represent time as an unsigned integer of the number of seconds since the Ripple Epoch.
### Parameters
`iso8601`: A string representing a date and time. This string is parsed using JavaScript's `Date.parse()` method.
### Return Value
The number of seconds since the Ripple Epoch.
### Example
```javascript
api.iso8601ToRippleTime('2017-02-17T15:04:57Z');
```
```json
540659097
```

View File

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

View File

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

View File

@@ -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 similar to 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' }
```

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

View File

@@ -7,6 +7,10 @@ sign(txJSON: string, keypair: object, options: object): {signedTransaction: stri
Sign a prepared transaction. The signed transaction must subsequently be [submitted](#submit).
This method can sign any of [the transaction types supported by ripple-binary-codec](https://github.com/ripple/ripple-binary-codec/blob/cfcde79c19c359e9a0466d7bc3dc9a3aef47bb99/src/enums/definitions.json#L1637). When a new transaction type is added to the XRP Ledger, it will be unrecognized until `ripple-binary-codec` is updated. If you try to sign an unrecognized transaction type, this method throws an error similar to the following:
`Error: [TRANSACTION_TYPE] is not a valid name or ordinal for TransactionType`
### Parameters
<%- renderSchema("input/sign.json") %>

View File

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

View File

@@ -15,7 +15,7 @@ Type | Description
[escrowCancellation](#escrow-cancellation) | An `escrowCancellation` transaction unlocks the funds in an escrow and sends them back to the creator of the escrow, but it will only work after the escrow expires.
[escrowExecution](#escrow-execution) | An `escrowExecution` transaction unlocks the funds in an escrow and sends them to the destination of the escrow, but it will only work if the cryptographic condition is provided.
[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 unreedemed Check, removing it from the ledger without sending any money.
[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.
@@ -43,17 +43,19 @@ Executing a transaction with `RippleAPI` requires the following four steps:
## Transaction Fees
Every transaction must destroy a small amount of XRP as a cost to send the transaction. 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.
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` will be 20 drops × (1 + 2 Signatures) = 60 drops. See [Transaction Cost](https://developers.ripple.com/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 will never succeeed 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.
We recommend that you specify a `maxLedgerVersion` so that you can quickly determine that a failed transaction will 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

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

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "ripple-lib",
"version": "1.0.2",
"version": "1.3.3",
"license": "ISC",
"description": "A JavaScript API for interacting with Ripple in Node.js and the browser",
"files": [
@@ -10,68 +10,60 @@
"main": "dist/npm/",
"types": "dist/npm/index.d.ts",
"browser": {
"ws": "./dist/npm/common/wswrapper.js"
"ws": "./dist/npm/common/wswrapper.js",
"https-proxy-agent": false
},
"directories": {
"test": "test"
},
"dependencies": {
"@types/lodash": "^4.14.85",
"@types/lodash": "^4.14.136",
"@types/ws": "^3.2.0",
"bignumber.js": "^4.1.0",
"https-proxy-agent": "2.2.1",
"jsonschema": "1.2.2",
"lodash": "^4.17.4",
"ripple-address-codec": "^2.0.1",
"ripple-binary-codec": "^0.1.13",
"ripple-hashes": "^0.3.1",
"ripple-address-codec": "^3.0.4",
"ripple-binary-codec": "^0.2.4",
"ripple-hashes": "^0.3.4",
"ripple-keypairs": "^0.10.1",
"ripple-lib-transactionparser": "0.7.1",
"ws": "^3.3.1"
},
"devDependencies": {
"@types/node": "^8.0.53",
"@types/node": "11.13.0",
"assert-diff": "^1.0.1",
"coveralls": "^2.13.1",
"doctoc": "^0.15.0",
"ejs": "^2.3.4",
"eventemitter2": "^0.4.14",
"gulp": "^3.8.10",
"gulp-bump": "^0.1.13",
"gulp-rename": "^1.2.0",
"http-server": "^0.8.5",
"jayson": "^1.2.2",
"gulp": "^4.0.2",
"json-loader": "^0.5.2",
"json-schema-to-markdown-table": "^0.4.0",
"mocha": "^2.1.0",
"mocha-in-sauce": "^0.0.1",
"mocha": "6.1.3",
"mocha-junit-reporter": "^1.9.1",
"null-loader": "^0.1.1",
"nyc": "^11.3.0",
"source-map-support": "^0.5.0",
"nyc": "^14.1.1",
"source-map-support": "0.5.12",
"ts-loader": "^3.2.0",
"ts-node": "^3.3.0",
"ts-node": "8.0.3",
"tslint": "^5.8.0",
"tslint-eslint-rules": "^4.1.1",
"typescript": "2.9.2",
"typescript": "3.4.2",
"uglifyjs-webpack-plugin": "^1.1.4",
"webpack": "^3.10.0",
"yargs": "^8.0.2"
"webpack": "3.12.0"
},
"scripts": {
"build": "gulp",
"doctoc": "doctoc docs/index.md --title '# RippleAPI Reference' --github --maxlevel 2",
"docgen": "node --harmony scripts/build_docs.js",
"clean": "rm -rf dist/npm",
"compile": "mkdir -p dist/npm/common && cp -r src/common/schemas dist/npm/common/ && tsc",
"compile": "mkdir -p dist/npm/common/js && cp -r src/common/js/ dist/npm/common/js/ && mkdir -p dist/npm/common && cp -r src/common/schemas dist/npm/common/ && tsc --build",
"watch": "tsc -w",
"prepublish": "npm run clean && npm run compile && npm run build",
"test": "nyc mocha",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"test": "TS_NODE_PROJECT=src/tsconfig.json nyc mocha --exit",
"lint": "tslint -p ./",
"perf": "./scripts/perf_test.sh",
"start": "node scripts/http.js",
"sauce": "node scripts/sauce-runner.js"
"start": "node scripts/http.js"
},
"repository": {
"type": "git",

View File

@@ -16,7 +16,7 @@ unittest() {
# test "src"
mocha test --reporter mocha-junit-reporter --reporter-options mochaFile=$CIRCLE_TEST_REPORTS/test-results.xml
yarn test --coverage
yarn run coveralls
#yarn run coveralls
# test compiled version in "dist/npm"
$(npm bin)/babel -D --optional runtime --ignore "**/node_modules/**" -d test-compiled/ test/
@@ -45,7 +45,6 @@ unittest() {
integrationtest() {
mocha test/integration/integration-test.js
mocha test/integration/http-integration-test.js
# run integration tests in PhantomJS
#gulp build-tests build-min

View File

@@ -1,16 +0,0 @@
'use strict';
const createHTTPServer = require('../dist/npm/http').createHTTPServer;
const port = 5990;
const serverUrl = 'wss://s1.ripple.com';
function main() {
const server = createHTTPServer({server: serverUrl}, port);
server.start().then(() => {
console.log('Server started on port ' + String(port));
});
}
main();

View File

@@ -1,100 +0,0 @@
const _ = require('lodash');
const MochaSauce = require('mocha-in-sauce');
const testUrl = 'http://testripple.circleci.com:8080/test/saucerunner.html';
function main() {
// uncomment for more debug info
// process.env.DEBUG = '*';
// configure
const config = {
name: 'RippleAPI',
host: 'localhost',
port: 4445,
maxDuration: 180000,
// the current build name (optional)
build: Date.now(),
url: testUrl,
runSauceConnect: true
};
if (process.env.CIRCLE_BUILD_NUM) {
config.build = process.env.CIRCLE_BUILD_NUM;
config.tags = [process.env.CIRCLE_BRANCH, process.env.CIRCLE_SHA1];
config.tunnelIdentifier = process.env.CIRCLE_BUILD_NUM;
}
const sauce = new MochaSauce(config);
sauce.concurrency(5);
// setup what browsers to test with
sauce.browser({browserName: 'firefox', platform: 'Linux',
version: '43'});
sauce.browser({browserName: 'firefox', platform: 'Windows 8.1',
version: '43'});
sauce.browser({browserName: 'firefox', platform: 'OS X 10.11',
version: '43'});
sauce.browser({browserName: 'safari', platform: 'OS X 10.11',
version: '9'});
sauce.browser({browserName: 'safari', platform: 'OS X 10.10',
version: '8'});
sauce.browser({browserName: 'safari', platform: 'OS X 10.9',
version: '7'});
sauce.browser({browserName: 'chrome', platform: 'OS X 10.11',
version: '47'});
sauce.browser({browserName: 'chrome', platform: 'Linux',
version: '47'});
sauce.browser({browserName: 'chrome', platform: 'Windows 8.1',
version: '47'});
sauce.browser({browserName: 'internet explorer', platform: 'Windows 10',
version: '11'});
sauce.browser({browserName: 'MicrosoftEdge', platform: 'Windows 10',
version: '20'});
sauce.on('init', function(browser) {
console.log(' init : %s %s', browser.browserName, browser.platform);
});
sauce.on('start', function(browser) {
console.log(' start : %s %s', browser.browserName, browser.platform);
});
sauce.on('end', function(browser, res) {
console.log(' end : %s %s : %d failures', browser.browserName,
browser.platform, res && res.failures);
});
sauce.on('connected', sauceConnectProcess => {
sauceConnectProcess.on('exit', function(code, /* signal */) {
if (code > 0) {
console.log('something wrong - exiting');
process.exit();
} else {
console.log('normal tunnel exit');
}
});
});
sauce.start(function(err, res) {
let failure = false;
if (err) {
console.log('Error starting Sauce');
console.error(err);
process.exitCode = 2;
} else {
console.log('-------------- done --------------');
failure = _.some(res, 'failures');
console.log('Tests are failed:', failure);
if (failure) {
process.exitCode = 1;
}
}
});
}
main();

View File

@@ -0,0 +1,17 @@
import {RippleAPI} from '../../dist/npm'
const api = new RippleAPI({
server: 'wss://s.altnet.rippletest.net:51233'
})
getTransaction()
async function getTransaction() {
await api.connect()
const ledger = await api.getLedger({includeTransactions: true})
console.log(ledger)
const tx = await api.getTransaction(ledger.transactionHashes[0])
console.log(tx)
console.log('deliveredAmount:', tx.outcome.deliveredAmount)
process.exit(0)
}

View File

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

13
snippets/tsconfig.json Normal file
View File

@@ -0,0 +1,13 @@
{
"extends": "../tsconfig-base",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"references": [
{ "path": "../src" }
],
"include": [
"./src/**/*.ts"
]
}

View File

@@ -5,6 +5,7 @@ import {
validate,
xrpToDrops,
dropsToXrp,
rippleTimeToISO8601,
iso8601ToRippleTime,
txFlags
} from './common'
@@ -22,8 +23,9 @@ import getBalances from './ledger/balances'
import getBalanceSheet from './ledger/balance-sheet'
import getPaths from './ledger/pathfind'
import getOrders from './ledger/orders'
import getOrderbook from './ledger/orderbook'
import getSettings from './ledger/settings'
import {getOrderbook,
formatBidsAndAsks} from './ledger/orderbook'
import {getSettings, parseAccountFlags} from './ledger/settings'
import getAccountInfo from './ledger/accountinfo'
import getAccountObjects from './ledger/accountobjects'
import getPaymentChannel from './ledger/payment-channel'
@@ -69,10 +71,11 @@ import * as ledgerUtils from './ledger/utils'
import * as transactionUtils from './transaction/utils'
import * as schemaValidator from './common/schema-validator'
import {getServerInfo, getFee} from './common/serverinfo'
import {clamp} from './ledger/utils'
import {Instructions, Prepare} from './transaction/types'
import {clamp, renameCounterpartyToIssuer} from './ledger/utils'
import {TransactionJSON, Instructions, Prepare} from './transaction/types'
import {ConnectionOptions} from './common/connection'
export type APIOptions = {
export interface APIOptions extends ConnectionOptions {
server?: string,
feeCushion?: number,
maxFeeXRP?: string,
@@ -114,6 +117,9 @@ class RippleAPI extends EventEmitter {
schemaValidator
}
static renameCounterpartyToIssuer = renameCounterpartyToIssuer
static formatBidsAndAsks = formatBidsAndAsks
constructor(options: APIOptions = {}) {
super()
validate.apiOptions(options)
@@ -206,7 +212,7 @@ class RippleAPI extends EventEmitter {
*
* You can later submit the transaction with `submit()`.
*/
async prepareTransaction(txJSON: object, instructions: Instructions = {}):
async prepareTransaction(txJSON: TransactionJSON, instructions: Instructions = {}):
Promise<Prepare> {
return transactionUtils.prepareTransaction(txJSON, this, instructions)
}
@@ -295,13 +301,14 @@ class RippleAPI extends EventEmitter {
getBalances = getBalances
getBalanceSheet = getBalanceSheet
getPaths = getPaths
getOrders = getOrders
getOrderbook = getOrderbook
getOrders = getOrders
getSettings = getSettings
getAccountInfo = getAccountInfo
getAccountObjects = getAccountObjects
getPaymentChannel = getPaymentChannel
getLedger = getLedger
parseAccountFlags = parseAccountFlags
preparePayment = preparePayment
prepareTrustline = prepareTrustline
@@ -331,6 +338,7 @@ class RippleAPI extends EventEmitter {
xrpToDrops = xrpToDrops
dropsToXrp = dropsToXrp
rippleTimeToISO8601 = rippleTimeToISO8601
iso8601ToRippleTime = iso8601ToRippleTime
txFlags = txFlags

View File

@@ -202,16 +202,10 @@ class Connection extends EventEmitter {
this._updateLedgerVersions(data)
this._updateFees(data)
this._rebindOnUnxpectedClose()
this._rebindOnUnexpectedClose()
this._retry = 0
this._ws.on('error', error => {
// TODO: "type" does not exist on official error type, safe to remove?
if (process.browser && error && (<any>error).type === 'error') {
// we are in browser, ignore error - `close` event will be fired
// after error
return
}
this.emit('error', 'websocket', error.message, error)
})
@@ -222,7 +216,7 @@ class Connection extends EventEmitter {
})
}
_rebindOnUnxpectedClose() {
_rebindOnUnexpectedClose() {
if (this._onUnexpectedCloseBound) {
this._ws.removeListener('close', this._onUnexpectedCloseBound)
}
@@ -231,7 +225,7 @@ class Connection extends EventEmitter {
this._ws.once('close', this._onUnexpectedCloseBound)
}
_unbindOnUnxpectedClose() {
_unbindOnUnexpectedClose() {
if (this._onUnexpectedCloseBound) {
this._ws.removeListener('close', this._onUnexpectedCloseBound)
}
@@ -240,7 +234,7 @@ class Connection extends EventEmitter {
_onOpenError(reject, error) {
this._onOpenErrorBound = null
this._unbindOnUnxpectedClose()
this._unbindOnUnexpectedClose()
reject(new NotConnectedError(error.message, error))
}
@@ -268,7 +262,7 @@ class Connection extends EventEmitter {
options.agent = new HttpsProxyAgent(proxyOptions)
}
if (this._authorization !== undefined) {
const base64 = new Buffer(this._authorization).toString('base64')
const base64 = Buffer.from(this._authorization).toString('base64')
options.headers = {Authorization: `Basic ${base64}`}
}
const optionsOverrides = _.omitBy({
@@ -287,7 +281,7 @@ class Connection extends EventEmitter {
return websocket
}
connect() {
connect(): Promise<void> {
this._clearReconnectTimer()
return new Promise((resolve, reject) => {
if (!this._url) {
@@ -322,11 +316,11 @@ class Connection extends EventEmitter {
})
}
disconnect() {
disconnect(): Promise<void> {
return this._disconnect(true)
}
_disconnect(calledByUser) {
_disconnect(calledByUser): Promise<void> {
if (calledByUser) {
this._clearReconnectTimer()
this._retry = 0
@@ -445,7 +439,7 @@ class Connection extends EventEmitter {
this.once(eventName, response => {
if (response.status === 'error') {
_reject(new RippledError(response.error, response))
_reject(new RippledError(response.error_message || response.error, response))
} else if (response.status === 'success') {
_resolve(response.result)
} else {

View File

@@ -1,16 +1,51 @@
import {txFlagIndices} from './txflags'
// Ordering from https://developers.ripple.com/accountroot.html
const accountRootFlags = {
PasswordSpent: 0x00010000, // password set fee is spent
RequireDestTag: 0x00020000, // require a DestinationTag for payments
RequireAuth: 0x00040000, // require authorization to hold IOUs
DepositAuth: 0x01000000, // require account to auth deposits
DisallowXRP: 0x00080000, // disallow sending XRP
DisableMaster: 0x00100000, // force regular key
NoFreeze: 0x00200000, // permanently disallowed freezing trustlines
GlobalFreeze: 0x00400000, // trustlines globally frozen
DefaultRipple: 0x00800000
// lsfDefaultRipple:
// Enable rippling on trust lines by default.
// Required for issuing addresses; discouraged for others.
DefaultRipple: 0x00800000,
// lsfDepositAuth:
// Require account to auth deposits.
// This account can only receive funds from transactions it sends,
// or preauthorized accounts.
DepositAuth: 0x01000000,
// lsfDisableMaster:
// Force regular key.
// Disallows use of the master key.
DisableMaster: 0x00100000,
// lsfDisallowXRP:
// Disallow sending XRP.
// Not enforced by rippled; client applications should check.
DisallowXRP: 0x00080000,
// lsfGlobalFreeze:
// Trustlines globally frozen.
GlobalFreeze: 0x00400000,
// lsfNoFreeze:
// Permanently disallowed freezing trustlines.
// Once enabled, cannot be disabled.
NoFreeze: 0x00200000,
// lsfPasswordSpent:
// Password set fee is spent.
// The account has used its free SetRegularKey transaction.
PasswordSpent: 0x00010000,
// lsfRequireAuth:
// Require authorization to hold IOUs (issuances).
RequireAuth: 0x00040000,
// lsfRequireDestTag:
// Require a DestinationTag for incoming payments.
RequireDestTag: 0x00020000
}
const AccountFlags = {

File diff suppressed because it is too large Load Diff

View File

@@ -35,7 +35,7 @@ class RangeSet {
}
addRange(start: number, end: number) {
assert(start <= end, 'invalid range')
assert(start <= end, `invalid range ${start} <= ${end}`)
this.ranges = mergeIntervals(this.ranges.concat([[start, end]]))
}

View File

@@ -6,7 +6,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The Ripple address of the account to get the balance sheet of."
"description": "The XRP Ledger address of the account to get the balance sheet of."
},
"options": {
"properties": {

View File

@@ -7,6 +7,10 @@
"options": {
"description": "Options affecting what ledger and how much data to return.",
"properties": {
"ledgerHash": {
"type": "string",
"description": "Get ledger data for this historical ledger hash."
},
"ledgerVersion": {
"$ref": "ledgerVersion",
"description": "Get ledger data for this historical ledger version."

View File

@@ -6,7 +6,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The Ripple address of the account to get open orders for."
"description": "The XRP Ledger address of the account to get open orders for."
},
"options": {
"description": "Options that determine what orders will be returned.",

View File

@@ -12,7 +12,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The Ripple address of the account where funds will come from."
"description": "The XRP Ledger address of the account where funds will come from."
},
"amount": {
"$ref": "laxAmount",
@@ -49,7 +49,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The address to send to."
"description": "An address representing the destination of the transaction."
},
"amount": {
"$ref": "laxLaxAmount",

View File

@@ -10,14 +10,14 @@
"properties": {
"minLedgerVersion": {
"$ref": "ledgerVersion",
"description": "The lowest ledger version to search."
"description": "The lowest ledger version to search. This must be an integer greater than 0, or one of the following strings: 'validated', 'closed', 'current'."
},
"maxLedgerVersion": {
"$ref": "ledgerVersion",
"description": "The highest ledger version to search"
"description": "The highest ledger version to search. This must be an integer greater than 0, or one of the following strings: 'validated', 'closed', 'current'."
},
"includeRawTransaction": {
"description": "Include raw transaction data. For advanced users; exercise caution when interpreting this data. "
"description": "Include raw transaction data. For advanced users; exercise caution when interpreting this data."
}
},
"additionalProperties": false

View File

@@ -22,7 +22,7 @@
},
"minLedgerVersion": {
"$ref": "ledgerVersion",
"description": "Return only transactions in this ledger verion or higher."
"description": "Return only transactions in this ledger version or higher."
},
"maxLedgerVersion": {
"$ref": "ledgerVersion",

View File

@@ -10,7 +10,7 @@
"secret": {
"type": "string",
"format": "secret",
"description": "The secret of the account that is initiating the transaction. (This field is exclusive with keypair)."
"description": "The secret of the account that is initiating the transaction. (This field cannot be used with keypair)."
},
"keypair": {
"type": "object",
@@ -24,7 +24,7 @@
"description": "The uppercase hexadecimal representation of the secp256k1 or Ed25519 public key."
}
},
"description": "The private and public key of the account that is initiating the transaction. (This field is exclusive with secret).",
"description": "The private and public key of the account that is initiating the transaction. (This field cannot be used with secret).",
"required": ["privateKey", "publicKey"],
"additionalProperties": false
},

View File

@@ -13,7 +13,7 @@
"$ref": "currency"
},
"counterparty": {
"description": "The Ripple address of the account that owes or is owed the funds (omitted if `currency` is \"XRP\" or \"drops\")",
"description": "The XRP Ledger address of the account that owes or is owed the funds (omitted if `currency` is \"XRP\" or \"drops\")",
"$ref": "address"
}
},

View File

@@ -14,7 +14,7 @@
"$ref": "currency"
},
"counterparty": {
"description": "The Ripple address of the account that owes or is owed the funds.",
"description": "The XRP Ledger address of the account that owes or is owed the funds.",
"$ref": "address"
}
},

View File

@@ -6,7 +6,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The address to receive at."
"description": "An address representing the destination of the transaction."
},
"tag": {"$ref": "tag"}
},

View File

@@ -5,7 +5,7 @@
"properties": {
"address": {
"$ref": "address",
"description": "The address to receive at."
"description": "An address representing the destination of the transaction."
},
"amount": {
"$ref": "laxAmount",

View File

@@ -10,7 +10,7 @@
"$ref": "sequence"
},
"fee": {
"description": "An exact fee to pay for the transaction. See [Transaction Fees](#transaction-fees) for more information.",
"description": "An exact fee to pay for the transaction, before multiplying for multi-signed transactions. See [Transaction Fees](#transaction-fees) for more information.",
"$ref": "value"
},
"maxFee": {
@@ -18,7 +18,7 @@
"$ref": "value"
},
"maxLedgerVersion": {
"description": "The highest ledger version that the transaction can be included in. If this option and `maxLedgerVersionOffset` are both omitted, the `maxLedgerVersion` option will default to 3 greater than the current validated ledger version (equivalent to `maxLedgerVersionOffset=3`). Use `null` to not set a maximum ledger version.",
"description": "The highest ledger version that the transaction can be included in. If this option and `maxLedgerVersionOffset` are both omitted, the `maxLedgerVersion` option will default to 3 greater than the current validated ledger version (equivalent to `maxLedgerVersionOffset=3`). Use `null` to not set a maximum ledger version. If not null, this must be an integer greater than 0, or one of the following strings: 'validated', 'closed', 'current'.",
"oneOf": [
{"$ref": "ledgerVersion"},
{"type": "null"}

View File

@@ -9,7 +9,7 @@
},
"maxAmount": {
"$ref": "laxAmount",
"description": "The maximum amount to send. (This field is exclusive with source.amount)"
"description": "The maximum amount to send. (This field cannot be used with source.amount)"
},
"tag": {"$ref": "tag"}
},

View File

@@ -5,11 +5,11 @@
"properties": {
"address": {
"$ref": "address",
"description": "The address to send to."
"description": "An address representing the destination of the transaction."
},
"minAmount": {
"$ref": "laxAmount",
"description": "The minimum amount to be delivered. (This field is exclusive with destination.amount)"
"description": "The minimum amount to be delivered. (This field cannot be used with destination.amount)"
},
"tag": {"$ref": "tag"}
},

View File

@@ -13,7 +13,7 @@
},
"disableMasterKey": {
"type": "boolean",
"description": "Disallows use of the master key to sign transactions for this account."
"description": "Disallows use of the master key to sign transactions for this account. To disable the master key, you must authorize the transaction by signing it with the master key pair. You cannot use a regular key pair or a multi-signature. You can re-enable the master key pair using a regular key pair or multi-signature. See [AccountSet](https://developers.ripple.com/accountset.html)."
},
"disallowIncomingXRP": {
"type": "boolean",
@@ -94,7 +94,7 @@
"maxItems": 8
}
},
"required": ["threshold", "weights"],
"required": ["threshold"],
"additionalProperties": false
},
"transferRate": {

View File

@@ -9,7 +9,7 @@
},
"amount": {
"$ref": "laxAmount",
"description": "An exact amount to send. If the counterparty is not specified, amounts with any counterparty may be used. (This field is exclusive with source.maxAmount)"
"description": "An exact amount to send. If the counterparty is not specified, amounts with any counterparty may be used. (This field cannot be used with source.maxAmount)"
},
"tag": {"$ref": "tag"}
},

View File

@@ -1,11 +1,12 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "tx",
"link": "https://ripple.com/build/transactions/",
"title": "tx-json",
"link": "https://developers.ripple.com/transaction-formats.html",
"description": "An object in rippled txJSON format",
"type": "object",
"properties": {
"Account": {"$ref": "address"}
"Account": {"$ref": "address"},
"TransactionType": {"type": "string"}
},
"required": ["Account"]
"required": ["Account", "TransactionType"]
}

View File

@@ -31,7 +31,7 @@
},
"threads": {
"type": "number",
"description": "*(Admin only)* The number of threads in the servers main job pool, performing various Ripple Network operations."
"description": "*(Admin only)* The number of threads in the servers main job pool, performing various operations."
}
},
"required": ["jobTypes", "threads"]
@@ -70,7 +70,7 @@
},
"serverState": {
"type": "string",
"description": "A string indicating to what extent the server is participating in the network. See [Possible Server States](https://ripple.com/build/rippled-apis/#possible-server-states) for more details.",
"description": "A string indicating to what extent the server is participating in the network. See [Possible Server States](https://developers.ripple.com/rippled-server-states.html) for more details.",
"enum": ["disconnected", "connected", "syncing", "tracking", "full", "validating", "proposing"]
},
"validatedLedger": {

View File

@@ -6,7 +6,7 @@
"properties": {
"result": {
"type": "string",
"description": "Result code returned by rippled. See [Transaction Results](https://ripple.com/build/transactions/#full-transaction-response-list) for a complete list."
"description": "Result code returned by rippled. See [Transaction Results](https://developers.ripple.com/transaction-results.html) for a complete list."
},
"timestamp": {
"type": "string",

View File

@@ -14,7 +14,7 @@
"properties": {
"fee": {
"$ref": "value",
"description": "An exact fee to pay for the transaction. See [Transaction Fees](#transaction-fees) for more information."
"description": "The fee to pay for the transaction. See [Transaction Fees](#transaction-fees) for more information. For multi-signed transactions, this fee will be multiplied by (N+1), where N is the number of signatures you plan to provide."
},
"sequence": {
"$ref": "sequence",
@@ -25,7 +25,7 @@
{"$ref": "ledgerVersion"},
{"type": "null"}
],
"description": "The highest ledger version that the transaction can be included in. Set to `null` if there is no maximum."
"description": "The highest ledger version that the transaction can be included in. Set to `null` if there is no maximum. If not null, this must be an integer greater than 0, or one of the following strings: 'validated', 'closed', 'current'."
}
},
"additionalProperties": false,

View File

@@ -5,13 +5,33 @@
"properties": {
"resultCode": {
"type": "string",
"description": "The result code returned by rippled. [List of transaction responses](https://ripple.com/build/transactions/#full-transaction-response-list)"
"description": "Deprecated: Use `engine_result` instead."
},
"resultMessage": {
"type": "string",
"description": "Human-readable explanation of the status of the transaction."
"description": "Deprecated: Use `engine_result_message` instead."
},
"engine_result": {
"type": "string",
"description": "Code indicating the preliminary result of the transaction, for example `tesSUCCESS`. [List of transaction responses](https://developers.ripple.com/transaction-results.html)"
},
"engine_result_code": {
"type": "integer",
"description": "Numeric code indicating the preliminary result of the transaction, directly correlated to `engine_result`"
},
"engine_result_message": {
"type": "string",
"description": "Human-readable explanation of the transaction's preliminary result."
},
"tx_blob": {
"type": "string",
"description": "The complete transaction in hex string format."
},
"tx_json": {
"$ref": "tx-json",
"description": "The complete transaction in JSON format."
}
},
"required": ["resultCode", "resultMessage"],
"required": ["resultCode", "resultMessage", "engine_result", "engine_result_code", "engine_result_message", "tx_blob", "tx_json"],
"additionalProperties": false
}

View File

@@ -1,7 +1,7 @@
import * as _ from 'lodash'
import {convertKeysFromSnakeCaseToCamelCase} from './utils'
import BigNumber from 'bignumber.js'
import {RippleAPI} from '../index'
import {RippleAPI} from '..'
export type GetServerInfoResponse = {
buildVersion: string,

View File

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

View File

@@ -1,8 +1,5 @@
export type Amount = {
value: string,
currency: string,
issuer?: string,
counterparty?: string
export interface Amount extends Issue {
value: string
}
@@ -21,8 +18,8 @@ export interface TakerRequestAmount {
/**
* A currency-counterparty pair, or just currency if it's XRP.
*/
export type Issue = {
currency: string,
issuer?: string,
export interface Issue {
currency: string
issuer?: string
counterparty?: string
}

View File

@@ -18,5 +18,6 @@ export interface Ledger {
hash?: string,
close_flags?: number,
parent_close_time?: number,
accountState?: any[]
accountState?: any[],
validated?: boolean
}

View File

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

View File

@@ -103,6 +103,7 @@ function toRippledAmount(amount: Amount): RippledAmount {
function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
if (typeof obj === 'object') {
const accumulator = Array.isArray(obj) ? [] : {}
let newKey
return _.reduce(obj, (result, value, key) => {
newKey = key
@@ -113,7 +114,7 @@ function convertKeysFromSnakeCaseToCamelCase(obj: any): any {
}
result[newKey] = convertKeysFromSnakeCaseToCamelCase(value)
return result
}, {})
}, accumulator)
}
return obj
}
@@ -125,7 +126,6 @@ function removeUndefined<T extends object>(obj: T): T {
/**
* @param {Number} rpepoch (seconds since 1/1/2000 GMT)
* @return {Number} ms since unix epoch
*
*/
function rippleToUnixTimestamp(rpepoch: number): number {
return (rpepoch + 0x386D4380) * 1000
@@ -133,7 +133,7 @@ function rippleToUnixTimestamp(rpepoch: number): number {
/**
* @param {Number|Date} timestamp (ms since unix epoch)
* @return {Number} seconds since ripple epoch ( 1/1/2000 GMT)
* @return {Number} seconds since ripple epoch (1/1/2000 GMT)
*/
function unixToRippleTimestamp(timestamp: number): number {
return Math.round(timestamp / 1000) - 0x386D4380
@@ -143,6 +143,10 @@ function rippleTimeToISO8601(rippleTime: number): string {
return new Date(rippleToUnixTimestamp(rippleTime)).toISOString()
}
/**
* @param {string} iso8601 international standard date format
* @return {number} seconds since ripple epoch (1/1/2000 GMT)
*/
function iso8601ToRippleTime(iso8601: string): number {
return unixToRippleTimestamp(Date.parse(iso8601))
}

View File

@@ -124,3 +124,6 @@ _.partial(schemaValidate, 'api-options')
export const instructions =
_.partial(schemaValidate, 'instructions')
export const tx_json =
_.partial(schemaValidate, 'tx-json')

View File

@@ -1,84 +0,0 @@
/* eslint-disable new-cap */
import * as assert from 'assert'
import * as _ from 'lodash'
import * as jayson from 'jayson'
import {RippleAPI} from './api'
/* istanbul ignore next */
function createHTTPServer(options, httpPort) {
const rippleAPI = new RippleAPI(options)
const methodNames = _.filter(_.keys(RippleAPI.prototype), k => {
return typeof RippleAPI.prototype[k] === 'function'
&& k !== 'connect'
&& k !== 'disconnect'
&& k !== 'constructor'
&& k !== 'RippleAPI'
})
function applyPromiseWithCallback(fnName, callback, args_) {
try {
let args = args_
if (!_.isArray(args_)) {
const fnParameters = jayson.Utils.getParameterNames(rippleAPI[fnName])
args = fnParameters.map(name => args_[name])
const defaultArgs = _.omit(args_, fnParameters)
assert(_.size(defaultArgs) <= 1,
'Function must have no more than one default argument')
if (_.size(defaultArgs) > 0) {
args.push(defaultArgs[_.keys(defaultArgs)[0]])
}
}
Promise.resolve(rippleAPI[fnName](...args))
.then(res => callback(null, res))
.catch(err => {
callback({code: 99, message: err.message, data: {name: err.name}})
})
} catch (err) {
callback({code: 99, message: err.message, data: {name: err.name}})
}
}
const methods = {}
_.forEach(methodNames, fn => {
methods[fn] = jayson.Method((args, cb) => {
applyPromiseWithCallback(fn, cb, args)
}, {collect: true})
})
const server = jayson.server(methods)
let httpServer = null
return {
server: server,
start: function() {
if (httpServer !== null) {
return Promise.reject('Already started')
}
return new Promise(resolve => {
rippleAPI.connect().then(() => {
httpServer = server.http()
httpServer.listen(httpPort, resolve)
})
})
},
stop: function() {
if (httpServer === null) {
return Promise.reject('Not started')
}
return new Promise(resolve => {
rippleAPI.disconnect()
httpServer.close(() => {
httpServer = null
resolve()
})
})
}
}
}
export {
createHTTPServer
}

View File

@@ -1,5 +1,5 @@
import {validate, removeUndefined, dropsToXrp} from '../common'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import {AccountInfoResponse} from '../common/types/commands/account_info'
export type GetAccountInfoOptions = {

View File

@@ -1,5 +1,5 @@
import {removeUndefined} from '../common'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import {
GetAccountObjectsOptions,
AccountObjectsResponse

View File

@@ -2,7 +2,7 @@ import * as _ from 'lodash'
import {validate} from '../common'
import {Amount} from '../common/types/objects'
import {ensureLedgerVersion} from './utils'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
export type BalanceSheetOptions = {
excludeAddresses?: Array<string>,

View File

@@ -3,6 +3,7 @@ import {validate} from '../common'
import {Connection} from '../common'
import {GetTrustlinesOptions} from './trustlines'
import {FormattedTrustline} from '../common/types/objects/trustlines'
import {RippleAPI} from '..'
export type Balance = {
@@ -47,7 +48,7 @@ function getLedgerVersionHelper(connection: Connection, optionValue?: number
return connection.getLedgerVersion()
}
function getBalances(address: string, options: GetTrustlinesOptions = {}
function getBalances(this: RippleAPI, address: string, options: GetTrustlinesOptions = {}
): Promise<GetBalances> {
validate.getTrustlines({address, options})

View File

@@ -1,8 +1,9 @@
import {validate} from '../common'
import {FormattedLedger, parseLedger} from './parse/ledger'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
export type GetLedgerOptions = {
ledgerHash?: string,
ledgerVersion?: number,
includeAllData?: boolean,
includeTransactions?: boolean,
@@ -16,6 +17,7 @@ async function getLedger(
validate.getLedger({options})
// 2. Make Request
const response = await this.request('ledger', {
ledger_hash: options.ledgerHash,
ledger_index: options.ledgerVersion || 'validated',
expand: options.includeAllData,
transactions: options.includeTransactions,
@@ -25,5 +27,4 @@ async function getLedger(
return parseLedger(response.ledger)
}
export default getLedger

View File

@@ -5,16 +5,17 @@ import {
FormattedOrderbookOrder
} from './parse/orderbook-order'
import {validate} from '../common'
import {Amount, Issue} from '../common/types/objects'
import {Issue} from '../common/types/objects'
import {BookOffer} from '../common/types/commands'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import BigNumber from 'bignumber.js'
export type FormattedOrderbook = {
bids: FormattedOrderbookOrder[],
asks: FormattedOrderbookOrder[]
}
function isSameIssue(a: Amount, b: Amount) {
function isSameIssue(a: Issue, b: Issue) {
return a.currency === b.currency && a.counterparty === b.counterparty
}
@@ -33,12 +34,12 @@ function flipOrder(order: FormattedOrderbookOrder) {
return _.merge({}, order, {specification: newSpecification})
}
function alignOrder(base: Amount, order: FormattedOrderbookOrder) {
function alignOrder(base: Issue, order: FormattedOrderbookOrder): FormattedOrderbookOrder {
const quantity = order.specification.quantity
return isSameIssue(quantity, base) ? order : flipOrder(order)
}
function formatBidsAndAsks(
export function formatBidsAndAsks(
orderbook: OrderbookInfo, offers: BookOffer[]) {
// the "base" currency is the currency that you are buying or selling
// the "counter" is the currency that the "base" is priced in
@@ -50,7 +51,10 @@ function formatBidsAndAsks(
// for asks: lowest quality => lowest totalPrice/quantity => lowest price
// for both bids and asks, lowest quality is closest to mid-market
// we sort the orders so that earlier orders are closer to mid-market
const orders = _.sortBy(offers, 'quality').map(parseOrderbookOrder)
const orders = offers.sort((a, b) => {
return (new BigNumber(a.quality)).comparedTo(b.quality)
}).map(parseOrderbookOrder)
const alignedOrders = orders.map(_.partial(alignOrder, orderbook.base))
const bids = alignedOrders.filter(_.partial(directionFilter, 'buy'))
const asks = alignedOrders.filter(_.partial(directionFilter, 'sell'))
@@ -87,7 +91,7 @@ export type OrderbookInfo = {
counter: Issue
}
export default async function getOrderbook(
export async function getOrderbook(
this: RippleAPI,
address: string,
orderbook: OrderbookInfo,
@@ -105,5 +109,6 @@ export default async function getOrderbook(
directOfferResult => directOfferResult.offers)
const reverseOffers = _.flatMap(reverseOfferResults,
reverseOfferResult => reverseOfferResult.offers)
return formatBidsAndAsks(orderbook, [...directOffers, ...reverseOffers])
return formatBidsAndAsks(orderbook,
[...directOffers, ...reverseOffers])
}

View File

@@ -1,7 +1,7 @@
import * as _ from 'lodash'
import {validate} from '../common'
import {FormattedAccountOrder, parseAccountOrder} from './parse/account-order'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import {AccountOffersResponse} from '../common/types/commands'
export type GetOrdersOptions = {

View File

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

View File

@@ -5,7 +5,7 @@ const AccountFields = constants.AccountFields
function parseField(info, value) {
if (info.encoding === 'hex' && !info.length) { // e.g. "domain"
return new Buffer(value, 'hex').toString('ascii')
return Buffer.from(value, 'hex').toString('ascii')
}
if (info.shift) {
return (new BigNumber(value)).shift(-info.shift).toNumber()

View File

@@ -59,6 +59,11 @@ function parseState(state) {
return {rawState: JSON.stringify(state)}
}
/**
* @param {Ledger} ledger must be a *closed* ledger with valid `close_time` and `parent_close_time`
* @returns {FormattedLedger} formatted ledger
* @throws RangeError: Invalid time value (rippleTimeToISO8601)
*/
export function parseLedger(ledger: Ledger): FormattedLedger {
const ledgerVersion = parseInt(ledger.ledger_index || ledger.seqNum, 10)
return removeUndefined(Object.assign(

View File

@@ -4,6 +4,7 @@ import {PayChannelLedgerEntry} from '../../common/types/objects'
export type FormattedPaymentChannel = {
account: string,
amount: string,
balance: string,
publicKey: string,
destination: string,

View File

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

View File

@@ -122,7 +122,7 @@ function parseOutcome(tx: any): any|undefined {
}
function hexToString(hex: string): string|undefined {
return hex ? new Buffer(hex, 'hex').toString('utf-8') : undefined
return hex ? Buffer.from(hex, 'hex').toString('utf-8') : undefined
}
function parseMemos(tx: any): Array<Memo>|undefined {

View File

@@ -14,6 +14,7 @@ import {RippledAmount, Amount} from '../common/types/objects'
import {
GetPaths, PathFind, RippledPathsResponse, PathFindRequest
} from './pathfind-types'
import {RippleAPI} from '..'
const NotFoundError = errors.NotFoundError
const ValidationError = errors.ValidationError
@@ -46,9 +47,7 @@ function requestPathFind(connection: Connection, pathfind: PathFind
&& !request.destination_amount.issuer) {
// Convert blank issuer to sender's address
// (Ripple convention for 'any issuer')
// https://ripple.com/build/transactions/
// #special-issuer-values-for-sendmax-and-amount
// https://ripple.com/build/ripple-rest/#counterparties-in-payments
// https://developers.ripple.com/payment.html#special-issuer-values-for-sendmax-and-amount
request.destination_amount.issuer = request.destination_account
}
if (pathfind.source.currencies && pathfind.source.currencies.length > 0) {
@@ -149,7 +148,7 @@ function formatResponse(pathfind: PathFind, paths: RippledPathsResponse) {
}
}
function getPaths(pathfind: PathFind): Promise<GetPaths> {
function getPaths(this: RippleAPI, pathfind: PathFind): Promise<GetPaths> {
validate.getPaths({pathfind})
const address = pathfind.source.address

View File

@@ -3,7 +3,7 @@ import {
FormattedPaymentChannel
} from './parse/payment-channel'
import {validate, errors} from '../common'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import {LedgerEntryResponse} from '../common/types/commands'
const NotFoundError = errors.NotFoundError

View File

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

View File

@@ -4,6 +4,8 @@ import parseTransaction from './parse/transaction'
import {validate, errors} from '../common'
import {Connection} from '../common'
import {FormattedTransactionType} from '../transaction/types'
import {RippledError} from '../common/errors'
import {RippleAPI} from '..'
export type TransactionOptions = {
minLedgerVersion?: number,
@@ -59,10 +61,16 @@ function isTransactionInRange(tx: any, options: TransactionOptions) {
}
function convertError(connection: Connection, options: TransactionOptions,
error: Error
error: RippledError
): Promise<Error> {
const _error = (error.message === 'txnNotFound') ?
new errors.NotFoundError('Transaction not found') : error
let shouldUseNotFoundError = false
if ((error.data && error.data.error === 'txnNotFound') || error.message === 'txnNotFound') {
shouldUseNotFoundError = true
}
// In the future, we should deprecate this error, instead passing through the one from rippled.
const _error = shouldUseNotFoundError ? new errors.NotFoundError('Transaction not found') : error
if (_error instanceof errors.NotFoundError) {
return utils.hasCompleteLedgerRange(connection, options.minLedgerVersion,
options.maxLedgerVersion).then(hasCompleteLedgerRange => {
@@ -89,7 +97,7 @@ function formatResponse(options: TransactionOptions, tx: TransactionResponse
return parseTransaction(tx, options.includeRawTransaction)
}
async function getTransaction(id: string, options: TransactionOptions = {}
async function getTransaction(this: RippleAPI, id: string, options: TransactionOptions = {}
): Promise<FormattedTransactionType> {
validate.getTransaction({id, options})
const _options = await utils.ensureLedgerVersion.call(this, options)

View File

@@ -6,6 +6,7 @@ import parseTransaction from './parse/transaction'
import getTransaction from './transaction'
import {validate, errors, Connection} from '../common'
import {FormattedTransactionType} from '../transaction/types'
import {RippleAPI} from '..'
export type TransactionsOptions = {
@@ -162,7 +163,7 @@ function getTransactionsInternal(connection: Connection, address: string,
return utils.getRecursive(getter, options.limit).then(format)
}
function getTransactions(address: string, options: TransactionsOptions = {}
function getTransactions(this: RippleAPI, address: string, options: TransactionsOptions = {}
): Promise<GetTransactionsResponse> {
validate.getTransactions({address, options})

View File

@@ -1,7 +1,7 @@
import * as _ from 'lodash'
import {validate} from '../common'
import parseAccountTrustline from './parse/account-trustline'
import {RippleAPI} from '../api'
import {RippleAPI} from '..'
import {FormattedTrustline} from '../common/types/objects/trustlines'
export type GetTrustlinesOptions = {

View File

@@ -4,6 +4,7 @@ import * as common from '../common'
import {Connection} from '../common'
import {FormattedTransactionType} from '../transaction/types'
import {Issue} from '../common/types/objects'
import {RippleAPI} from '..'
export type RecursiveData = {
marker: string,
@@ -76,7 +77,7 @@ function signum(num) {
* Order two rippled transactions based on their ledger_index.
* If two transactions took place in the same ledger, sort
* them based on TransactionIndex
* See: https://ripple.com/build/transactions/
* See: https://developers.ripple.com/transaction-metadata.html
*/
function compareTransactions(
first: FormattedTransactionType, second: FormattedTransactionType
@@ -105,7 +106,7 @@ function isPendingLedgerVersion(connection: Connection,
ledgerVersion < (maxLedgerVersion || 0))
}
function ensureLedgerVersion(options: any
function ensureLedgerVersion(this: RippleAPI, options: any
): Promise<object> {
if (Boolean(options) && options.ledgerVersion !== undefined &&
options.ledgerVersion !== null

View File

@@ -4,4 +4,3 @@ export {
deriveKeypair,
deriveAddress
}

View File

@@ -2,17 +2,18 @@ import keypairs = require('ripple-keypairs')
import * as common from '../common'
const {errors, validate} = common
function generateAddress(options?: object): object {
const secret = keypairs.generateSeed(options)
const keypair = keypairs.deriveKeypair(secret)
const address = keypairs.deriveAddress(keypair.publicKey)
return {secret, address}
export type GeneratedAddress = {
secret: string,
address: string
}
function generateAddressAPI(options?: object): object {
function generateAddressAPI(options?: any): GeneratedAddress {
validate.generateAddress({options})
try {
return generateAddress(options)
const secret = keypairs.generateSeed(options)
const keypair = keypairs.deriveKeypair(secret)
const address = keypairs.deriveAddress(keypair.publicKey)
return {secret, address}
} catch (error) {
throw new errors.UnexpectedError(error.message)
}

View File

@@ -1,18 +1,19 @@
import * as common from '../common'
import {RippleAPI} from '..'
function isConnected(): boolean {
function isConnected(this: RippleAPI): boolean {
return this.connection.isConnected()
}
function getLedgerVersion(): Promise<number> {
function getLedgerVersion(this: RippleAPI): Promise<number> {
return this.connection.getLedgerVersion()
}
function connect(): Promise<void> {
function connect(this: RippleAPI): Promise<void> {
return this.connection.connect()
}
function disconnect(): Promise<void> {
function disconnect(this: RippleAPI): Promise<void> {
return this.connection.disconnect()
}

View File

@@ -1,14 +1,15 @@
import * as utils from './utils'
import {TransactionJSON, prepareTransaction} from './utils'
import {validate} from '../common'
import {Instructions, Prepare} from './types'
import {RippleAPI} from '..'
export type CheckCancel = {
export type CheckCancelParameters = {
checkID: string
}
function createCheckCancelTransaction(account: string,
cancel: CheckCancel
): object {
cancel: CheckCancelParameters
): TransactionJSON {
const txJSON = {
Account: account,
TransactionType: 'CheckCancel',
@@ -18,15 +19,19 @@ function createCheckCancelTransaction(account: string,
return txJSON
}
function prepareCheckCancel(address: string,
checkCancel: CheckCancel,
function prepareCheckCancel(this: RippleAPI, address: string,
checkCancel: CheckCancelParameters,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareCheckCancel(
{address, checkCancel, instructions})
const txJSON = createCheckCancelTransaction(
address, checkCancel)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareCheckCancel(
{address, checkCancel, instructions})
const txJSON = createCheckCancelTransaction(
address, checkCancel)
return prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareCheckCancel

View File

@@ -2,18 +2,19 @@ import * as utils from './utils'
const ValidationError = utils.common.errors.ValidationError
const toRippledAmount = utils.common.toRippledAmount
import {validate} from '../common'
import {Instructions, Prepare} from './types'
import {Instructions, Prepare, TransactionJSON} from './types'
import {Amount} from '../common/types/objects'
import {RippleAPI} from '..'
export type CheckCash = {
export type CheckCashParameters = {
checkID: string,
amount?: Amount,
deliverMin?: Amount
}
function createCheckCashTransaction(account: string,
checkCash: CheckCash
): object {
checkCash: CheckCashParameters
): TransactionJSON {
if (checkCash.amount && checkCash.deliverMin) {
throw new ValidationError('"amount" and "deliverMin" properties on '
+ 'CheckCash are mutually exclusive')
@@ -36,15 +37,19 @@ function createCheckCashTransaction(account: string,
return txJSON
}
function prepareCheckCash(address: string,
checkCash: CheckCash,
function prepareCheckCash(this: RippleAPI, address: string,
checkCash: CheckCashParameters,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareCheckCash(
{address, checkCash, instructions})
const txJSON = createCheckCashTransaction(
address, checkCash)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareCheckCash(
{address, checkCash, instructions})
const txJSON = createCheckCashTransaction(
address, checkCash)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareCheckCash

View File

@@ -1,10 +1,11 @@
import * as utils from './utils'
const toRippledAmount = utils.common.toRippledAmount
import {validate, iso8601ToRippleTime} from '../common'
import {Instructions, Prepare} from './types'
import {Instructions, Prepare, TransactionJSON} from './types'
import {Amount} from '../common/types/objects'
import {RippleAPI} from '..'
export type CheckCreate = {
export type CheckCreateParameters = {
destination: string,
sendMax: Amount,
destinationTag?: number,
@@ -13,8 +14,8 @@ export type CheckCreate = {
}
function createCheckCreateTransaction(account: string,
check: CheckCreate
): object {
check: CheckCreateParameters
): TransactionJSON {
const txJSON: any = {
Account: account,
TransactionType: 'CheckCreate',
@@ -37,15 +38,19 @@ function createCheckCreateTransaction(account: string,
return txJSON
}
function prepareCheckCreate(address: string,
checkCreate: CheckCreate,
function prepareCheckCreate(this: RippleAPI, address: string,
checkCreate: CheckCreateParameters,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareCheckCreate(
{address, checkCreate, instructions})
const txJSON = createCheckCreateTransaction(
address, checkCreate)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareCheckCreate(
{address, checkCreate, instructions})
const txJSON = createCheckCreateTransaction(
address, checkCreate)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareCheckCreate

View File

@@ -7,7 +7,7 @@ import {validate} from '../common'
import {computeBinaryTransactionHash} from 'ripple-hashes'
function addressToBigNumber(address) {
const hex = (new Buffer(decodeAddress(address))).toString('hex')
const hex = (Buffer.from(decodeAddress(address))).toString('hex')
return new BigNumber(hex, 16)
}

View File

@@ -1,18 +1,21 @@
import * as _ from 'lodash'
import * as utils from './utils'
const validate = utils.common.validate
import {Instructions, Prepare} from './types'
import {Instructions, Prepare, TransactionJSON} from './types'
import {Memo} from '../common/types/objects'
import {RippleAPI} from '..'
export type EscrowCancellation = {
owner: string,
escrowSequence: number,
// TODO: This ripple-lib memo format should be deprecated in favor of rippled's format.
// If necessary, expose a public method for converting between the two formats.
memos?: Array<Memo>
}
function createEscrowCancellationTransaction(account: string,
payment: EscrowCancellation
): object {
): TransactionJSON {
const txJSON: any = {
TransactionType: 'EscrowCancel',
Account: account,
@@ -20,12 +23,12 @@ function createEscrowCancellationTransaction(account: string,
OfferSequence: payment.escrowSequence
}
if (payment.memos !== undefined) {
txJSON.Memos = _.map(payment.memos, utils.convertMemo)
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
return txJSON
}
function prepareEscrowCancellation(address: string,
function prepareEscrowCancellation(this: RippleAPI, address: string,
escrowCancellation: EscrowCancellation,
instructions: Instructions = {}
): Promise<Prepare> {

View File

@@ -1,9 +1,9 @@
import * as _ from 'lodash'
import * as utils from './utils'
import {validate, iso8601ToRippleTime, xrpToDrops} from '../common'
const ValidationError = utils.common.errors.ValidationError
import {Instructions, Prepare} from './types'
import {Instructions, Prepare, TransactionJSON} from './types'
import {Memo} from '../common/types/objects'
import {RippleAPI} from '..'
export type EscrowCreation = {
amount: string,
@@ -18,7 +18,7 @@ export type EscrowCreation = {
function createEscrowCreationTransaction(account: string,
payment: EscrowCreation
): object {
): TransactionJSON {
const txJSON: any = {
TransactionType: 'EscrowCreate',
Account: account,
@@ -42,7 +42,7 @@ function createEscrowCreationTransaction(account: string,
txJSON.DestinationTag = payment.destinationTag
}
if (payment.memos !== undefined) {
txJSON.Memos = _.map(payment.memos, utils.convertMemo)
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
if (Boolean(payment.allowCancelAfter) && Boolean(payment.allowExecuteAfter) &&
txJSON.CancelAfter <= txJSON.FinishAfter) {
@@ -52,15 +52,19 @@ function createEscrowCreationTransaction(account: string,
return txJSON
}
function prepareEscrowCreation(address: string,
function prepareEscrowCreation(this: RippleAPI, address: string,
escrowCreation: EscrowCreation,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareEscrowCreation(
{address, escrowCreation, instructions})
const txJSON = createEscrowCreationTransaction(
address, escrowCreation)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareEscrowCreation(
{address, escrowCreation, instructions})
const txJSON = createEscrowCreationTransaction(
address, escrowCreation)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareEscrowCreation

View File

@@ -1,9 +1,9 @@
import * as _ from 'lodash'
import * as utils from './utils'
const validate = utils.common.validate
const ValidationError = utils.common.errors.ValidationError
import {Instructions, Prepare} from './types'
import {Memo} from '../common/types/objects'
import {RippleAPI} from '..'
export type EscrowExecution = {
owner: string,
@@ -15,7 +15,7 @@ export type EscrowExecution = {
function createEscrowExecutionTransaction(account: string,
payment: EscrowExecution
): object {
): utils.TransactionJSON {
const txJSON: any = {
TransactionType: 'EscrowFinish',
Account: account,
@@ -35,20 +35,24 @@ function createEscrowExecutionTransaction(account: string,
txJSON.Fulfillment = payment.fulfillment
}
if (payment.memos !== undefined) {
txJSON.Memos = _.map(payment.memos, utils.convertMemo)
txJSON.Memos = payment.memos.map(utils.convertMemo)
}
return txJSON
}
function prepareEscrowExecution(address: string,
function prepareEscrowExecution(this: RippleAPI, address: string,
escrowExecution: EscrowExecution,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareEscrowExecution(
{address, escrowExecution, instructions})
const txJSON = createEscrowExecutionTransaction(
address, escrowExecution)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareEscrowExecution(
{address, escrowExecution, instructions})
const txJSON = createEscrowExecutionTransaction(
address, escrowExecution)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareEscrowExecution

View File

@@ -1,9 +1,9 @@
import * as _ from 'lodash'
import * as utils from './utils'
const offerFlags = utils.common.txFlags.OfferCreate
import {validate, iso8601ToRippleTime} from '../common'
import {Instructions, Prepare, OfferCreateTransaction} from './types'
import {FormattedOrderSpecification} from '../common/types/objects/index'
import {RippleAPI} from '..'
function createOrderTransaction(
account: string, order: FormattedOrderSpecification
@@ -39,17 +39,21 @@ function createOrderTransaction(
txJSON.OfferSequence = order.orderToReplace
}
if (order.memos !== undefined) {
txJSON.Memos = _.map(order.memos, utils.convertMemo)
txJSON.Memos = order.memos.map(utils.convertMemo)
}
return txJSON as OfferCreateTransaction
}
function prepareOrder(address: string, order: FormattedOrderSpecification,
function prepareOrder(this: RippleAPI, address: string, order: FormattedOrderSpecification,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareOrder({address, order, instructions})
const txJSON = createOrderTransaction(address, order)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareOrder({address, order, instructions})
const txJSON = createOrderTransaction(address, order)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareOrder

View File

@@ -1,28 +1,32 @@
import * as _ from 'lodash'
import * as utils from './utils'
const validate = utils.common.validate
import {Instructions, Prepare} from './types'
import {Instructions, Prepare, TransactionJSON} from './types'
import {RippleAPI} from '..'
function createOrderCancellationTransaction(account: string,
orderCancellation: any
): object {
): TransactionJSON {
const txJSON: any = {
TransactionType: 'OfferCancel',
Account: account,
OfferSequence: orderCancellation.orderSequence
}
if (orderCancellation.memos !== undefined) {
txJSON.Memos = _.map(orderCancellation.memos, utils.convertMemo)
txJSON.Memos = orderCancellation.memos.map(utils.convertMemo)
}
return txJSON
}
function prepareOrderCancellation(address: string, orderCancellation: object,
function prepareOrderCancellation(this: RippleAPI, address: string, orderCancellation: object,
instructions: Instructions = {}
): Promise<Prepare> {
validate.prepareOrderCancellation({address, orderCancellation, instructions})
const txJSON = createOrderCancellationTransaction(address, orderCancellation)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.prepareOrderCancellation({address, orderCancellation, instructions})
const txJSON = createOrderCancellationTransaction(address, orderCancellation)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default prepareOrderCancellation

View File

@@ -3,6 +3,7 @@ const ValidationError = utils.common.errors.ValidationError
const claimFlags = utils.common.txFlags.PaymentChannelClaim
import {validate, xrpToDrops} from '../common'
import {Instructions, Prepare} from './types'
import {RippleAPI} from '..'
export type PaymentChannelClaim = {
channel: string,
@@ -16,8 +17,8 @@ export type PaymentChannelClaim = {
function createPaymentChannelClaimTransaction(account: string,
claim: PaymentChannelClaim
): object {
const txJSON: any = {
): utils.TransactionJSON {
const txJSON: utils.TransactionJSON = {
Account: account,
TransactionType: 'PaymentChannelClaim',
Channel: claim.channel,
@@ -58,15 +59,19 @@ function createPaymentChannelClaimTransaction(account: string,
return txJSON
}
function preparePaymentChannelClaim(address: string,
function preparePaymentChannelClaim(this: RippleAPI, address: string,
paymentChannelClaim: PaymentChannelClaim,
instructions: Instructions = {}
): Promise<Prepare> {
validate.preparePaymentChannelClaim(
{address, paymentChannelClaim, instructions})
const txJSON = createPaymentChannelClaimTransaction(
address, paymentChannelClaim)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.preparePaymentChannelClaim(
{address, paymentChannelClaim, instructions})
const txJSON = createPaymentChannelClaimTransaction(
address, paymentChannelClaim)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default preparePaymentChannelClaim

View File

@@ -1,6 +1,7 @@
import * as utils from './utils'
import {validate, iso8601ToRippleTime, xrpToDrops} from '../common'
import {Instructions, Prepare} from './types'
import {RippleAPI} from '..'
export type PaymentChannelCreate = {
amount: string,
@@ -14,7 +15,7 @@ export type PaymentChannelCreate = {
function createPaymentChannelCreateTransaction(account: string,
paymentChannel: PaymentChannelCreate
): object {
): utils.TransactionJSON {
const txJSON: any = {
Account: account,
TransactionType: 'PaymentChannelCreate',
@@ -37,15 +38,19 @@ function createPaymentChannelCreateTransaction(account: string,
return txJSON
}
function preparePaymentChannelCreate(address: string,
function preparePaymentChannelCreate(this: RippleAPI, address: string,
paymentChannelCreate: PaymentChannelCreate,
instructions: Instructions = {}
): Promise<Prepare> {
validate.preparePaymentChannelCreate(
{address, paymentChannelCreate, instructions})
const txJSON = createPaymentChannelCreateTransaction(
address, paymentChannelCreate)
return utils.prepareTransaction(txJSON, this, instructions)
try {
validate.preparePaymentChannelCreate(
{address, paymentChannelCreate, instructions})
const txJSON = createPaymentChannelCreateTransaction(
address, paymentChannelCreate)
return utils.prepareTransaction(txJSON, this, instructions)
} catch (e) {
return Promise.reject(e)
}
}
export default preparePaymentChannelCreate

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