Get Started Using JavaScript Library
This tutorial guides you through the basics of building an XRP Ledger-connected application in JavaScript using the xrpl.js
client library in either Node.js or web browsers.
Goals
In this tutorial, you'll learn:
- The basic building blocks of XRP Ledger-based applications.
- 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.js
library to look up information about an account on the XRP Ledger. - How to put these steps together to create a JavaScript app or web-app.
Prerequisites
To complete this tutorial, you should meet the following guidelines:
- Have some familiarity with writing code in JavaScript.
- 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.
Source Code
Click Download on the top right of the code preview panel to download the source code.
Steps
Follow the steps to create a simple application with xrpl.js
.
1. Install Dependencies
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:
npm install xrpl
This 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:
{
"dependencies": {
"xrpl": "^4.4.0"
},
"type": "module"
}
2. Connect to the XRP Ledger
Connect to the XRP Ledger Testnet
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.
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.
Connect to the XRP Ledger Mainnet
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 (
rippled
) 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 xrpl.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 xrpl.Client(PUBLIC_SERVER) await client.connect()
3. Get Account
(Optional) Use Your Own Wallet Seed
To use an existing wallet seed encoded in base58, you can create a Wallet
instance from it.
4. Query the XRP Ledger
Use the Client's request()
method to access the XRP Ledger's WebSocket API.
5. Listen for Events
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.
6. Disconnect
Disconnect when done 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.
7. Run the Application
Finally, in your terminal, run the application like so:
node get-acct-info.js
You should see output similar to the following:
Connected to Testnet
Creating a new wallet and funding it with Testnet XRP...
Wallet: rMnXR9p2sZT9iZ6ew3iEqvBMyPts1ADc4i
Balance: 10
Account Testnet Explorer URL:
https://testnet.xrpl.org/accounts/rMnXR9p2sZT9iZ6ew3iEqvBMyPts1ADc4i
Getting account info...
{
"api_version": 2,
"id": 4,
"result": {
"account_data": {
"Account": "rMnXR9p2sZT9iZ6ew3iEqvBMyPts1ADc4i",
"Balance": "10000000",
"Flags": 0,
"LedgerEntryType": "AccountRoot",
"OwnerCount": 0,
"PreviousTxnID": "0FF9DB2FE141DD0DF82566A171B6AF70BB2C6EB6A53D496E65D42FC062C91A78",
"PreviousTxnLgrSeq": 9949268,
"Sequence": 9949268,
"index": "4A9C9220AE778DC38C004B2B17A08E218416D90E01456AFCF844C18838B36D01"
},
"account_flags": {
"allowTrustLineClawback": false,
"defaultRipple": false,
"depositAuth": false,
"disableMasterKey": false,
"disallowIncomingCheck": false,
"disallowIncomingNFTokenOffer": false,
"disallowIncomingPayChan": false,
"disallowIncomingTrustline": false,
"disallowIncomingXRP": false,
"globalFreeze": false,
"noFreeze": false,
"passwordSpent": false,
"requireAuthorization": false,
"requireDestinationTag": false
},
"ledger_hash": "304C7CC2A33B712BE43EB398B399E290C191A71FCB71784F584544DFB7C441B0",
"ledger_index": 9949268,
"validated": true
},
"type": "response"
}
Listening for ledger close events...
Ledger #9949269 validated with 0 transactions!
Ledger #9949270 validated with 0 transactions!
Ledger #9949271 validated with 0 transactions!
Disconnected
See Also
// Import the library
import xrpl from "xrpl"
// Define the network client
const SERVER_URL = "wss://s.altnet.rippletest.net:51233/"
const client = new xrpl.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 fund_result = await client.fundWallet()
const test_wallet = fund_result.wallet
console.log(`Wallet: ${test_wallet.address}`)
console.log(`Balance: ${fund_result.balance}`)
console.log('Account Testnet Explorer URL:')
console.log(` https://testnet.xrpl.org/accounts/${test_wallet.address}`)
// To generate a wallet without funding it, uncomment the code below
// const test_wallet = xrpl.Wallet.generate()
// To provide your own seed, replace the test_wallet value with the below
// const test_wallet = xrpl.Wallet.fromSeed("your-seed-key")
// Get info from the ledger about the address we just funded
console.log("\nGetting account info...")
const response = await client.request({
"command": "account_info",
"account": test_wallet.address,
"ledger_index": "validated"
})
console.log(JSON.stringify(response, null, 2))
// Listen to ledger close events
console.log("\nListening for ledger close events...")
client.request({
"command": "subscribe",
"streams": ["ledger"]
})
client.on("ledgerClosed", async (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);