* generate faucet wallet
* updated comments
* added example in documentation
* updated documentation
* Added xprl.org link in docs
* updated code snippet
* Made changes from comments
* new changes from comments
* yarn.lock
* removed axios and use https.request
* updated webpack to include http and https fallback
* fixed files formatting
* small fixes
* Fix typo for Testnet
Co-authored-by: Elliot Lee <github.public@intelliot.com>
Co-authored-by: Elliot Lee <github.public@intelliot.com>
* export offline methods to top-level of package
- All methods that don’t require a network connection are exported at the top-level of the package.
- These instance methods are now marked as deprecated.
- Removed an empty ts file
Per https://github.com/ripple/rippled/issues/3214
The following fields are deprecated and may be removed without further notice: accepted, hash (use ledger_hash instead), seqNum (use ledger_index instead), totalCoins (use total_coins instead).
Added test for lowercase hex in transaction memo
* Relaxed existing test to accept case change in memo after decoding
* Added check of resulting signature
- Suggest XRPLF's public cluster; this is a better starter experience since
it's full-history and blocks known scam accounts
- Update the Node.js compatibility language to match the README.
- Remove dated language about ES5/ES6 Promises.
- Re-gen docs (this seems to have added a memo field that was previously
modified in some other PR)
Add the following missing specifications to the list of transactionType
specifications:
- Ticket Create
- Account Delete
- Deposit Preauth
Rearrange the transaction type specifications to be in alphabetical
order.
* clearing of awaiting response promises when response handled
* Apply suggestions from code review
Co-authored-by: Elliot Lee <github.public@intelliot.com>
Using request('submit', ...) allows the ripple-lib API to be effectively
identical to the underlying rippled API. Whereas submit() returns only
certain fields from rippled, using request('submit') gives you rippled's
full response, including the new fields added in rippled v1.5.0.
The now-deprecated ripple-hashes library provided a number of hash
functions for users to compute the hashes/IDs for various XRP Ledger
objects:
* Transactions (to generate transaction hashes, also known as IDs)
* Transaction signing hashes (to sign transactions)
* Ledger Object IDs (to look up specific ledger objects in a ledger's
state tree; see https://xrpl.org/ledger-object-ids.html)
This commit exports these utility methods from ripple-lib as static
methods. Access them on the RippleAPI class. Example:
import {RippleAPI} from 'ripple-lib'
const hash = RippleAPI.computeBinaryTransactionHash(...)
Fix#1209
Calling: Uint8Array.from(undefined)
Throws:
TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
at Function.from (<anonymous>)
* generateSeed: Pass only entropy and algorithm
* Update typescript and ripple-keypairs
* Improve unit tests
* Rename [Original Address] to [Classic Address] in test output
* Assign event listener to socket close event on open before attempting to execute post-connection logic, prottects possible unhandled rejection in disconnect
* Remove try/catch for linting failure
* Up timeout for CI failure
* Feedback emit error for disconnection failure on connect failure
* Feedback ignore error on disconnect, propagate root cause
* Feedback add extra test check for expected error on connect
* Feedback remove setTimeout for await reconnect
The documentation previously just stated that any array of integers
was acceptable for providing as entropy, but it must be an array of
length 16 where the values are from 0-255 (uint8) to ensure we have
16 bytes of entropy.
Being able to fetch the WalletLocator field opens up new use-cases. The field can store for example a transaction hash, referencing a transaction with memos containing useful data.
This allows for the use of Node 6. Note that Node v6 is no longer supported by Node.js (End-of-life'd in April 2019). We recommend updating to Node v8/v10 ASAP, to keep getting security updates and fixes from the Node.js team.
* Update TxParser and Mocha
* Convert ripple-hashes to TypeScript and add into ripple-lib along with unit tests
* Switch casing to camelCase
* Document intToVuc
* Convert Slots to numbers, add exception if number is outside 0-15
* Remove Shamap v2 support
* Improve naming
When there are multiple representations of the same value
(for example, trailing zeros) the verification will fail.
This points users to the error.data object for details about
the failure, and adds a diff so that the cause of the
discrepancy can be seen at a glance.
* 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
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
* 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
* 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.
* 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)
* 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
The following methods are available directly under the RippleAPI object,
not under schemaValidator:
isValidAddress, isValidSecret, deriveKeypair, deriveAddress
computeLedgerHash: support new getLedger response by using
rawTransaction
BREAKING CHANGES:
* Remove the `rawTransactions` field and replace it with a new `rawTransaction` field in each transaction.
* Rename the `metaData` field (in each raw transaction) to `meta` (for consistency with rippled's `tx` method).
* Add `ledger_index` to each raw transaction.
The 'amount' field should almost never be used.
With partial payments, the field can show an amount that is
significantly less than the amount that the transaction actually
delivered. This change sets amount to 0 XRP when it may be misleading.
This change omits the `amount` when parsing payment transactions.
See `HISTORY.md` for recommended alternatives.
Rename files for consistency with their titles:
* Rename amount-base to amountbase
* Rename tx-hash to transaction-hash
* Rename id to transactionHash
* Rename objects/settings.json to objects/settings-plus-memos.json
* Rename ledgerversion to ledger-version
* Export iso8601ToRippleTime(), txFlags, convertStringToHex()
* Fix a bug that caused fees exceeding 999 to throw an error
e.g. '1,000' would not be recognized as a valid number.
To use 6 decimal places, toFixed should be used instead of toFormat.
* Add maxFeeXRP (default 2 XRP) as an optional RippleAPI constructor parameter
- No calculated or specified fee can exceed this value
- If the fee exceeds 2 XRP, throw a ValidationError
* sign() - throw ValidationError when Fee exceeds maxFeeXRP
* Document getFee parameters
* Explain new fee limits in HISTORY.md
* Deprecate `maxFee`
- `RippledError`: Include the full response from the `rippled` server.
- A new test ensures correct behavior when `streams` is not an array.
- `NotConnectedError` may be thrown with a different message than before.
* Add support for all rippled APIs, including subscriptions.
* Add support for arbitrary stream message types.
* Note that rippled APIs take amounts in drops.
* request() will be available in ripple-lib version 1.0.0+
This library is for integrating a JavaScript/TypeScript app with the XRP Ledger and supports functionality such as IOUs, payment paths, the decentralized exchange, account settings, payment channels, escrows, multi-signing, and more.
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)
Then see the [documentation](#documentation).
## Running tests
### Using ripple-lib with React Native
If you want to use `ripple-lib` with React Native you will need to have some of the NodeJS modules available. To help with this you can use a module like [rn-nodeify](https://github.com/tradle/rn-nodeify).
1. Install dependencies (you can use `npm` as well):
```shell
yarn add react-native-crypto
yarn add ripple-lib
# install peer deps
yarn add react-native-randombytes
# install latest rn-nodeify
yarn add rn-nodeify@latest --dev
```
2. After that, run the following command:
```shell
# install node core shims and recursively hack package.json files
# in ./node_modules to add/update the "browser"/"react-native" field with relevant mappings
./node_modules/.bin/rn-nodeify --hack --install
```
3. Enable `crypto`:
`rn-nodeify` will create a `shim.js` file in the project root directory.
Open it and uncomment the line that requires the crypto module:
```javascript
// If using the crypto shim, uncomment the following line to ensure
// crypto is loaded first, so it can populate global.crypto
require('crypto')
```
4. Import `shim` in your project (it must be the first line):
```javascript
import './shim'
...
```
### Using ripple-lib with Deno
Until official support for [Deno](https://deno.land) is added, you can use the following work-around to use `ripple-lib` with Deno:
```javascript
import ripple from 'https://dev.jspm.io/npm:ripple-lib';
(async () => {
const api = new (ripple as any).RippleAPI({ server: 'wss://s.altnet.rippletest.net:51233' });
+ [RippleAPI Full Reference Documentation](https://xrpl.org/rippleapi-reference.html) ([in this repo](https://github.com/ripple/ripple-lib/blob/develop/docs/index.md))
We have a low-traffic mailing list for announcements of new ripple-lib releases. (About 1 email per week)
+ [Subscribe to xrpl-announce](https://groups.google.com/g/xrpl-announce)
If you're using the XRP Ledger in production, you should run a [rippled server](https://github.com/ripple/rippled) and subscribe to the ripple-server mailing list as well.
+ [Subscribe to ripple-server](https://groups.google.com/forum/#!forum/ripple-server)
## Development
To build the library for Node.js and the browser:
```
$ yarn build
```
The TypeScript compiler will [output](./tsconfig.json#L7) the resulting JS files in `./dist/npm/`.
webpack will output the resulting JS files in `./build/`.
For details, see the `scripts` in `package.json`.
## Running Tests
### Unit Tests
1. Clone the repository
2. `cd` into the repository and install dependencies with `yarn install`
3.`yarn test` or `yarn test --coverage` (`istanbul` will create coverage reports in `coverage/lcov-report/`)
3. `yarn test`
### Linting
Run `yarn lint` to lint the code with `eslint`.
## 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`.
Do not edit `./docs/index.md` directly because it is a generated file.
`npm` may be used instead of `yarn` in the commands above.
Instead, edit the appropriate `.md.ejs` files in `./docs/src/`.
This table shows which versions of ripple-lib are currently supported with security updates:
| Version | Supported |
| ------- | ---------------------- |
| 1.x | :white_check_mark: Yes |
| 0.x | :x: No |
## Responsible disclosure security policy
The responsible disclosure of vulnerabilities helps to protect users of the project. Vulnerabilities are first triaged in a private manner, and only publicly disclosed after a reasonable time period that allows patching the vulnerability and provides an upgrade path for users.
When contacting us directly via email, we will do our best to respond in a reasonable time to resolve the issue. Do not disclose the vulnerability until it has been patched and users have been given time to upgrade.
We kindly ask you to refrain from malicious acts that put our users, the project, or any of the project’s team members at risk.
## Reporting a security issue
Security is a top priority. But no matter how much effort we put into security, there can still be vulnerabilities present.
If you discover a security vulnerability, please use the following means of communications to report it to us:
To modify account flags, you can use an AccountSet transaction and its `SetFlag` or `ClearFlag` fields.
The flags are called [AccountSet flags (asf*)](https://xrpl.org/accountset.html#accountset-flags):
`RippleAPI.accountSetFlags.requireDestinationTag`: Require a destination tag to send transactions to this account.
`RippleAPI.accountSetFlags.requireAuthorization`: Require authorization for users to hold balances issued by this address. Can only be enabled if the address has no trust lines connected to it.
`RippleAPI.accountSetFlags.disallowIncomingXRP`: XRP should not be sent to this account. (Enforced by client applications, not by rippled)
`RippleAPI.accountSetFlags.disableMasterKey`: Disallow use of the master key pair. Can only be enabled if the account has configured another way to sign transactions.
`RippleAPI.accountSetFlags.enableTransactionIDTracking`: Track the ID of this account's most recent transaction.
`RippleAPI.accountSetFlags.noFreeze`: Permanently give up the ability to freeze individual trust lines or disable Global Freeze. This flag can never be disabled after being enabled.
`RippleAPI.accountSetFlags.globalFreeze`: Freeze all assets issued by this account.
`RippleAPI.accountSetFlags.defaultRipple`: Enable [rippling](https://xrpl.org/rippling.html) on this account's trust lines by default.
`RippleAPI.accountSetFlags.depositAuth`:Enable Deposit Authorization on this account.
Every XRP Ledger account has an *address*, which is a base58-encoding of a hash of the account's public key. XRP Ledger addresses always start with the lowercase letter `r`.
```json
"X7AcgcsBL6XDcUb289X4mJ8djcdyKaB5hJDWMArnXr61cqZ"
```
An *address* refers to a specific XRP Ledger account. It is a base-58 encoding of a hash of the account's public key. There are two kinds of addresses in common use:
### Classic Address
A *classic address* encodes a hash of the account's public key and a checksum. It has no other data. This kind of address always starts with the lowercase letter `r`.
### X-address
An *X-address* encodes a hash of the account's public key, a tag, and a checksum. This kind of address starts with the uppercase letter `X` if it is intended for use on the production XRP Ledger (mainnet). It starts with the uppercase letter `T` if it is intended for use on a test network such as Testnet or Devnet.
## Account Sequence Number
Every XRP Ledger account has a *sequence number* that is used to keep transactions in order. Every transaction must have a sequence number. A transaction can only be executed if it has the next sequence number in order, of the account sending it. This prevents one transaction from executing twice and transactions executing out of order. The sequence number starts at `1` and increments for each transaction that the account makes.
Every XRP Ledger account has a *sequence number* that is used to keep transactions in order. Every transaction must have a sequence or a ticketSequence number. A transaction can only be executed if it has the next sequence number in order, of the account sending it, or uses a previously generated ticketSequence number. This prevents one transaction from executing twice and transactions executing out of order. The sequence number starts at `1` and increments for each transaction that the account makes.
## Currency
@@ -19,14 +31,13 @@ Currencies are represented as either 3-character currency codes or 40-character
## Value
A *value* is a quantity of a currency represented as a decimal string. Be careful: JavaScript's native number format does not have sufficient precision to represent all values. XRP has different precision from other currencies.
**XRP** has 6 significant digits past the decimal point. In other words, XRP cannot be divided into positive values smaller than `0.000001` (1e-6). XRP has a maximum value of `100000000000` (1e11).
**XRP** has 6 significant digits past the decimal point. In other words, XRP cannot be divided into positive values smaller than `0.000001` (1e-6). This smallest unit is called a "drop". XRP has a maximum value of `100000000000` (1e11). Some RippleAPI methods accept XRP to maintain compatibility with older versions of the API. For consistency with the `rippled` APIs, we recommend formally specifying XRP values in *drops* in all API requests, and converting them to XRP for display. This is like Bitcoin's *satoshis* and Ethereum's *wei*. 1 XRP = 1,000,000 drops.
**Non-XRP values** have 16 decimal digits of precision, with a maximum value of `9999999999999999e80`. The smallest positive non-XRP value is `1e-81`.
## Amount
Example amount:
Example 100.00 USD amount:
```json
{
@@ -36,15 +47,16 @@ Example amount:
}
```
Example XRP amount:
Example 3.0 XRP amount, in drops:
```json
{
"currency": "XRP",
"value": "2000"
"currency": "drops",
"value": "3000000"
}
```
(Requires `ripple-lib` version 1.0.0 or higher.)
An *amount* is data structure representing a currency, a quantity of that currency, and the counterparty on the trustline that holds the value. For XRP, there is no counterparty.
An *amount* is an object specifying a currency, a quantity of that currency, and the counterparty (issuer) on the trustline that holds the value. For XRP, there is no counterparty.
A *lax amount* allows the counterparty to be omitted for all currencies. If the counterparty is not specified in an amount within a transaction specification, then any counterparty may be used for that amount.
@@ -52,4 +64,4 @@ A *lax lax amount* allows either or both the counterparty and value to be omitte
A *balance* is an amount than can have a negative value.
server: 'wss://s1.ripple.com' // Public rippled server hosted by Ripple, Inc.
server: 'wss://xrplcluster.com' // Public cluster
});
api.on('error', (errorCode, errorMessage) => {
console.log(errorCode + ': ' + errorMessage);
@@ -16,7 +16,7 @@ api.on('connected', () => {
});
api.on('disconnected', (code) => {
// code - [close code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent) sent by the server
// will be 1000 if this was normal closure
// the code is 1000 for a normal closure
console.log('disconnected, code:', code);
});
api.connect().then(() => {
@@ -26,9 +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.
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).
[Node.js v14](https://nodejs.org/) is recommended. Other versions may work but are not frequently tested.
<aside class="notice">
All the code snippets in this documentation assume that you have surrounded them with this boilerplate.
@@ -39,7 +37,7 @@ If you omit the "catch" section, errors may not be visible.
</aside>
<aside class="notice">
The "error" event is emitted whenever an error occurs that cannot be associated with a specific request. If the listener is not registered, an exception will be thrown whenever the event is emitted.
The API emits an "error" event whenever an error occurs that cannot be associated with a specific request. If there is no listener registered for this event, the API throws an exception whenever the event is emitted.
</aside>
### Parameters
@@ -55,7 +53,7 @@ If you omit the `server` parameter, RippleAPI operates [offline](#offline-functi
1. Install [Node.js](https://nodejs.org) and [Yarn](https://yarnpkg.com/en/docs/install). Most Linux distros have a package for Node.js; check that it's the version you want.
2. Use yarn to install RippleAPI:
`yarn install ripple-lib`
`yarn add ripple-lib`
After you have installed ripple-lib, you can create scripts using the [boilerplate](#boilerplate) and run them using the Node.js executable, typically named `node`:
Combines signed transactions from multiple accounts for a multisignature transaction. The signed transaction must subsequently be [submitted](#submit).
Combines signed transactions from multiple accounts for a multisignature transaction into a form that can be [submitted](#submit).
Returns formatted bids and asks, which make up an orderbook.
This is a static method on the `RippleAPI` class.
### Parameters
This method takes two parameters.
1. An `OrderbookInfo` object: `{ base: Issue, counter: Issue }`.
2. An array of `BookOffer` objects.
### Return Value
This method returns an object with two properties: `bids` and `asks`, each of which is an array of bids (buy orders) or asks (sell orders), respectively. Both `bids` and `asks` are formatted the same way.
Object structure:
<%- renderSchema('output/get-orderbook.json') %>
**Raw order data:** The response includes a `data` property containing the raw order data. This may include `owner_funds`, `Flags`, and other fields.
For details, see the `rippled` [book_offers method](https://xrpl.org/book_offers.html).
Returns the estimated transaction fee for the rippled server the RippleAPI instance is connected to.
This uses the [feeCushion parameter](#parameters) provided to the RippleAPI constructor, or the default value of `1.2`.
### Parameters
This method has no parameters.
<%- renderSchema('input/get-fee.json') %>
### Return Value
This method returns a promise that resolves with a stringencoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
This method returns a promise that resolves with a string-encoded floating point value representing the estimated fee to submit a transaction, expressed in XRP.
Returns header information for the specified ledger (or the most recent validated ledger if no ledger is specified). Optionally, all the transactions that were validated in the ledger or the account state information can be returned with the ledger header.
Returns open orders for the specified account. Open orders are orders that have not yet been fully executed and are still in the order book.
**Breaking change:** In ripple-lib 1.1.0 and earlier, orders returned by this method were not sorted correctly. Orders are now sorted correctly, from best to worst.
**See also:** An alternative way to get orderbooks is with `request` and [`formatBidsAndAsks`](#formatbidsandasks).
### Parameters
<%- renderSchema('input/get-orderbook.json') %>
### Return Value
This method returns a promise that resolves with an object with the following structure (Note: the structures of `bids` and `asks` are identical):
This method returns a promise that resolves with an object with the following structure Both `bids` and `asks` have the same format:
<%- renderSchema('output/get-orderbook.json') %>
### New in ripple-lib 0.22.0 and higher
**Raw order data:** The response includes a `data` property containing the raw order data. This may include `owner_funds`, `Flags`, and other fields.
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).
For details, see the `rippled` [book_offers method](https://xrpl.org/book_offers.html).
Returns settings for the specified account. Note: For account data that is not modifiable by the user, see [getAccountInfo](#getaccountinfo).
@@ -10,7 +10,7 @@ Returns settings for the specified account. Note: For account data that is not m
### Return Value
This method returns a promise that resolves with an array of objects with the following structure (Note: all fields are optional as they will not be shown if they are set to their default value):
This method returns a promise that resolves with an array of objects with the following structure. All fields are optional, and are omitted if they are set to their default value.
Returns `true` when there are more pages available.
When there are more results than contained in the response, the response includes a `marker` field. You can use this convenience method, or check for `marker` yourself.
See [Markers and Pagination](https://xrpl.org/markers-and-pagination.html).
### Return Value
This method returns `true` if `currentResponse` includes a `marker`.
RippleAPI is the official client library to the XRP Ledger. Currently, RippleAPI is only available in JavaScript.
RippleAPI (ripple-lib) is the official client library to the XRP Ledger. Currently, RippleAPI is only available in JavaScript/TypeScript.
Using RippleAPI, you can:
* [Query transactions from the XRP Ledger history](#gettransaction)
@@ -9,4 +10,6 @@ Using RippleAPI, you can:
* [Generate a new XRP Ledger Address](#generateaddress)
* ... and [much more](#api-methods).
RippleAPI only provides access to *validated*, *immutable* transaction data.
This page contains documentation for ripple-lib. To use ripple-lib with npm/yarn, begin with the [Getting Started](https://github.com/ripple/ripple-lib#getting-started) steps.
**What is ripple-lib used for?** Here's a [list of applications that use `ripple-lib`](https://github.com/ripple/ripple-lib/blob/develop/APPLICATIONS.md). Open a PR to add your app or project to the list!
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.
RippleAPI can also function without internet connectivity. This can be useful in order to generate secrets and sign transactions from a secure, isolated machine.
RippleAPI can also function without internet connectivity, so you can generate secrets and sign transactions from a secure, isolated machine.
To instantiate RippleAPI in offline mode, use the following boilerplate code:
To instantiate RippleAPI in offline mode, use the following code:
Parse an `AccountRoot` object's [`Flags`](https://xrpl.org/accountroot.html#accountroot-flags).
### Parameters
This method takes one parameter, the AccountRoot `Flags` number to parse. Note that flags have different mappings on other types of objects or in transactions such as AccountSet.
### Return Value
This method returns an object with containing a key for each AccountRoot flag known to this version of RippleAPI. Each flag has a boolean value of `true` or `false`.
Prepare a Check cancellation transaction. This cancels an unredeemed Check, removing it from the ledger without sending any money. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
Prepare a Check cancellation transaction. This type of transaction cancels an unredeemed Check, removing it from the ledger without sending any money. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
Prepare a Check cashing transaction. This redeems a Check to receive up to the amount authorized by the corresponding CheckCreate transaction. The prepared transaction must subsequently be [signed](#sign) and [submitted](#submit).
Prepare a Check cashing transaction. This redeems a Check to receive up to the amount authorized by the corresponding CheckCreate transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
This is a convenience method for generating the EscrowCreate JSON used by rippled, so the same restrictions apply.
Field mapping: `allowCancelAfter` is equivalent to rippled's `CancelAfter`; `allowExecuteAfter` is equivalent to `FinishAfter`. At the `allowCancelAfter` time, the escrow is considered expired. This means that the funds can only be returned to the sender. At the `allowExecuteAfter` time, the escrow is permitted to be released to the recipient (if the `condition` is fulfilled).
Note that `allowCancelAfter` must be chronologically later than `allowExecuteAfter`.
### Return Value
This method returns a promise that resolves with an object with the following structure:
Prepare a ticket transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
Ticket functionality requires the [TicketBatch amendment](https://github.com/ripple/xrpl-dev-portal/issues/898). As of 2020-11-24, this amendment is not activated on the Mainnet, Testnet, or Devnet.
Prepare a transaction. The prepared transaction can then be [signed](#sign) and [submitted](#submit).
This method works with any of [the transaction types supported by rippled](https://xrpl.org/transaction-types.html).
Notably, this is the preferred method for preparing `DepositPreauth` or `AccountDelete` transactions.
### Parameters
Name | Type | Description
---- | ---- | -----------
transaction | [Transaction](https://xrpl.org/transaction-formats.html) | The specification (JSON) of the transaction to prepare. Set `Account` to the address of the account that is creating the transaction. You may omit auto-fillable fields like `Fee`, `Flags`, and `Sequence` to have them set automatically.
instructions | [Instructions](#transaction-instructions) | *Optional* Instructions for executing the transaction.
### Return Value
This method returns a promise that resolves with an object with the following structure:
Returns an object with the `counterparty` field renamed to `issuer`. This is useful because RippleAPI generally uses the name `counterparty` while the rippled API generally uses the name `issuer`.
This is a static method on the `RippleAPI` class.
### Parameters
This method takes one parameter, an object with a `counterparty` field.
### Return Value
This method returns a new object based on the source object, but with `issuer` instead of `counterparty`.
Returns the response from invoking the specified command, with the specified options, on the connected rippled server.
Refer to [HTTP / WebSocket APIs](https://xrpl.org/rippled-api.html) for commands and options. All XRP amounts must be specified in drops. One drop is equal to 0.000001 XRP. See [Specifying Currency Amounts](https://xrpl.org/basic-data-types.html#specifying-currency-amounts).
Most commands return data for the `current` (in-progress, open) ledger by default. Do not rely on this. Always specify a ledger version in your request. In the example below, the 'validated' ledger is requested, which is the most recent ledger that has been validated by the whole network. See [Specifying Ledgers](https://xrpl.org/basic-data-types.html#specifying-ledgers).
### Return Value
This method returns a promise that resolves with the response from rippled.
### Example
```javascript
// Replace 'ledger' with your desired rippled command
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.
ripple-lib uses the XRP Ledger's [WebSocket API](https://xrpl.org/rippled-api.html) for online functionality. You can use ripple-lib to call these APIs directly. Use the `request()`, `hasNextPage()`, and `requestNextPage()` methods:
* Use `request()` to issue any `rippled` command, including `account_currencies`, `subscribe`, and `unsubscribe`. [Full list of API Methods](https://xrpl.org/public-rippled-methods.html).
* Use `hasNextPage()` to determine whether a response has more pages. This is true when the response includes a [`marker` field](https://xrpl.org/markers-and-pagination.html).
* Use `requestNextPage()` to request the next page of data.
When using rippled APIs:
* [Specify XRP amounts in drops](https://xrpl.org/basic-data-types.html#specifying-currency-amounts).
* [Specify timestamps as the number of seconds since the "Ripple Epoch"](https://xrpl.org/basic-data-types.html#specifying-time).
* Instead of `counterparty`, use `issuer`.
## Listening to streams
The `rippled` server can push updates to your client when various events happen.
Refer to [Subscriptions in the `rippled` API docs](https://xrpl.org/subscribe.html) for details.
Note that the `streams` parameter for generic streams takes an array. For example, to subscribe to the `validations` stream, use `{ streams: [ 'validations' ] }`.
The string names of some generic streams to subscribe to are in the table below. (Refer to `rippled` for an up-to-date list of streams.)
Type | Description
---- | -----------
`server` | Sends a message whenever the status of the `rippled` server (for example, network connectivity) changes.
`ledger` | Sends a message whenever the consensus process declares a new validated ledger.
`transactions` | Sends a message whenever a transaction is included in a closed ledger.
`transactions_proposed` | Sends a message whenever a transaction is included in a closed ledger, as well as some transactions that have not yet been included in a validated ledger and may never be. Not all proposed transactions appear before validation. Even some transactions that don't succeed are included in validated ledgers because they take the anti-spam transaction fee.
`validations` | Sends a message whenever the server receives a validation message, also called a validation vote, regardless of whether the server trusts the validator.
`manifests` | Sends a message whenever the server receives a manifest.
`peer_status` | (Admin-only) Information about connected peer `rippled` servers, especially with regards to the consensus process.
When you subscribe to a stream, you must also listen to the relevant message type(s). Some of the available message types are in the table below. (Refer to `rippled` for an up-to-date list of message types.)
Type | Description
---- | -----------
`ledgerClosed` | Sent by the `ledger` stream when the consensus process declares a new fully validated ledger. The message identifies the ledger and provides some information about its contents.
`validationReceived` | Sent by the `validations` stream when the server receives a validation message, also called a validation vote, regardless of whether the server trusts the validator.
`manifestReceived` | Sent by the `manifests` stream when the server receives a manifest.
`transaction` | Sent by many subscriptions including `transactions`, `transactions_proposed`, `accounts`, `accounts_proposed`, and `book` (Order Book). See [Transaction Streams](https://xrpl.org/subscribe.html#transaction-streams) for details.
`peerStatusChange` | (Admin-only) Reports a large amount of information on the activities of other `rippled` servers to which the server is connected.
`path_find` | Asynchronous follow-up response to the currently open path\_find request. See [rippled path\_find method](https://xrpl.org/path_find.html) for details.
To register your listener function, use `connection.on(type, handler)`.
Here is an example of listening for transactions on given account(s):
```
const account = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn' // Replace with the account you want notifications for
api.connect().then(() => {
// 'transaction' can be replaced with the relevant `type` from the table above
api.connection.on('transaction', (event) => {
// Do something useful with `event`
console.log(JSON.stringify(event, null, 2))
})
api.request('subscribe', {
accounts: [ account ]
}).then(response => {
console.log('Successfully subscribed')
}).catch(error => {
// Handle `error`
})
})
```
The subscription ends when you unsubscribe or the WebSocket connection is closed.
For full details, see the [subscribe method](https://xrpl.org/subscribe.html).
This method checks an object for conformance to a specified schema. It does not return anything, but throws a `ValidationError` if the object does not conform to the schema.
Sign a prepared transaction. The signed transaction must subsequently be [submitted](#submit).
Sign a prepared transaction. The signed transaction can then be [submitted](#submit).
This method can sign any of [the transaction types supported by ripple-binary-codec](https://github.com/ripple/ripple-binary-codec/blob/cfcde79c19c359e9a0466d7bc3dc9a3aef47bb99/src/enums/definitions.json#L1637). When a new transaction type is added to the XRP Ledger, it is unrecognized until `ripple-binary-codec` is updated. If you try to sign an unrecognized transaction type, this method throws an error like the following:
`Error: [TRANSACTION_TYPE] is not a valid name or ordinal for TransactionType`
### Parameters
<%- renderSchema("input/sign.json") %>
When this method is used for multi-signing, the `options` parameter is required. See the multi-signing example in this section for more details.
### Return Value
This method returns an object with the following structure:
@@ -20,10 +26,116 @@ This method returns an object with the following structure:
If the multi-signing account was setup properly, the above example logs `resultCode: 'tesSUCCESS'` and the hash for the transaction. If any of `{signAs: some_address}` options were missing, the code returns a validation error such as:
```
[ValidationError(txJSON is not the same for all signedTransactions)]
Sign a payment channel claim. The signature can be submitted in a subsequent [PaymentChannelClaim](#preparepaymentchannelclaim) transaction.
Sign a payment channel claim. A [PaymentChannelClaim](#preparepaymentchannelclaim) transaction can use the resulting signature to withdraw XRP from a payment channel.
A *transaction specification* specifies what a transaction should do. Each [Transaction Type](#transaction-types) has its own type of specification.
A *transaction specification* specifies what a transaction should do. Each [Transaction Type](#transaction-types) has its own type of specification, which corresponds to the [native XRP Ledger transaction types](https://xrpl.org/transaction-types.html).
## Payment
## Account Delete
See [Transaction Types](#transaction-types) for a description.
Delete your account and send the remaining XRP elsewhere. (Native transactiontype: [AccountDelete](https://xrpl.org/accountdelete.html))
> **Note:** To prepare an Account Delete transaction, use [`prepareTransaction()`](#preparetransaction) with the [native transaction format](https://xrpl.org/accountdelete.html).
## Check Cancel
See [Transaction Types](#transaction-types) for a description.
Cancel a Check that has not been redeemed. (Native transactiontype: [CheckCancel](https://xrpl.org/checkcancel.html))
Create a Check, a deferred payment that can be redeemed by the destination. (Native transaction type: [CheckCreate](https://xrpl.org/checkcreate.html))
Preauthorize an sender to deposit money at an account using [Deposit Authorization](https://xrpl.org/depositauth.html). (Native transaction type: [DepositPreauth](https://xrpl.org/depositpreauth.html))
> **Note:** To prepare a Deposit Preauth transaction, use [`prepareTransaction()`](#preparetransaction) with the [native transaction format](https://xrpl.org/depositpreauth.html).
## Escrow Cancellation
Cancel an Escrow that has passed its expiration. (Native transaction type: [EscrowCancel](https://xrpl.org/escrowcancel.html))
Create an Escrow that locks up XRP until a given time or condition is met. (Native transaction type: [EscrowCreate](https://xrpl.org/escrowcreate.html))
Create and execute a limit order in the decentralized exchange. (Native transaction type: [OfferCreate](https://xrpl.org/offercreate.html))
<%- renderSchema('specifications/order.json') %>
The following invalid flag combination causes a `ValidationError`: `immediateOrCancel` and `fillOrKill`. These fields are mutually exclusive, and cannot both be set at the same time.
Create a Payment Channel with XRP set aside for asynchronous payments. (Native transaction type: [PaymentChannelCreate](https://xrpl.org/paymentchannelcreate.html))
Set aside account Sequence numbers as Tickets to be used by later transactions.
> **Caution:** As of 2021-01-22, Tickets are not yet available on the XRP Ledger.
> **Note:** To prepare a Ticket Create transaction, use [`prepareTransaction()`](#preparetransaction) with the native transaction format. <!-- Future link: https://xrpl.org/ticketcreate.html -->
## Trustline
Create or modify a trust line between two accounts, for an issued currency. (Native transaction type: [TrustSet](https://xrpl.org/trustset.html))
Submits a signed transaction. The transaction is not guaranteed to succeed; it must be verified with [getTransaction](#gettransaction).
The `submit` method applies a transaction and sends it to the network to be confirmed and included in future ledgers.
This method takes a signed, serialized transaction as a binary blob, and submits it to the network as-is. Since signed transaction objects are immutable, no part of the transaction can be modified or automatically filled in after submission.
To send a transaction as robustly as possible, you should construct and sign it in advance, persist it somewhere that you can access even after a power outage, then `submit` it as a `tx_blob`. After submission, monitor the network with the `tx` method to see if the transaction was successfully applied; if a restart or other problem occurs, you can safely re-submit the `tx_blob` transaction: it won't be applied twice since it has the same sequence number as the old transaction.
| `tx_blob` | String | Hex representation of the signed transaction to submit. This can be a multi-signed transaction. |
| `fail_hard` | Boolean | (Optional, defaults to false) If true, and the transaction fails locally, do not retry or relay the transaction to other servers |
### Return Value
This method returns an object with the following structure:
When successful, this method returns an object containing the following fields:
| `engine_result` | String | Text [result code](https://xrpl.org/transaction-results.html) indicating the preliminary result of the transaction, for example `tesSUCCESS` |
| `engine_result_code` | Integer | Numeric version of the [result code](https://xrpl.org/transaction-results.html). **Not recommended.** |
| `engine_result_message` | String | Human-readable explanation of the transaction's preliminary result |
| `tx_blob` | String | The complete transaction in hex string format |
| `tx_json` | Object | The complete transaction in JSON format |
| `accepted` | Boolean | The value `true` indicates that the transaction was applied, queued, broadcast, or kept for later. The value `false` indicates that none of those happened, so the transaction cannot possibly succeed as long as you do not submit it again and have not already submitted it another time. [New in: rippled 1.5.0] |
| `account_sequence_available` | Number | The next [Sequence Number](https://xrpl.org/basic-data-types.html#account-sequence) available for the sending account after all pending and [queued](https://xrpl.org/transaction-queue.html) transactions. [New in: rippled 1.5.0] |
| `account_sequence_next` | number | The next [Sequence Number](https://xrpl.org/basic-data-types.html#account-sequence) for the sending account after all transactions that have been provisionally applied, but not transactions in the [queue](https://xrpl.org/transaction-queue.html). [New in: rippled 1.5.0] |
| `applied` | Boolean | The value `true` indicates that this transaction was applied to the open ledger. In this case, the transaction is likely, but not guaranteed, to be validated in the next ledger version. [New in: rippled 1.5.0] |
| `broadcast` | Boolean | The value `true` indicates this transaction was broadcast to peer servers in the peer-to-peer XRP Ledger network. (Note: if the server has no peers, such as in [stand-alone mode](https://xrpl.org/rippled-server-modes.html#reasons-to-run-a-rippled-server-in-stand-alone-mode), the server uses the value `true` for cases where it _would_ have broadcast the transaction.) The value `false` indicates the transaction was not broadcast to any other servers. [New in: rippled 1.5.0] |
| `kept` | Boolean | The value `true` indicates that the transaction was kept to be retried later. [New in: rippled 1.5.0] |
| `queued` | Boolean | The value `true` indicates the transaction was put in the [Transaction Queue](https://xrpl.org/transaction-queue.html), which means it is likely to be included in a future ledger version. [New in: rippled 1.5.0] |
| `open_ledger_cost` | String | The current [open ledger cost](https://xrpl.org/transaction-cost.html#open-ledger-cost) before processing this transaction. Transactions with a lower cost are likely to be [queued](https://xrpl.org/transaction-queue.html). [New in: rippled 1.5.0] |
| `validated_ledger_index` | Integer | The [ledger index](https://xrpl.org/basic-data-types.html#ledger-index) of the newest validated ledger at the time of submission. This provides a lower bound on the ledger versions that the transaction can appear in as a result of this request. (The transaction could only have been validated in this ledger version or earlier if it had already been submitted before.) |
Note: Many situations can prevent a transaction from processing successfully, such as a lack of trust lines connecting the two accounts in a payment, or changes in the state of the ledger since the time the transaction was constructed. Even if nothing is wrong, it may take several seconds to close and validate the ledger version that includes the transaction. Do not consider the transaction's results final until they appear in a validated ledger version.
@@ -6,20 +6,21 @@ A transaction type is specified by the strings in the first column in the table
Type | Description
---- | -----------
[payment](#payment) | A `payment` transaction represents a transfer of value from one account to another. Depending on the [path](https://ripple.com/build/paths/) taken, additional exchanges of value may occur atomically to facilitate the payment.
[payment](#payment) | A `payment` transaction represents a transfer of value from one account to another. Depending on the [path](https://xrpl.org/paths.html) taken, additional exchanges of value may occur atomically to enable the payment.
[order](#order) | An `order` transaction creates a limit order. It defines an intent to exchange currencies, and creates an order in the XRP Ledger's order book if not completely fulfilled when placed. Orders can be partially fulfilled.
[orderCancellation](#order-cancellation) | An `orderCancellation` transaction cancels an order in the XRP Ledger's order book.
[trustline](#trustline) | A `trustline` transactions creates or modifies a trust line between two accounts.
[trustline](#trustline) | A `trustline` transaction creates or modifies a trust line between two accounts.
[settings](#settings) | A `settings` transaction modifies the settings of an account in the XRP Ledger.
[escrowCreation](#escrow-creation) | An `escrowCreation` transaction creates an escrow on the ledger, which locks XRP until a cryptographic condition is met or it expires. It is like an escrow service where the XRP Ledger acts as the escrow agent.
[escrowCancellation](#escrow-cancellation) | An `escrowCancellation` transaction unlocks the funds in an escrow and sends them back to the creator of the escrow, 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.
[escrowCancellation](#escrow-cancellation) | An `escrowCancellation` transaction unlocks the funds in an escrow and sends them back to the creator of the escrow, if the escrow has expired.
[escrowExecution](#escrow-execution) | An `escrowExecution` transaction unlocks the funds in an escrow and sends them to the destination of the escrow, if the conditions for the escrow are met.
[checkCreate](#check-create) | A `checkCreate` transaction creates a check on the ledger, which is a deferred payment that can be cashed by its intended destination.
[checkCancel](#check-cancel) | A `checkCancel` transaction cancels an 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.
[paymentChannelClaim](#payment-channel-claim) | A `paymentChannelClaim` transaction withdraws XRP from a channel and optionally requests to close it.
[ticketCreate](#ticket-create) | A successful `ticketCreate` transaction adds a Ticket in the directory of the owning account.
## Transaction Flow
@@ -37,23 +38,26 @@ Executing a transaction with `RippleAPI` requires the following four steps:
* [prepareCheckCreate](#preparecheckcreate)
* [prepareCheckCancel](#preparecheckcancel)
* [prepareCheckCash](#preparecheckcash)
* [prepareTicketCreate](#prepareticketcreate)
2. [Sign](#sign) - Cryptographically sign the transaction locally and save the [transaction ID](#transaction-id). Signing is how the owner of an account authorizes a transaction to take place. For multisignature transactions, the `signedTransaction` fields returned by `sign` must be collected and passed to the [combine](#combine) method.
3. [Submit](#submit) - Submit the transaction to the connected server.
4. Verify - Verify that the transaction got validated by querying with [getTransaction](#gettransaction). This is necessary because transactions may fail even if they were successfully submitted.
## Transaction Fees
Every transaction must destroy a small amount of XRP as a cost to 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` is 20 drops × (1 + 2 Signatures) = 60 drops. See [Transaction Cost](https://xrpl.org/transaction-cost.html).
## Transaction Instructions
Transaction instructions indicate how to execute a transaction, complementary with the [transaction specification](#transaction-specifications).
<%- renderSchema("objects/instructions.json") %>
We recommended that you specify a `maxLedgerVersion` so that you can quickly determine that a failed transaction will never succeeed in the future. It is impossible for a transaction to succeed after the 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 can never succeed in the future. It is impossible for a transaction to succeed after the XRP Ledger's consensus-validated ledger version exceeds the transaction's `maxLedgerVersion`. If you omit `maxLedgerVersion`, the "prepare\*" method automatically supplies a `maxLedgerVersion` equal to the current ledger plus 3, which it includes in the return value from the "prepare\*" method.
This object provides constants for use when creating or interpreting transaction flags. Most transactions have a set of bit-flags that represent various options that affect how a transaction should behave. These options are represented as binary values that can be combined with bitwise-or operations to encode multiple flags at once.
Most flags only have meaning for a specific transaction type. The same bitwise value may be reused for flags on different transaction types, so it is important to pay attention to the transaction type when setting and reading flags.
Bits that are not defined as flags MUST be 0.
### Global Flag
Applies globally to all transactions.
`txFlags.Universal.FullyCanonicalSig`: Require a fully-canonical signature. When preparing transactions, ripple-lib enables this flag for you.
### Payment Flags
`txFlags.Payment.NoRippleDirect`: Do not use the default path; only use specified paths. This is intended to force the transaction to take arbitrage opportunities. Most clients do not need this.
`txFlags.Payment.PartialPayment`: If the specified destination amount cannot be sent without spending more than the source maxAmount, reduce the received amount instead of failing outright. See [Partial Payments](https://xrpl.org/partial-payments.html) for more details.
`txFlags.Payment.LimitQuality`: Only take paths where all the conversions have an input:output ratio that is equal or better than the ratio of `destination.amount`:`source.maxAmount`. See [Limit Quality](https://xrpl.org/payment.html#limit-quality) for details.
### OfferCreate Flags
`txFlags.OfferCreate.Passive`: If enabled, the offer does not consume offers that exactly match it, and instead becomes an Offer object in the ledger. It still consumes offers that cross it.
`txFlags.OfferCreate.ImmediateOrCancel`: Treat the offer as an Immediate or Cancel order. If enabled, the offer never becomes a ledger object: it only tries to match existing offers in the ledger.
`txFlags.OfferCreate.FillOrKill`: Treat the offer as a Fill or Kill order.
`txFlags.OfferCreate.Sell`: Treat the offer as a Sell order. With `order.direction = 'sell'`, exchange the entire `order.quantity`, even if it means obtaining more than the `order.totalPrice` amount in exchange. If using `prepareOrder`, ripple-lib sets this flag for you.
### TrustSet Flags
`txFlags.TrustSet.SetAuth`: Authorize the other party to hold issuances from this account. (No effect unless using the AccountSet.RequireAuth flag.) Cannot be unset.
`txFlags.TrustSet.NoRipple`: Obsolete.
`txFlags.TrustSet.SetNoRipple`: Blocks [rippling](https://xrpl.org/rippling.html) between two trustlines of the same currency, if this flag is set on both.
`txFlags.TrustSet.ClearNoRipple`: Clears the No-[Rippling](https://xrpl.org/rippling.html) flag.
`txFlags.TrustSet.SetFreeze`: Freeze the trustline. A non-XRP currency can be frozen by the exchange or gateway that issued it. XRP cannot be frozen.
`txFlags.TrustSet.ClearFreeze`: Unfreeze the trustline.
### AccountSet Flags
You can use the `prepareSettings` method to change your account flags. This method uses AccountSet flags internally.
In the rippled API, Account Flags can be enabled and disabled with the SetFlag and ClearFlag parameters. See [AccountSet Flags](https://xrpl.org/accountset.html#accountset-flags).
The AccountSet transaction type has some transaction flags, but their use is discouraged.
* `txFlags.AccountSet.RequireDestTag`
* `txFlags.AccountSet.OptionalDestTag`
* `txFlags.AccountSet.RequireAuth`
* `txFlags.AccountSet.OptionalAuth`
* `txFlags.AccountSet.DisallowXRP`
* `txFlags.AccountSet.AllowXRP`
### PaymentChannelClaim Flags
`txFlags.PaymentChannelClaim.Renew`: Clear the channel's Expiration time. (Expiration is different from the channel's immutable CancelAfter time.) Only the source address of the payment channel can use this flag.
`txFlags.PaymentChannelClaim.Close`: Request to close the channel. Only the channel source and destination addresses can use this flag. This flag closes the channel immediately if it has no more XRP allocated to it after processing the current claim, or if the destination address uses it. If the source address uses this flag when the channel still holds XRP, this schedules the channel to close after SettleDelay seconds have passed. (Specifically, this sets the Expiration of the channel to the close time of the previous ledger plus the channel's SettleDelay time, unless the channel already has an earlier Expiration time.) If the destination address uses this flag when the channel still holds XRP, any XRP that remains after processing the claim is returned to the source address.
### Other Transaction Types
The remaining transaction types do not have any flags at this time.
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.
* When implementing Reliable Transaction Submission, there are many potential solutions, each with different trade-offs. The main decision points are:
* 1) Transaction preparation:
* - How do we decide which account sequence and LastLedgerSequence numbers to use?
* (To prevent unintentional duplicate transactions, an {account, account_sequence} pair can be used as a transaction's idempotency key)
* - How do we decide how much to pay for the transaction fee? (If our transactions have been failing due to low fee, we should consider increasing this value)
* 2) Transaction status retrieval. Options include:
* - Poll for transaction status:
* - On a regular interval (e.g. every 3-5 seconds), or
* - When a new validated ledger is detected
* + (To accommodate an edge case in transaction retrieval, check the sending account's Sequence number to confirm that it has the expected value;
* alternatively, wait until a few additional ledgers have been validated before deciding that a transaction has definitively not been included in a validated ledger)
* - Listen for transaction status: scan all validated transactions to see if our transactions are among them
* 3) What do we do when a transaction fails? It is possible to implement retry logic, but caution is advised. Note that there are a few ways for a transaction to fail:
* A) `tec`: The transaction was included in a ledger but only claimed the transaction fee
* B) `tesSUCCESS` but unexpected result: The transaction was successful but did not have the expected result. This generally does not occur for XRP-to-XRP payments
* C) The transaction was not, and never will be, included in a validated ledger [3C]
* For brevity, these are XRP-to-XRP payments, taking a source, destination, and an amount in drops.
*
* The script will attempt to make all of these payments as quickly as possible, and report the final status of each. Transactions that fail are NOT retried.
// Compute the hash of an order, given the owner's classic address (starting with `r`) and the account sequence number of the `OfferCreate` order transaction.
// @deprecated Invoke from top-level package instead
// Compute the hash of an escrow, given the owner's classic address (starting with `r`) and the account sequence number of the `EscrowCreate` escrow transaction.
// @deprecated Invoke from top-level package instead
// Compute the hash of a payment channel, given the owner's classic address (starting with `r`), the classic address of the destination, and the account sequence number of the `PaymentChannelCreate` payment channel transaction.
// @deprecated Invoke from top-level package instead
* Original code based on "backo" - https://github.com/segmentio/backo
* MIT License - Copyright 2014 Segment.io
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* A Back off strategy that increases exponentially. Useful with repeated
* setTimeout calls over a network (where the destination may be down).
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.