Class Client

Client for interacting with rippled servers.

Hierarchy

  • EventEmitter<EventTypes>
    • Client

Constructor

  • Creates a new Client with a websocket connection to a rippled server.

    Parameters

    • server: string

      URL of the server to connect to.

    • options: ClientOptions = {}

      Options for client settings.

    Returns Client

    Example

    import { Client } from "xrpl"
    const client = new Client('wss://s.altnet.rippletest.net:51233')

Abstraction

  • Get XRP/non-XRP balances for an account.

    Parameters

    • address: string

      Address of the account to retrieve balances for.

    • options: {
          ledger_hash?: string;
          ledger_index?: LedgerIndex;
          limit?: number;
          peer?: string;
      } = {}

      Allows the client to specify a ledger_hash, ledger_index, filter by peer, and/or limit number of balances.

      • Optional ledger_hash?: string

        Retrieve the account balances at the ledger with a given ledger_hash.

      • Optional ledger_index?: LedgerIndex

        Retrieve the account balances at a given ledger_index.

      • Optional limit?: number

        Limit number of balances to return.

      • Optional peer?: string

        Filter balances by peer.

    Returns Promise<{
        currency: string;
        issuer?: string;
        value: string;
    }[]>

    An array of XRP/non-XRP balances for the given account.

    Example

    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.

    Returns Promise<number>

    The most recently validated ledger index.

    Example

    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.

    Parameters

    • currency1: BookOfferCurrency

      Specification of one currency involved. (With a currency code and optionally an issuer)

    • currency2: BookOfferCurrency

      Specification of a second currency involved. (With a currency code and optionally an issuer)

    • options: {
          ledger_hash?: null | string;
          ledger_index?: LedgerIndex;
          limit?: number;
          taker?: null | string;
      } = {}

      Options allowing the client to specify ledger_index, ledger_hash, filter by taker, and/or limit number of orders.

      • Optional ledger_hash?: null | string

        Retrieve the orderbook at the ledger with a given ledger_hash.

      • Optional ledger_index?: LedgerIndex

        Retrieve the orderbook at a given ledger_index.

      • Optional limit?: number

        The limit passed into each book_offers request. Can return more than this due to two calls being made. Defaults to 20.

      • Optional taker?: null | string

        Filter orders by taker.

    Returns Promise<{
        buy: BookOffer[];
        sell: BookOffer[];
    }>

    An object containing buy and sell objects.

  • Retrieves the XRP balance of a given account address.

    Parameters

    • address: string

      The XRP address to retrieve the balance for.

    • Optional options: {
          ledger_hash?: string;
          ledger_index?: LedgerIndex;
      } = {}

      Additional options for fetching the balance (optional).

      Optional
      • Optional ledger_hash?: string

        The hash of the ledger to retrieve the balance from (optional).

      • Optional ledger_index?: LedgerIndex

        The index of the ledger to retrieve the balance from (optional).

    Returns Promise<number>

    A promise that resolves with the XRP balance as a number.

    Example

    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'

Core

  • 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.

    Type Parameters

    Parameters

    • transaction: T

      A SubmittableTransaction in JSON format

    • Optional signersCount: number

      The expected number of signers for this transaction. Only used for multisigned transactions.

      Optional

    Returns Promise<T>

    The autofilled transaction.

    Example

    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:

    1. Autofill.
    2. Sign & Encode.
    3. Submit.

    Parameters

    • transaction: string | SubmittableTransaction

      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
      • Optional autofill?: boolean

        If true, autofill a transaction.

      • Optional failHard?: boolean

        If true, and the transaction fails locally, do not retry or relay the transaction to other servers.

      • Optional wallet?: Wallet

        A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.

    Returns Promise<SubmitResponse>

    A promise that contains SubmitResponse.

    Throws

    RippledError if submit request fails.

    Example

    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.

    Type Parameters

    Parameters

    • transaction: string | T

      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
      • Optional autofill?: boolean

        If true, autofill a transaction.

      • Optional failHard?: boolean

        If true, and the transaction fails locally, do not retry or relay the transaction to other servers.

      • Optional wallet?: Wallet

        A wallet to sign a transaction. It must be provided when submitting an unsigned transaction.

    Returns Promise<TxResponse<T>>

    A promise that contains TxResponse, that will return when the transaction has been validated.

    Example

    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.

    Throws

    Connection errors: If the Client object is unable to establish a connection to the specified WebSocket endpoint, an error will be thrown.

    Throws

    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.

    Throws

    Ledger errors: If the ledger being used to submit the transaction is undergoing maintenance or otherwise unavailable, an error will be thrown.

    Throws

    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.

