rippleapi quickstart - script explanation and submit-and-verify script

This commit is contained in:
mDuo13
2016-01-26 20:30:59 -08:00
parent b2be858b6b
commit d2f9d39144
5 changed files with 602 additions and 31 deletions

View File

@@ -44,23 +44,7 @@ Alternatively, you can [create a repo on GitHub](https://help.github.com/article
Here's a good template:
```
{
"name": "my_ripple_experiment",
"version": "0.0.1",
"license": "UNLICENSED",
"private": true,
"dependencies": {
"ripple-lib": "*",
"babel-cli": "^6.0.0",
"babel-preset-es2015": "*"
},
"babel": {
"presets": ["es2015"]
},
"devDependencies": {
"eslint": "*"
}
}
{% include 'code_samples/rippleapi_quickstart/package.json' %}
```
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](http://eslint.org/) (`eslint`) for checking your code quality.
@@ -96,8 +80,126 @@ git add .gitignore
git commit -m "ignore node_modules"
```
# First RippleAPI Script
# 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:
```
{% include 'code_samples/rippleapi_quickstart/get-account-info.js' %}
```
## 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](https://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/). This is purely optional, but it helps you avoid some common pitfalls of JavaScript. See also: [Restrictions on Code in Strict Mode](https://msdn.microsoft.com/library/br230269%28v=vs.94%29.aspx#Anchor_1).
The second line imports RippleAPI into the current scope using Node.js's require function. The [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) 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](rippleapi.html#parameters). The `server` parameter tells it where it should connect to a `rippled` server.
* The example `server` setting uses a secure WebSocket connection to connect to one of the public servers that Ripple (the company) operates.
* If you don't include the `server` option, RippleAPI runs in [offline mode](rippleapi.html#offline-functionality) instead, which severely limits what you can do with it.
* You can specify a [Ripple Test Net](https://ripple.com/build/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`](rippled-setup.html), you can instruct it to connect to your local server. For example, you might say `server: 'ws://localhost:5005'` instead.
### Connecting and Promises ###
```
api.connect().then(() => {
```
The [connect() method](rippleapi.html#connect) is one of many RippleAPI methods that returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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](https://en.wikipedia.org/wiki/First-class_function).
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). 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](https://github.com/mDuo13/)) 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`](rippleapi.html#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](rippleapi.html#boilerplate). 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](reliable_tx.html) you still have to wait for the [consensus process](https://ripple.com/knowledge_center/the-ripple-ledger-consensus-process/) to finally accept or reject your transaction. The following example code demonstrates how to wait for the final outcome of a transaction:
```
{% include 'code_samples/rippleapi_quickstart/submit-and-verify.js' %}
```