RippleAPI Quick Start Guide
This tutorial guides you through the basics of building a simple Ripple-connected application using Node.js and RippleAPI, a simple JavaScript API for accessing the Ripple Consensus Ledger.
Environment Setup
The first step to using RippleAPI successfully is setting up your development environment.
Install Node.js and npm
RippleAPI is built as an application for the Node.js runtime environment, so the first step is getting Node.js installed. Specifically, RippleAPI requires Node.js version 0.12, version 4.x, or higher.
This step depends on your operating system. We recommend the official instructions for installing Node.js using a package manager for your operating system. If the packages for Node.js and npm (Node Package Manager) are separate (this includes Arch Linux, CentOS, Fedora, and RHEL), you should make sure to install both.
After you have installed Node.js, you can check whether it's installed by checking the version of the node binary from a commandline:
node --version
On some platforms, the binary is named nodejs instead:
nodejs --version
Use NPM to install RippleAPI and dependencies
RippleAPI uses the newest version of JavaScript, ECMAScript 6 (also known as ES2015). In order to use the new features of ECMAScript 6, RippleAPI depends on Babel-Node and its ES2015 presets. Fortunately you can use npm to install RippleAPI and these dependencies all at once.
1. Create a new directory for your project
For example, to create a folder called my_ripple_experiment:
mkdir my_ripple_experiment && cd my_ripple_experiment
Alternatively, you can create a repo on GitHub in order to share your work. After setting it up, clone the repo to your local machine and cd into that directory.
2. Create a new package.json file for your project.
Here's a good template:
{
"name": "my_ripple_experiment",
"version": "0.0.1",
"license": "MIT",
"private": true,
"//": "Change the license to something appropriate. You may want to use 'UNLICENSED' if you are just starting out.",
"dependencies": {
"ripple-lib": "*",
"babel-cli": "^6.0.0",
"babel-preset-es2015": "*"
},
"babel": {
"presets": ["es2015"]
},
"devDependencies": {
"eslint": "*"
}
}
This includes RippleAPI itself (ripple-lib), Babel (babel-cli), the ECMAScript 6 presets for Babel (babel-preset-es2015). It also has the optional add-on ESLint (eslint) for checking your code quality.
3. Use NPM to install the dependencies.
npm install
This automatically installs all the dependencies defined in the package.json into the local folder node_modules/. (We recommend not using npm -g to install the dependencies globally.)
The install process may take a while, and may end with a few warnings. The following warnings are benign, and do not indicate a real problem:
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.6
npm WARN ajv@1.4.10 requires a peer of ajv-i18n@0.1.x but none was installed.
4. (Optional) Tell Git to ignore the node_modules folder.
If you are using Git to manage your repository, it's considered a good practice to omit the node_modules folder from the Git repo. Other people who check out your code can use npm to install the dependencies, and you don't have to keep the repo synchronized with changes to other people's code. Edit the .gitignore file and add the following line to it:
/node_modules/
Save and commit the changes:
git add .gitignore
git commit -m "ignore node_modules"
First RippleAPI Script
With RippleAPI installed, it's time to test that it works. Here's a simple script that uses RippleAPI to retrieve information on a specific account:
'use strict';
const {RippleAPI} = require('ripple-lib');
const api = new RippleAPI({
server: 'wss://s1.ripple.com' // Public rippled server
});
api.connect().then(() => {
/* begin custom code ------------------------------------ */
const my_address = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
console.log('getting account info for', my_address);
return api.getAccountInfo(my_address);
// info => {...} is just a shorter syntax for function(info) {...}
}).then(info => {
console.log(info);
console.log('getAccountInfo done');
/* end custom code -------------------------------------- */
}).then(() => {
return api.disconnect();
}).then(()=> {
console.log('done and disconnected.');
}).catch(console.error);
Running the script
RippleAPI and the script both use the ECMAScript 6 version of JavaScript, which is (at this time) not supported by Node.js natively. That's why we installed Babel earlier. The easiest way to run ECMAScript 6 is to use the babel-node binary, which NPM installs in the node_modules/.bin/ directory of your project. Thus, running the script looks like this:
./node_modules/.bin/babel-node get-account-info.js
Output:
getting account info for rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn
{ sequence: 359,
xrpBalance: '75.181663',
ownerCount: 4,
previousInitiatedTransactionID: 'E5C6DD25B2DCF534056D98A2EFE3B7CFAE4EBC624854DE3FA436F733A56D8BD9',
previousAffectingTransactionID: 'E5C6DD25B2DCF534056D98A2EFE3B7CFAE4EBC624854DE3FA436F733A56D8BD9',
previousAffectingTransactionLedgerVersion: 18489336 }
getAccountInfo done
done and disconnected.
Understanding the script
Even for a simple script, there's a lot packed into that, including quite a few conventions that are part of standard JavaScript. Understanding these concepts will help you write better code using RippleAPI, so let's divide the sample code into smaller chunks that are easier to understand.
Script opening
'use strict';
const {RippleAPI} = require('ripple-lib');
The opening line enables strict mode. This is purely optional, but it helps you avoid some common pitfalls of JavaScript. See also: Restrictions on Code in Strict Mode.
The second line imports RippleAPI into the current scope using Node.js's require function. The destructuring assignment assigns it to the variable name RippleAPI instead of ripple-lib (which is the name of the package, for historical reasons).
Instantiating the API
const api = new RippleAPI({
server: 'wss://s1.ripple.com' // Public rippled server
});
This section creates a new instance of the RippleAPI class, assigning it to the variable api. (The const keyword means you can't reassign the value api to some other value. The internal state of the object can still change, though.)
The one argument to the constructor is an options object, which has a variety of options. The server parameter tells it where it should connect to a rippled server.
- The example
serversetting uses a secure WebSocket connection to connect to one of the public servers that Ripple (the company) operates. - If you don't include the
serveroption, RippleAPI runs in offline mode instead, which severely limits what you can do with it. - You can specify a Ripple Test Net server instead to connect to the parallel-world Test Network instead of the production Ripple Consensus Ledger.
- If you run your own
rippled, you can instruct it to connect to your local server. For example, you might sayserver: 'ws://localhost:5005'instead.
Connecting and Promises
api.connect().then(() => {
The connect() method is one of many RippleAPI methods that returns a Promise, which is a special kind of JavaScript object. A Promise is designed to perform some asynchronous operation, like querying a the Ripple Consensus Ledger.
When you get a Promise back from some expression (like api.connect()), you call the Promise's then method and pass in a callback function. Passing a function as an argument is conventional in JavaScript, taking advantage of how JavaScript functions are first-class objects.
When a Promise finishes with its asynchronous operations, the Promise runs the callback function you passed it. The return value from the then method is another Promise object, so you can "chain" that into another then method, or the Promise's catch method, which also takes a callback. The callback you provide to catch gets called if something goes wrong.
Finally, we have more new ECMAScript 6 syntax - an arrow function. Arrow functions are just a shorter way of defining anonymous functions, which is pretty convenient when you're defining lots of one-off functions as callbacks, like we are here. The syntax ()=> {...} is mostly equivalent to function() {...}. If you want an anonymous function with one parameter, you can use a syntax like info => {...} instead, which is basically just function(info) {...} as well.
Custom code
/* begin custom code ------------------------------------ */
const my_address = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
console.log('getting account info for',my_address);
return api.getAccountInfo(my_address);
}).then( info => {
console.log(info);
console.log('getAccountInfo done');
/* end custom code -------------------------------------- */
This is the part that really defines what this script does, so this is the part you will probably spend the most time customizing.
The example code looks up a Ripple account (belonging to this writer) by its address. You can substitute your own address, if you want.
The console.log() function is a built-in tool in both Node.js and web browsers, which writes out to the console; this example includes lots of console output to make it easier to understand what the code is doing.
Keep in mind that the example code starts in the middle of a callback function (called when RippleAPI finishes connecting). That function calls RippleAPI's getAccountInfo method, and returns the results.
The results of that API method are another Promise, so the line }).then( info => { passes in another anonymous callback function to run when the second Promise's asynchronous work is done. Unlike the previous case, this callback function takes one argument, called info, which holds the -- actual -- return value from the getAccountInfo API method. The rest of this callback function just outputs that return value to the console.
Cleanup
}).then(() => {
return api.disconnect();
}).then(()=> {
console.log('done and disconnected.');
}).catch(console.error);
The remainder of the sample code is mostly more boilerplate code. The first line ends the previous callback function, then chains to another callback to run when it ends. That method disconnects cleanly from the Ripple Consensus Ledger, and has yet another callback which writes to the console when it finishes.
Finally, we get to the catch method of this entire long Promise chain. If any of the Promises or their callback functions encounters an error, the callback provided here will run. One thing worth noting: instead of defining a new anonymous callback function here, we can just pass in the standard console.error function, which writes whatever arguments it gets out to the console. If you so desired, you could define a smarter callback function here which might intelligently catch certain error types.
Waiting for Validation
One of the biggest challenges in using the Ripple Consensus Ledger (or any decentralized system) is knowing the final, immutable transaction results. Even if you follow the best practices you still have to wait for the consensus process to finally accept or reject your transaction. The following example code demonstrates how to wait for the final outcome of a transaction:
'use strict';
/* import RippleAPI and support libraies*/
const {RippleAPI} = require('ripple-lib');
const assert = require('assert');
/* Credentials of the account placing the offer */
const my_addr = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
const my_secret = 's████████████████████████████';
/* Define the order to place here */
const my_order = {
'direction': 'buy',
'quantity': {
'currency': '',
'counterparty': '',
'value': ''
},
'totalPrice': {
'currency': '',
'counterparty': '',
'value': ''
}
};
/* milliseconds to wait between ledger checks*/
const INTERVAL = 1000;
/* Instantiate RippleAPI */
const api = new RippleAPI({server: 'wss://s1.ripple.com'});
/* number of ledgers to check for valid transaction before fail */
const ledgerOffset = 5;
const my_instructions = {maxLedgerVersionOffset: ledgerOffset};
/* function to verify a transaction is on the RCL */
function verifyTransaction(hash, options) {
console.log('Verifing Transaction');
return api.getTransaction(hash, options).then(data => {
console.log('Result: ', data.outcome.result);
console.log('Validated in Ledger: ', data.outcome.ledgerVersion);
console.log('Sequence: ', data.sequence);
return data.outcome.result === 'tesSUCCESS';
}).catch(error => {
/* if transaction not on current ledger try again until max ledger hit */
if (error instanceof api.errors.PendingLedgerVersionError) {
return new Promise((resolve, reject) => {
setTimeout(() => verifyTransaction(hash, options)
.then(resolve, reject), INTERVAL);
});
}
return result;// TODO: Fix this. It's currently undefined.
});
}
/* function to prepare, sign, and submit a transaction to the RCL
success verifies the transaction is being considered for the next ledger.
Still requires vlaidation */
function submitTransaction(lastClosedLedgerVersion, prepared, secret) {
const signedData = api.sign(prepared.txJSON, secret);
return api.submit(signedData.signedTransaction).then(data => {
console.log('Result: ', data.resultCode);
console.log('Message: ', data.resultMessage);
/* if transaction was not successfully submitted throw error */
assert.strictEqual(data.resultCode, 'tesSUCCESS');
/* if successfully submitted fire off validation workflow */
const options = {
minLedgerVersion: lastClosedLedgerVersion,
maxLedgerVersion: prepared.instructions.maxLedgerVersion
};
return new Promise((resolve, reject) => {
setTimeout(() => verifyTransaction(signedData.id, options)
.then(resolve, reject), INTERVAL);
});
});
}
api.connect().then(() => {
console.log('Connected');
return api.prepareOrder(my_addr, my_order, my_instructions);
}).then(prepared => {
console.log('Order Prepared');
return api.getLedger().then(ledger => {
console.log('Current Ledger', ledger.ledgerVersion);
return submitTransaction(ledger.ledgerVersion, prepared, my_secret);
});
}).then(() => {
api.disconnect().then(() => {
console.log('api disconnected');
process.exit();
});
}).catch(console.error);
