How to send Ripple XRP with JavaScript

Hideyoshi Moriya
2 min readAug 24, 2018

--

In this article, I’m going to explain how to send XRP with JavaScript (Node.js).

Install ripple-lib

First of all, install the ripple-lib library by using following code:

npm install ripple-lib

Instantiate Ripple API

When Instantiating Ripple API, you can specify a server to connect.

const RippleAPI = require('ripple-lib').RippleAPI
const api = new RippleAPI({
//server: 'wss://s1.ripple.com' // MAINNET
server: 'wss://s.altnet.rippletest.net:51233' // TESTNET
})

Connect to Ripple API

api.connect().then(() => {
// Connected
}).catch(console.error)

Create instructions and payment object

  • Instructions are a set of optional parameters to create a transaction object.
  • In payment object, you need to specify to/from addresses and XRP amount to send.
const instructions = {maxLedgerVersionOffset: 5}
const currency = 'XRP'
const amount = '0.01'

const payment = {
source: {
address: ADDRESS_1,
maxAmount: {
value: amount,
currency: currency
}
},
destination: {
address: ADDRESS_2,
amount: {
value: amount,
currency: currency
}
}
}

Create a payment transaction

To create payment transaction, you can use the preparePayment method.

api.preparePayment(ADDRESS_1, payment, instructions).then(prepared => {
// transaction object can be retrived by accessing prepared.txJSON property.
})

Sign to transaction

A transaction object and a secret of sender are needed to sign.

const {signedTransaction, id} = api.sign(prepared.txJSON, SECRET_1)

Submit transaction

Submit a signed transaction.

api.submit(signedTransaction).then(result => {
console.log(JSON.stringify(result, null, 2))
})

Full Code Example

Please replace ADDRESS_1, SECRET_! and ADDRESS_2 when using the following code.

const RippleAPI = require('ripple-lib').RippleAPI// TESTNET ADDRESS 1
const ADDRESS_1 = "rDAvqFiGyYdZ8hQwYVwK5n4qdVT5hsE4iG"
const SECRET_1 = "sa9MF8ep3bupHx1D2uSmG514BBtB8"
// TESTNET ADDRESS 2
const ADDRESS_2 = "rfUaVzRmNhj6QnEBAwEeZ68tKQcwMWvarx"
const instructions = {maxLedgerVersionOffset: 5}
const currency = 'XRP'
const amount = '0.01'
const payment = {
source: {
address: ADDRESS_1,
maxAmount: {
value: amount,
currency: currency
}
},
destination: {
address: ADDRESS_2,
amount: {
value: amount,
currency: currency
}
}
}
const api = new RippleAPI({
//server: 'wss://s1.ripple.com' // MAINNET
server: 'wss://s.altnet.rippletest.net:51233' // TESTNET
})
api.connect().then(() => {
console.log('Connected...')
api.preparePayment(ADDRESS_1, payment, instructions).then(prepared => {
const {signedTransaction, id} = api.sign(prepared.txJSON, SECRET_1)
console.log(id)
api.submit(signedTransaction).then(result => {
console.log(JSON.stringify(result, null, 2))
api.disconnect()
})
})
}).catch(console.error)

References

Support

If you find this article is helpful, it would be greatly appreciated if you could tip XRP to the address below. Thank you!

rJw4xRMQT8Aw6RjDBzSzjcN9rk5FuKvzpy

--

--