Faucet

  • The fundWallet() method is used to send an amount of XRP (usually 1000) to a new (randomly generated) or existing XRP Ledger wallet.

    Parameters

    • this: Client
    • Optional wallet: null | Wallet

      An existing XRPL Wallet to fund. If undefined or null, a new Wallet will be created.

      Optional
    • options: FundingOptions = {}

      See below.

    Returns Promise<{
        balance: number;
        wallet: Wallet;
    }>

    A Wallet on the Testnet or Devnet that contains some amount of XRP, and that wallet's balance in XRP.

    Example

    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}`)
    }
    }

    Throws

    When either Client isn't connected or unable to fund wallet address.

Fee

feeCushion: number

Factor to multiply estimated fee by to provide a cushion in case the required fee rises during submission of a transaction. Defaults to 1.2.

maxFeeXRP: string

Maximum transaction cost to allow, in decimal XRP. Must be a string-encoded number. Defaults to '2'.

Network

  • Tells the Client instance to connect to its rippled server.

    Returns Promise<void>

    A promise that resolves with a void value when a connection is established.

    Example

    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.

    Example

    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.

    Returns Promise<void>

    A promise that resolves with a void value when a connection is destroyed.

    Example

    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.

    Returns boolean

    Whether the client instance is connected.

    Example

    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.

    Type Parameters

    • T extends EventTypes

    • U extends ((...args) => void) = OnEventToListenerMap<T>

    Parameters

    • eventName: T

      Name of the event. Only forwards streams.

    • listener: U

      Function to run on event.

    Returns Client

    This, because it inherits from EventEmitter.

    Example

    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.

    Type Parameters

    Parameters

    • req: R

      Request to send to the server.

    Returns Promise<T>

    The response from the server.

    Example

    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.

    Type Parameters

    Parameters

    • request: T

      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

    Returns Promise<U[]>

    The array of all responses.

    Throws

    ValidationError if there is no collection key (either from a known command or for the unknown command).

    Example

    // Request all ledger data pages
    const allResponses = await client.requestAll({ command: 'ledger_data' });
    console.log(allResponses);

    Example

    // Request all transaction data pages
    const allResponses = await client.requestAll({ command: 'transaction_data' });
    console.log(allResponses);
  • Requests the next page of data.

    Type Parameters

    Parameters

    • req: T

      Request to send.

    • resp: U

      Response with the marker to use in the request.

    Returns Promise<RequestNextPageReturnMap<T>>

    The response with the next page of data.

    Example

    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)

Other

buildVersion: undefined | string

Rippled Version used by the server this client is connected to

connection: Connection
networkID: undefined | number

Network ID of the server this client is connected to

prefixed: string | boolean
  • Type Parameters

    • T extends EventTypes

    Parameters

    • event: T
    • fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    • Optional context: any
      Optional

    Returns Client

  • Calls each of the listeners registered for a given event.

    Type Parameters

    • T extends EventTypes

    Parameters

    • event: T
    • Rest ...args: any[]
      Rest

    Returns boolean

  • Return an array listing the events for which the emitter has registered listeners.

    Returns EventTypes[]

  • Get networkID and buildVersion from server_info

    Returns Promise<void>

    void

    Example

    const { Client } = require('xrpl')
    const client = new Client('wss://s.altnet.rippletest.net:51233')
    await client.getServerInfo()
    console.log(client.networkID)
    console.log(client.buildVersion)
  • Return the number of listeners listening to a given event.

    Parameters

    • event: EventTypes

    Returns number

  • Return the listeners registered for a given event.

    Type Parameters

    • T extends EventTypes

    Parameters

    • event: T

    Returns ((...args) => void)[]

  • Type Parameters

    • T extends EventTypes

    Parameters

    • event: T
    • Optional fn: ((...args) => void)
      Optional
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    • Optional context: any
      Optional
    • Optional once: boolean
      Optional

    Returns Client

  • Add a one-time listener for a given event.

    Type Parameters

    • T extends EventTypes

    Parameters

    • event: T
    • fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    • Optional context: any
      Optional

    Returns Client

  • Remove all listeners, or those of the specified event.

    Parameters

    • Optional event: EventTypes
      Optional

    Returns Client

  • Remove the listeners of a given event.

    Type Parameters

    • T extends EventTypes

    Parameters

    • event: T
    • Optional fn: ((...args) => void)
      Optional
        • (...args): void
        • Parameters

          • Rest ...args: any[]
            Rest

          Returns void

    • Optional context: any
      Optional
    • Optional once: boolean
      Optional

    Returns Client

Generated using TypeDoc