Creates a new Client with a websocket connection to a rippled server.
URL of the server to connect to.
Options for client settings.
import { Client } from "xrpl"
const client = new Client('wss://s.altnet.rippletest.net:51233')
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_Retrieve the account balances at the ledger with a given ledger_hash.
Optional
ledger_Retrieve 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.
const { Client } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
const ledgerIndex = await client.getLedgerIndex()
console.log(ledgerIndex)
// 884039
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_Retrieve the orderbook at the ledger with a given ledger_hash.
Optional
ledger_Retrieve 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: { Additional options for fetching the balance (optional).
Optional
Optional
ledger_The hash of the ledger to retrieve the balance from (optional).
Optional
ledger_The index of the ledger to retrieve the balance from (optional).
A promise that resolves with the XRP balance as a number.
const client = new Client(wss://s.altnet.rippletest.net:51233)
await client.connect()
const balance = await client.getXrpBalance('rG1QQv2nh2gr7RCZ1P8YYcBUKCCN633jCn')
console.log(balance)
await client.disconnect()
/// '200'
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.
Optional
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.
Submits a signed/unsigned transaction. Steps performed on a transaction:
A transaction to autofill, sign & encode, and submit.
Optional
opts: { (Optional) Options used to sign and submit a transaction.
Optional
Optional
autofill?: booleanIf true, autofill a transaction.
Optional
failIf 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.
RippledError if submit request fails.
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: { (Optional) Options used to sign and submit a transaction.
Optional
Optional
autofill?: booleanIf true, autofill a transaction.
Optional
failIf 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.
Ledger errors: If the ledger being used to submit the transaction is undergoing maintenance or otherwise unavailable, an error will be thrown.
Timeout errors: If the transaction takes longer than the specified timeout period to be included in a validated
ledger, the promise returned by submitAndWait()
will be rejected with an error.
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.
Optional
See below.
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}`)
}
}
When either Client isn't connected or unable to fund wallet address.
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.
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()
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.
To use the disconnect() method, you first need to create a new Client object and connect it to a 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()
Checks if the Client instance is connected to its rippled server.
Whether the client instance is connected.
const { Client } = require('xrpl')
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
console.log(client.isConnected())
// true
await client.disconnect()
console.log(client.isConnected())
// false
Event handler for subscription streams.
Name of the event. Only forwards streams.
Function to run on event.
This, because it inherits from EventEmitter.
const api = new Client('wss://s.altnet.rippletest.net:51233')
api.on('transaction', (tx: TransactionStream) => {
console.log("Received Transaction")
console.log(tx)
})
await api.connect()
const response = await api.request({
command: 'subscribe',
streams: ['transactions_proposed']
})
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.
const response = await client.request({
command: 'account_info',
account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
})
console.log(response)
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).
Optional
The array of all responses.
ValidationError if there is no collection key (either from a known command or for the unknown command).
// Request all ledger data pages
const allResponses = await client.requestAll({ command: 'ledger_data' });
console.log(allResponses);
// Request all transaction data pages
const allResponses = await client.requestAll({ command: 'transaction_data' });
console.log(allResponses);
Requests the next page of data.
Request to send.
Response with the marker to use in the request.
The response with the next page of data.
const response = await client.request({
command: 'account_tx',
account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
})
console.log(response)
const nextResponse = await client.requestNextPage({
command: 'account_tx',
account: 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59',
},
response)
console.log(nextResponse)
Rippled Version used by the server this client is connected to
Readonly
connectionNetwork ID of the server this client is connected to
Static
prefixedDeprecated: 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.
Optional
Use autofill instead, provided for users familiar with v1
Remove the listeners of a given event.
Optional
fn: ((...args) => void)Optional
Rest
...args: any[]Rest
Optional
context: anyOptional
Optional
once: booleanOptional
Generated using TypeDoc
Client for interacting with rippled servers.