Creates a new Client with a websocket connection to a rippled server.
URL of the server to connect to.
Options for client settings.
Get XRP/non-XRP balances for an account.
Address of the account to retrieve balances for.
Allows the client to specify a ledger_hash, ledger_index, filter by peer, and/or limit number of balances.
Optional
ledger_hash?: stringRetrieve the account balances at the ledger with a given ledger_hash.
Optional
ledger_index?: LedgerIndexRetrieve the account balances at a given ledger_index.
Optional
limit?: numberLimit number of balances to return.
Optional
peer?: stringFilter balances by peer.
An array of XRP/non-XRP balances for the given account.
const { Client } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
async function getAccountBalances(address) {
try {
const options = {
ledger_index: 'validated',
limit: 10
};
const balances = await xrplClient.getBalances(address, options);
console.log('Account Balances:');
balances.forEach((balance) => {
console.log(`Currency: ${balance.currency}`);
console.log(`Value: ${balance.value}`);
console.log(`Issuer: ${balance.issuer}`);
console.log('---');
});
} catch (error) {
console.error('Error retrieving account balances:', error);
}
}
const address = 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh';
await getAccountBalances(address);
await client.disconnect();
Returns the index of the most recently validated ledger.
The most recently validated ledger index.
Fetch orderbook (buy/sell orders) between two currency pairs. This checks both sides of the orderbook
by making two order_book
requests (with the second reversing takerPays and takerGets). Returned offers are
not normalized in this function, so either currency could be takerGets or takerPays.
Specification of one currency involved. (With a currency code and optionally an issuer)
Specification of a second currency involved. (With a currency code and optionally an issuer)
Options allowing the client to specify ledger_index, ledger_hash, filter by taker, and/or limit number of orders.
Optional
ledger_hash?: null | stringRetrieve the orderbook at the ledger with a given ledger_hash.
Optional
ledger_index?: LedgerIndexRetrieve the orderbook at a given ledger_index.
Optional
limit?: numberThe limit passed into each book_offers request. Can return more than this due to two calls being made. Defaults to 20.
Optional
taker?: null | stringFilter orders by taker.
An object containing buy and sell objects.
Retrieves the XRP balance of a given account address.
The XRP address to retrieve the balance for.
Optional
options: { ledger_hash?: string; ledger_index?: LedgerIndex } = {}Additional options for fetching the balance (optional).
Optional
ledger_hash?: stringThe hash of the ledger to retrieve the balance from (optional).
Optional
ledger_index?: LedgerIndexThe index of the ledger to retrieve the balance from (optional).
A promise that resolves with the XRP balance as a number.
Autofills fields in a transaction. This will set Sequence
, Fee
,
lastLedgerSequence
according to the current state of the server this Client
is connected to. It also converts all X-Addresses to classic addresses and
flags interfaces into numbers.
A SubmittableTransaction in JSON format
Optional
signersCount: numberThe expected number of signers for this transaction. Only used for multisigned transactions.
The autofilled transaction.
const { Client } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
async function createAndAutofillTransaction() {
const transaction = {
TransactionType: 'Payment',
Account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',
Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)
}
try {
const autofilledTransaction = await client.autofill(transaction)
console.log(autofilledTransaction)
} catch (error) {
console.error(`Failed to autofill transaction: ${error}`)
}
}
createAndAutofillTransaction()
Autofill helps fill in fields which should be included in a transaction, but can be determined automatically
such as LastLedgerSequence
and Fee
. If you override one of the fields autofill
changes, your explicit
values will be used instead. By default, this is done as part of submit
and submitAndWait
when you pass
in an unsigned transaction along with your wallet to be submitted.
Simulates an unsigned transaction. Steps performed on a transaction:
A transaction to autofill, sign & encode, and submit.
Optional
opts: { binary?: Binary }(Optional) Options used to sign and submit a transaction.
Optional
binary?: BinaryIf true, return the metadata in a binary encoding.
A promise that contains SimulateResponse.
Submits a signed/unsigned transaction. Steps performed on a transaction:
A transaction to autofill, sign & encode, and submit.
Optional
opts: { autofill?: boolean; failHard?: boolean; wallet?: Wallet }(Optional) Options used to sign and submit a transaction.
Optional
autofill?: booleanIf true, autofill a transaction.
Optional
failHard?: booleanIf true, and the transaction fails locally, do not retry or relay the transaction to other servers.
Optional
wallet?: WalletA wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
A promise that contains SubmitResponse.
const { Client, Wallet } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
const wallet = Wallet.generate()
const transaction = {
TransactionType: 'Payment',
Account: wallet.classicAddress,
Destination: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
Amount: '10000000' // 10 XRP in drops (1/1,000,000th of an XRP)
}
const submitResponse = await client.submit(transaction, { wallet })
console.log(submitResponse)
Asynchronously submits a transaction and verifies that it has been included in a validated ledger (or has errored/will not be included for some reason). See Reliable Transaction Submission.
A transaction to autofill, sign & encode, and submit.
Optional
opts: { autofill?: boolean; failHard?: boolean; wallet?: Wallet }(Optional) Options used to sign and submit a transaction.
Optional
autofill?: booleanIf true, autofill a transaction.
Optional
failHard?: booleanIf true, and the transaction fails locally, do not retry or relay the transaction to other servers.
Optional
wallet?: WalletA wallet to sign a transaction. It must be provided when submitting an unsigned transaction.
A promise that contains TxResponse, that will return when the transaction has been validated.
const { Client, Wallet } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
async function submitTransaction() {
const senderWallet = client.fundWallet()
const recipientWallet = client.fundWallet()
const transaction = {
TransactionType: 'Payment',
Account: senderWallet.address,
Destination: recipientWallet.address,
Amount: '10'
}
try {
await client.submit(signedTransaction, { wallet: senderWallet })
console.log(result)
} catch (error) {
console.error(`Failed to submit transaction: ${error}`)
}
}
submitTransaction()
In this example we submit a payment transaction between two newly created testnet accounts.
Under the hood, submit
will call client.autofill
by default, and because we've passed in a Wallet
it
Will also sign the transaction for us before submitting the signed transaction binary blob to the ledger.
This is similar to submitAndWait
which does all of the above, but also waits to see if the transaction has been validated.
Connection errors: If the Client
object is unable to establish a connection to the specified WebSocket endpoint,
an error will be thrown.
Transaction errors: If the submitted transaction is invalid or cannot be included in a validated ledger for any
reason, the promise returned by submitAndWait()
will be rejected with an error. This could include issues with insufficient
balance, invalid transaction fields, or other issues specific to the transaction being submitted.
The fundWallet() method is used to send an amount of XRP (usually 1000) to a new (randomly generated) or existing XRP Ledger wallet.
Optional
wallet: null | WalletAn existing XRPL Wallet to fund. If undefined or null, a new Wallet will be created.
See below.
Optional
amount?: stringA custom amount to fund, if undefined or null, the default amount will be 1000.
Optional
faucetHost?: stringA custom host for a faucet server. On devnet, testnet, AMM devnet, and HooksV3 testnet, fundWallet
will
attempt to determine the correct server automatically. In other environments, or if you would like to customize
the faucet host in devnet or testnet, you should provide the host using this option.
Optional
faucetPath?: stringA custom path for a faucet server. On devnet,
testnet, AMM devnet, and HooksV3 testnet, fundWallet
will
attempt to determine the correct path automatically. In other environments,
or if you would like to customize the faucet path in devnet or testnet,
you should provide the path using this option.
Ex: client.fundWallet(null,{'faucet.altnet.rippletest.net', '/accounts'})
specifies a request to 'faucet.altnet.rippletest.net/accounts' to fund a new wallet.
Optional
usageContext?: stringAn optional field to indicate the use case context of the faucet transaction Ex: integration test, code snippets.
A Wallet on the Testnet or Devnet that contains some amount of XRP, and that wallet's balance in XRP.
Example 1: Fund a randomly generated wallet const { Client, Wallet } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233') await client.connect() const { balance, wallet } = await client.fundWallet()
Under the hood, this will use Wallet.generate()
to create a new random wallet, then ask a testnet faucet
To send it XRP on ledger to make it a real account. If successful, this will return the new account balance in XRP
Along with the Wallet object to track the keys for that account. If you'd like, you can also re-fill an existing
Account by passing in a Wallet you already have.
const api = new xrpl.Client("wss://s.altnet.rippletest.net:51233")
await api.connect()
const { wallet, balance } = await api.fundWallet()
Example 2: Fund wallet using a custom faucet host and known wallet address
fundWallet
will try to infer the url of a faucet API from the network your client is connected to.
There are hardcoded default faucets for popular test networks like testnet and devnet.
However, if you're working with a newer or more obscure network, you may have to specify the faucetHost
And faucetPath so fundWallet
can ask that faucet to fund your wallet.
const newWallet = Wallet.generate()
const { balance, wallet } = await client.fundWallet(newWallet, {
amount: '10',
faucetHost: 'https://custom-faucet.example.com',
faucetPath: '/accounts'
})
console.log(`Sent 10 XRP to wallet: ${address} from the given faucet. Resulting balance: ${balance} XRP`)
} catch (error) {
console.error(`Failed to fund wallet: ${error}`)
}
}
Readonly
feeFactor to multiply estimated fee by to provide a cushion in case the required fee rises during submission of a transaction. Defaults to 1.2.
Readonly
maxMaximum transaction cost to allow, in decimal XRP. Must be a string-encoded number. Defaults to '2'.
Get the url that the client is connected to.
The URL of the server this client is connected to.
Tells the Client instance to connect to its rippled server.
A promise that resolves with a void value when a connection is established.
Client.connect() establishes a connection between a Client object and the server.
const { Client } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
// do something with the client
await client.disconnect()
If you open a client connection, be sure to close it with await client.disconnect()
before exiting your application.
Disconnects the XRPL client from the server and cancels all pending requests and subscriptions. Call when you want to disconnect the client from the server, such as when you're finished using the client or when you need to switch to a different server.
A promise that resolves with a void value when a connection is destroyed.
Checks if the Client instance is connected to its rippled server.
Whether the client instance is connected.
Event handler for subscription streams.
This, because it inherits from EventEmitter.
Makes a request to the client with the given command and additional request body parameters.
Request to send to the server.
The response from the server.
Makes multiple paged requests to the client to return a given number of
resources. Multiple paged requests will be made until the limit
number of resources is reached (if no limit
is provided, a single request
will be made).
If the command is unknown, an additional collect
property is required to
know which response key contains the array of resources.
NOTE: This command is used by existing methods and is not recommended for general use. Instead, use rippled's built-in pagination and make multiple requests as needed.
The initial request to send to the server.
Optional
collect: string(Optional) the param to use to collect the array of resources (only needed if command is unknown).
The array of all responses.
Requests the next page of data.
The response with the next page of data.
API Version used by the server this client is connected to
Rippled Version used by the server this client is connected to
Readonly
connectionNetwork ID of the server this client is connected to
Static
prefixedCalls each of the listeners registered for a given event.
Return an array listing the events for which the emitter has registered listeners.
Return the number of listeners listening to a given event.
Return the listeners registered for a given event.
Add a one-time listener for a given event.
Optional
context: anyDeprecated: Use autofill instead, provided for users familiar with v1
A Transaction in JSON format
Optional
signersCount: numberThe expected number of signers for this transaction. Only used for multisigned transactions.
Remove all listeners, or those of the specified event.
Optional
event: EventTypes
Client for interacting with rippled servers.