This tutorial guides you through the basics of building an XRP Ledger-connected application in TypeScript using the xrpl.js client library in either Node.js or web browsers. Because xrpl.js ships its own type definitions, you get compile-time checking of your requests and transactions with no extra setup.
In this tutorial, you'll learn:
- The basic building blocks of XRP Ledger-based applications.
- How to set up a TypeScript project that compiles and runs against the XRP Ledger.
- How to connect to the XRP Ledger using
xrpl.js. - How to get an account on the Testnet using
xrpl.js. - How to use the
xrpl.jslibrary to look up information about an account on the XRP Ledger. - How to use the library's built-in types to build and validate a transaction from your own input values.
- How to put these steps together to create a TypeScript app or web-app.
To complete this tutorial, you should meet the following guidelines:
- Have some familiarity with writing code in TypeScript.
- Have installed Node.js version 20 or later in your development environment.
- If you want to build a web application, any modern web browser with JavaScript support should work fine.
You don't need to install the TypeScript compiler globally; the steps below add it as a project dependency.
Click Download on the top right of the code preview panel to download the source code.
Follow the steps to create a simple application with xrpl.js and TypeScript.
Start a new project by creating an empty folder, then move into that folder and use NPM to install the latest version of xrpl.js along with the TypeScript compiler and the Node.js type definitions:
npm install xrpl
npm install --save-dev typescript @types/nodeThis updates your package.json file, or creates a new one if it didn't already exist.
Your package.json file should look something like this:
{
"name": "get-started-typescript",
"description": "Example code for the Get Started Using TypeScript tutorial.",
"dependencies": {
"xrpl": "^4.4.0"
},
"devDependencies": {
"typescript": "^5.5.0",
"@types/node": "^22.0.0"
},
"type": "module"
}Add a tsconfig.json file to tell the compiler how to build your project. The settings below target modern JavaScript, enable strict type checking, and write the compiled output to a dist folder.
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2020", "DOM"],
"outDir": "dist",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["*.ts"]
}To make queries and submit transactions, you need to connect to the XRP Ledger. To do this with xrpl.js, you create an instance of the Client class and use the connect() method. Because you import the class directly, TypeScript infers the correct type for your client.
xrpl.js use Promises to return values asynchronously. The code samples here use the async/await pattern to wait for the actual result of the Promises.The sample code shows you how to connect to the Testnet, which is one of the available parallel networks.
When you're ready to move to production, you'll need to connect to the XRP Ledger Mainnet. You can do that in two ways:
By installing the core server (
xrpld) and running a node yourself. The core server connects to the Mainnet by default, but you can change the configuration to use Testnet or Devnet. There are good reasons to run your own core server. If you run your own server, you can connect to it like so:const MY_SERVER = 'ws://localhost:6006/' const client = new Client(MY_SERVER) await client.connect()See the example core server config file for more information about default values.
By using one of the available public servers:
const PUBLIC_SERVER = 'wss://xrplcluster.com/' const client = new Client(PUBLIC_SERVER) await client.connect()
The xrpl.js library has a Wallet class for handling the keys and address of an XRP Ledger account. On Testnet, you can fund a new account as shown in the example. Annotating the result with the Wallet type lets the compiler check every property you access.
If you want to generate a wallet without funding it, you can create a new Wallet instance. Keep in mind that you need to send XRP to the wallet for it to be a valid account on the ledger.
Use the Client's request() method to access the XRP Ledger's WebSocket API. Typing the request as an AccountInfoRequest verifies the command name and its fields, and the library infers the matching AccountInfoResponse for the result so you get autocomplete on the response too.
One of the biggest advantages of TypeScript is turning your own input into a well-formed transaction. Typing an object as a Payment makes the compiler require every field and reject values of the wrong type before you run the code. The xrpToDrops() helper converts an XRP amount into the drops string the ledger expects, and validate() runs the same structural checks the server does at runtime.
This example builds and validates the transaction without submitting it. To send it, sign and submit in one call with submitAndWait(). Before submitting real transactions, read Set up Secure Signing.
You can set up handlers for various types of events in xrpl.js, such as whenever the XRP Ledger's consensus process produces a new ledger version. To do that, first call the subscribe method to get the type of events you want, then attach an event handler using the on(eventType, callback) method of the client. The callback's ledger argument is typed for you, so fields like ledger_index and txn_count are checked as you use them.
Call the disconnect() function so Node.js can end the process. The example code waits 10 seconds before disconnecting to allow time for the ledger event listener to receive and display events.
Finally, in your terminal, compile the TypeScript to JavaScript and run the result:
npx tsc
node dist/get-acct-info.jsYou should see output similar to the following:
Connected to Testnet
Creating a new wallet and funding it with Testnet XRP...
Wallet: rKTfqsMZTPWNYWrzFjUwDNLa8XTeA45wvB
Balance: 100
Account Testnet Explorer URL:
https://testnet.xrpl.org/accounts/rKTfqsMZTPWNYWrzFjUwDNLa8XTeA45wvB
Getting account info...
{
"api_version": 2,
"id": 4,
"result": {
"account_data": {
"Account": "rKTfqsMZTPWNYWrzFjUwDNLa8XTeA45wvB",
"Balance": "100000000",
"Flags": 0,
"LedgerEntryType": "AccountRoot",
"OwnerCount": 0,
"PreviousTxnID": "C791975AB1FA811DD7C2A958F71629C3EB830545B25C11F488249D0AEADAA04C",
"PreviousTxnLgrSeq": 18910118,
"Sequence": 18910118,
"index": "0553BF36D48179C15297E1087002B6D33E076D71CAFEA7F0BB1362B9502C851D"
},
"ledger_hash": "CC057AE6CF43485107EA0E4184DE48D73DC4C8A742577964462AB49EDA8EC84E",
"ledger_index": 18910118,
"validated": true
},
"type": "response"
}
Built and validated a Payment transaction:
{
"TransactionType": "Payment",
"Account": "rKTfqsMZTPWNYWrzFjUwDNLa8XTeA45wvB",
"Amount": "22000000",
"Destination": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"
}
Listening for ledger close events...
Ledger #18910119 validated with 0 transactions!
Ledger #18910120 validated with 1 transactions!
Ledger #18910121 validated with 1 transactions!
Disconnected// Import the library along with the TypeScript types you use below.
import {
Client,
Wallet,
Payment,
AccountInfoRequest,
AccountInfoResponse,
xrpToDrops,
validate
} from 'xrpl'
// Define the network client. The Client type is inferred from the constructor.
const SERVER_URL = 'wss://s.altnet.rippletest.net:51233/'
const client = new Client(SERVER_URL)
await client.connect()
console.log('Connected to Testnet')
// Create a wallet and fund it with the Testnet faucet.
console.log('\nCreating a new wallet and funding it with Testnet XRP...')
const fundResult = await client.fundWallet()
// Annotating with the Wallet type lets TypeScript check every field you touch.
const testWallet: Wallet = fundResult.wallet
console.log(`Wallet: ${testWallet.address}`)
console.log(`Balance: ${fundResult.balance}`)
console.log('Account Testnet Explorer URL:')
console.log(` https://testnet.xrpl.org/accounts/${testWallet.address}`)
// To generate a wallet without funding it, uncomment the code below.
// const testWallet: Wallet = Wallet.generate()
// To provide your own seed, replace the testWallet value with the below.
// const testWallet: Wallet = Wallet.fromSeed('your-seed-key')
// Build the request as an AccountInfoRequest. TypeScript verifies the command
// name and fields, and infers the matching AccountInfoResponse for the result.
console.log('\nGetting account info...')
const request: AccountInfoRequest = {
command: 'account_info',
account: testWallet.address,
ledger_index: 'validated'
}
const response: AccountInfoResponse = await client.request(request)
console.log(JSON.stringify(response, null, 2))
// Turn your own input values into a valid transaction. Typing the object as a
// Payment makes the compiler require every field and reject the wrong ones.
const xrpToSend = 22 // a value you might read from user input
const payment: Payment = {
TransactionType: 'Payment',
Account: testWallet.address,
// xrpToDrops converts the XRP amount into the drops string the ledger expects.
Amount: xrpToDrops(xrpToSend),
Destination: 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe' // example destination
}
// validate() runs the same structural checks the server does, at runtime. It
// takes a generic transaction object, so pass the typed value through to it.
validate(payment as unknown as Record<string, unknown>)
console.log('\nBuilt and validated a Payment transaction:')
console.log(JSON.stringify(payment, null, 2))
// To send it, sign and submit in one call:
const submitResponse = await client.submitAndWait(payment, { wallet: testWallet })
console.log(JSON.stringify(submitResponse.result, null, 2))
// Listen to ledger close events. The ledger argument is typed for you, so
// ledger.ledger_index and ledger.txn_count are checked at compile time.
console.log('\nListening for ledger close events...')
client.request({
command: 'subscribe',
streams: ['ledger']
})
client.on('ledgerClosed', (ledger) => {
console.log(`Ledger #${ledger.ledger_index} validated ` +
`with ${ledger.txn_count} transactions!`)
})
// Disconnect when done so Node.js can end the process.
// Delay this by 10 seconds to give the ledger event listener time to receive
// and display some ledger events.
setTimeout(async () => {
await client.disconnect()
console.log('\nDisconnected')
}, 10000)