Get started: consolidate, start updating Node.js

This commit is contained in:
mDuo13
2021-10-05 17:22:15 -07:00
parent d04a12fc0d
commit 6fc9afbd7e
12 changed files with 141 additions and 591 deletions

View File

@@ -0,0 +1,39 @@
// Import the library
const xrpl = require("xrpl")
// Wrap code in an async function so we can use await
async function main() {
// Define the network client
const SERVER_URL = "https://s.altnet.rippletest.net:51234/"
const client = new xrpl.Client(SERVER_URL)
await client.connect()
// Create a wallet and fund it with the Testnet faucet:
const test_wallet = new xrpl.Wallet() // TODO: change to define based on fundWallet result
const fund_result = await client.fundWallet(test_wallet)
console.log(fund_result)
// Get info from the ledger about the address we just funded
const response = await client.request({
"command": "account_info",
"account": test_wallet.address,
"ledger_index": "validated"
})
console.log(response)
// Listen to 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
client.disconnect()
}
// call the async function
main()

View File

@@ -1,35 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>
<script type="application/javascript" src="assets/js/ripple-lib-1.9.1.min.js"></script>
<script>
console.log(ripple);
var api = new ripple.RippleAPI({server:'wss://s1.ripple.com/'});
api.connect().then(function() {
return api.getServerInfo();
}).then(function(server_info) {
document.body.innerHTML += "<p>Connected to rippled server!</p>" +
" <table>" +
" <tr><th>Version</th>" +
" <td>" + server_info.buildVersion + "</td></tr>" +
" <tr><th>Ledgers available</th>" +
" <td>" + server_info.completeLedgers + "</td></tr>" +
" <tr><th>hostID</th>" +
" <td>" + server_info.hostID + "</td></tr>" +
" <tr><th>Most Recent Validated Ledger Seq.</th>" +
" <td>" + server_info.validatedLedger.ledgerVersion + "</td></tr>" +
" <tr><th>Most Recent Validated Ledger Hash</th>" +
" <td>" + server_info.validatedLedger.hash + "</td></tr>" +
" <tr><th>Seconds since last ledger validated</th>" +
" <td>" + server_info.validatedLedger.age + "</td></tr>" +
" </table>";
});
</script>
<style type="text/css">
td, th { border: 1px solid black; padding: 5px; }
table { border-collapse: collapse; }
</style>
</head>
<body></body>
</html>

View File

@@ -1,201 +0,0 @@
# ESLint documentation can be found at http://eslint.org/docs/
env:
browser: true
node: true
amd: false
mocha: true
jasmine: false
es6: true
rules:
no-alert: 2
no-array-constructor: 2
no-arrow-condition: 0
no-bitwise: 0
no-caller: 2
no-case-declarations: 2
no-catch-shadow: 2
no-class-assign: 2
no-cond-assign: [2, 'always']
no-console: 0
no-const-assign: 2
no-constant-condition: 2
no-continue: 0
no-control-regex: 2
no-debugger: 2
no-delete-var: 2
no-div-regex: 0
no-dupe-class-members: 2
no-dupe-keys: 2
no-dupe-args: 2
no-duplicate-case: 2
no-else-return: 0
no-empty: 2
no-empty-character-class: 2
no-empty-label: 2
no-empty-pattern: 2
no-eq-null: 2
no-eval: 2
no-ex-assign: 2
no-extend-native: 2
no-extra-bind: 2
no-extra-boolean-cast: 2
no-extra-parens: [2, 'functions']
no-extra-semi: 2
no-fallthrough: 2
no-floating-decimal: 0
no-func-assign: 2
no-implicit-coercion: 2
no-implied-eval: 2
no-inline-comments: 0
no-inner-declarations: [2, 'functions']
no-invalid-regexp: 2
no-invalid-this: 0 # this rule would cause problems with mocha test cases
no-irregular-whitespace: 2
no-iterator: 2
no-label-var: 2
no-labels: 2
no-lone-blocks: 2
no-lonely-if: 2
no-loop-func: 2
no-mixed-requires: [0, false]
no-mixed-spaces-and-tabs: [2, false]
linebreak-style: [2, 'unix']
no-multi-spaces: 2
no-multi-str: 2
no-multiple-empty-lines: [2, {max: 2}]
no-native-reassign: 2
no-negated-condition: 0
no-negated-in-lhs: 2
no-nested-ternary: 0
no-new: 2
no-new-func: 2
no-new-object: 2
no-new-require: 0
no-new-wrappers: 2
no-obj-calls: 2
no-octal: 2
no-octal-escape: 2
no-param-reassign: 2
no-path-concat: 0
no-plusplus: 0
no-process-env: 0
no-process-exit: 0
no-proto: 2
no-redeclare: 2
no-regex-spaces: 2
no-restricted-modules: 0
no-restricted-syntax: 0
no-return-assign: 2
no-script-url: 2
no-self-compare: 2
no-sequences: 2
no-shadow: 2
no-shadow-restricted-names: 2
no-spaced-func: 2
no-sparse-arrays: 2
no-sync: 0
no-ternary: 0
no-trailing-spaces: 2
no-this-before-super: 2
no-throw-literal: 2
no-undef: 2
no-undef-init: 2
no-undefined: 0
no-unexpected-multiline: 2
no-underscore-dangle: 0
no-unneeded-ternary: 0
no-unreachable: 2
no-unused-expressions: 2
no-unused-vars: [2, {vars: 'all', args: 'all'}]
no-use-before-define: 2
no-useless-call: 2
no-useless-concat: 0
no-void: 2
no-var: 2
no-warning-comments: [0, {terms: ['todo', 'fixme', 'xxx'], location: 'start'}]
no-with: 2
no-magic-numbers: 0
array-bracket-spacing: [2, 'never']
arrow-body-style: 0
arrow-parens: [2, 'as-needed']
arrow-spacing: 2
accessor-pairs: 2
block-scoped-var: 2
block-spacing: 2
brace-style: 2
callback-return: 0
camelcase: 0
comma-dangle: 2
comma-spacing: 2
comma-style: 2
complexity: [0, 11]
computed-property-spacing: 2
consistent-return: 2
consistent-this: [2, 'self']
constructor-super: 2
curly: [2, 'all']
default-case: 0
dot-location: [2, 'property']
dot-notation: [2, {allowKeywords: true}]
eol-last: 2
eqeqeq: 2
func-names: 0
func-style: [2, 'declaration']
generator-star-spacing: 2
global-require: 0
guard-for-in: 0
handle-callback-err: 2
id-length: 0
indent: [2, 2, {SwitchCase: 1}]
init-declarations: 0
jsx-quotes: 0
key-spacing: [2, {beforeColon: false, afterColon: true}]
lines-around-comment: 0
max-depth: [0, 4]
max-len: [2, 80]
max-nested-callbacks: [0, 2]
max-params: [0, 4]
max-statements: [0, 10]
new-cap: 2
new-parens: 2
newline-after-var: 0
object-curly-spacing: [2, 'never']
object-shorthand: 0
one-var: [2, 'never']
operator-assignment: [0, 'always']
operator-linebreak: 0
padded-blocks: 0
prefer-arrow-callback: 0
prefer-const: 2
prefer-spread: 2
prefer-reflect: 0
prefer-template: 0
quote-props: 0
quotes: [2, 'single']
radix: 2
id-match: 0
require-jsdoc: 0
require-yield: 0
semi: 2
semi-spacing: 2
sort-vars: 0
space-after-keywords: 2
space-before-keywords: 2
space-before-blocks: 2
space-before-function-paren: [2, 'never']
space-in-parens: 2
space-infix-ops: 2
space-return-throw-case: 2
space-unary-ops: [2, {words: true, nonwords: false}]
spaced-comment: 2
strict: [2, 'global']
use-isnan: 2
valid-jsdoc: 2
valid-typeof: 2
vars-on-top: 0
wrap-iife: 0
wrap-regex: 0
yoda: [2, 'never']
ecmaFeatures:
jsx: true

View File

@@ -1,23 +0,0 @@
'use strict';
const RippleAPI = require('ripple-lib').RippleAPI;
const api = new RippleAPI({
server: 'wss://s1.ripple.com' // Public rippled server
});
api.connect().then(() => {
/* begin custom code ------------------------------------ */
const myAddress = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
console.log('getting account info for', myAddress);
return api.getAccountInfo(myAddress);
}).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);

View File

@@ -1,13 +0,0 @@
{
"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": "*"
},
"devDependencies": {
"eslint": "*"
}
}

File diff suppressed because one or more lines are too long

View File

@@ -90,7 +90,7 @@ Here are the basic steps you'll need to cover for almost any XRP Ledger project:
To make queries and submit transactions, you need to establish a connection to the XRP Ledger. To do this with `xrpl4j`,
you can use an [`XrplClient`](https://javadoc.io/doc/org.xrpl/xrpl4j-client/latest/org/xrpl/xrpl4j/client/XrplClient.html):
{{ include_code("_code-samples/xrpl4j/GetAccountInfo.java", start_with="// Construct a network client", end_before="// Create a Wallet using a WalletFactory", language="java") }}
{{ include_code("_code-samples/get-started/java/GetAccountInfo.java", start_with="// Construct a network client", end_before="// Create a Wallet using a WalletFactory", language="java") }}
#### Connect to the production XRP Ledger
@@ -122,7 +122,7 @@ an account on the Testnet or Devnet.
To make it easy to generate a new, random Wallet, `xrpl4j` provides the [`DefaultWalletFactory`](https://javadoc.io/doc/org.xrpl/xrpl4j-keypairs/latest/org/xrpl/xrpl4j/wallet/DefaultWalletFactory.html).
{{ include_code("_code-samples/xrpl4j/GetAccountInfo.java", start_with="// Create a Wallet using a WalletFactory", end_before="// Get the Classic and X-Addresses from testWallet", language="java") }}
{{ include_code("_code-samples/get-started/java/GetAccountInfo.java", start_with="// Create a Wallet using a WalletFactory", end_before="// Get the Classic and X-Addresses from testWallet", language="java") }}
The result of a call to `walletFactory.randomWallet(true).wallet()` is a [`Wallet` instance](https://javadoc.io/doc/org.xrpl/xrpl4j-keypairs/latest/org/xrpl/xrpl4j/wallet/Wallet.html):
@@ -142,7 +142,7 @@ Wallet {
In order to fund the account on the XRP Ledger, you can use a `FaucetClient` connected to the XRP Ledger Testnet:
{{ include_code("_code-samples/xrpl4j/GetAccountInfo.java", start_with="// Fund the account using the testnet Faucet", end_before="// Look up your Account Info", language="java") }}
{{ include_code("_code-samples/get-started/java/GetAccountInfo.java", start_with="// Fund the account using the testnet Faucet", end_before="// Look up your Account Info", language="java") }}
### {{n.next()}}. Query the XRP Ledger
@@ -150,7 +150,7 @@ You can query the XRP Ledger to get information about [a specific account](accou
Here, we'll use the [`XrplClient` we constructed](#1-connect-to-the-xrp-ledger) to look up information about the [wallet we generated](#2-generate-wallet) in the previous step.
{{ include_code("_code-samples/xrpl4j/GetAccountInfo.java", start_with="// Look up your Account Info", end_before="// Print the result", language="java") }}
{{ include_code("_code-samples/get-started/java/GetAccountInfo.java", start_with="// Look up your Account Info", end_before="// Print the result", language="java") }}
### {{n.next()}}. Putting it all together
@@ -163,7 +163,7 @@ Using these building blocks, we can create a simple Java app that:
```java
{% include '_code-samples/xrpl4j/GetAccountInfo.java' %}
{% include '_code-samples/get-started/java/GetAccountInfo.java' %}
```
To run the app, you can download the code from [Github](https://github.com/XRPLF/xrpl4j-sample) and run `GetAccountInfo` either

View File

@@ -8,27 +8,27 @@ labels:
- Development
showcase_icon: assets/img/logos/javascript.svg
---
# Get Started Using Node.js
# Get Started Using JavaScript
This tutorial guides you through the basics of building an XRP Ledger-connected application using [Node.js](http://nodejs.org/) and [RippleAPI](rippleapi-reference.html), a JavaScript/TypeScript client library for accessing the XRP Ledger. You can also use RippleAPI [straight from your browser](get-started.html).
This tutorial guides you through the basics of building an XRP Ledger-connected application in JavaScript or TypeScript using the [xrpl.js](https://github.com/XRPLF/xrpl.js/) client library in Node.js.
The scripts and config files used in this guide are [available in this website's GitHub Repository](https://github.com/XRPLF/xrpl-dev-portal/tree/master/content/_code-samples/rippleapi_quickstart).
<!--#{ keep multiple H1s so that all steps are surfaced in sidebar. Do not change H1 titles unless they provide a clear improvement bc they are linked to on external sites. }# -->
# Environment Setup
## Learning goals
The first step to using RippleAPI is setting up your development environment.
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 generate a wallet on the [Testnet](xrp-testnet-faucet.html) 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 simple JavaScript app or web-app.
## Requirements
## 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. RippleAPI requires Node.js v6 or higher. Ripple recommends using Node.js v10 LTS.
This step depends on your operating system. Ripple recommends using [the official instructions for installing Node.js using a package manager](https://nodejs.org/en/download/package-manager/) for your operating system. If the packages for Node.js and npm (Node Package Manager) are separate, install both. (This applies to Arch Linux, CentOS, Fedora, and RHEL.)
After you have installed Node.js, you can check the version of the `node` binary from a command line:
The xrpl.js library is intended for use with Node.js version 14. It may work with other versions, but they aren't regularly tested. If you have Node.js installed, you can check the version of the `node` binary from a command line:
```sh
node --version
@@ -42,322 +42,128 @@ nodejs --version
## Install Yarn
## Install with npm
RippleAPI uses Yarn to manage dependencies. Ripple recommends using Yarn v1.13.0.
This step depends on your operating system. Ripple recommends using [the official instructions for installing Yarn using a package manager](https://yarnpkg.com/en/docs/install#mac-stable) for your operating system.
After you have installed Yarn, you can check the version of the `yarn` binary from a command line:
Start a new project by creating an empty folder, then change into that folder and use NPM to install the latest version of xrpl.js:
```sh
yarn --version
npm install xrpl
```
## Start building
## Install RippleAPI and Dependencies
When you're working with the XRP Ledger, there are a few things you'll need to manage, whether you're adding XRP into your [wallet](wallets.html), integrating with the [decentralized exchange](decentralized-exchange.html), or [issuing tokens](issued-currencies.html). This tutorial walks you through basic patterns common to getting started with all of these use cases and provides sample code for implementing them.
Complete these steps to use Yarn to install RippleAPI and dependencies.
Here are the basic steps you'll need to cover for almost any XRP Ledger project:
1. [Connect to the XRP Ledger.](#1-connect-to-the-xrp-ledger)
1. [Generate a wallet.](#2-generate-wallet)
1. [Query the XRP Ledger.](#3-query-the-xrp-ledger)
### 1. Create a new directory for your project
### 1. Connect to the XRP Ledger
Create a folder called (for example) `my_ripple_experiment`:
To make queries and submit transactions, you need to establish a connection to the XRP Ledger. To do this with xrpl.js, you create an instance of the `Client` class and use the `connect()` method.
```sh
mkdir my_ripple_experiment && cd my_ripple_experiment
```
Optionally, start a [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) repository in that directory so you can track changes to your code.
```sh
git init
```
Alternatively, you can [create a repo on GitHub](https://docs.github.com/en/get-started/quickstart/create-a-repo/) to version and share your work. After setting it up, [clone the repo](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository/) to your local machine and `cd` into that directory.
### 2. Create a new `package.json` file for your project
Use the following template, which includes:
- RippleAPI itself (`ripple-lib`)
- (Optional) [ESLint](https://eslint.org/) (`eslint`) for checking code quality.
```json
{% include '_code-samples/rippleapi_quickstart/package.json' %}
```
<!-- SPELLING_IGNORE: eslint -->
### 3. Use Yarn to install RippleAPI and dependencies
Use Yarn to install RippleAPI and the dependencies defined in the `package.json` file you created for your project.
```sh
yarn
```
This installs RippleAPI and the dependencies into the local folder `node_modules/`.
The install process may end with a few warnings. You may safely ignore the following warnings:
```text
warning eslint > file-entry-cache > flat-cache > circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm WARN optional Skipping failed optional dependency /chokidar/fsevents:
npm WARN notsup Not compatible with your operating system or architecture: fsevents@1.0.6
```
# First RippleAPI Script
This script, `get-account-info.js`, fetches information about a hard-coded account. Use it to test that RippleAPI works:
**Tip:** Many network functions in xrpl.js use [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to return values asynchronously. The code samples here use the [`async/await` pattern](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) to wait for the actual result of the Promises.
```js
{% include '_code-samples/rippleapi_quickstart/get-account-info.js' %}
// Import the library
const xrpl = require("xrpl")
// Wrap code in an async function so we can use await
async function main() {
// Define the network client
const SERVER_URL = "https://s.altnet.rippletest.net:51234/"
const client = new xrpl.Client(SERVER_URL)
await client.connect()
// ... custom code goes here
// Disconnect when done so Node.js can end the process
client.disconnect()
}
main()
```
#### Connect to the production XRP Ledger
The sample code in the previous section shows you how to connect to the Testnet, which is one of the available [parallel networks](parallel-networks.html). When you're ready to integrate with the production XRP Ledger, you'll need to connect to the Mainnet. You can do that in two ways:
* By [installing the core server](install-rippled.html) (`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](connect-your-rippled-to-the-xrp-test-net.html). [There are good reasons to run your own core server](the-rippled-server.html#reasons-to-run-your-own-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](https://github.com/ripple/rippled/blob/c0a0b79d2d483b318ce1d82e526bd53df83a4a2c/cfg/rippled-example.cfg#L1562) 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()
## Run the Script
### 2. Generate Wallet
Run your first RippleAPI script using this command:
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 wallet like this:
```sh
node get-account-info.js
```
{{ include_code("_code-samples/get-started/js/get-acct-info.js", start_with="// Create a wallet", end_before="// Get info", language="js") }}
Output:
```text
getting account info for rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn
{ sequence: 359,
xrpBalance: '75.181663',
ownerCount: 4,
previousInitiatedTransactionID: 'E5C6DD25B2DCF534056D98A2EFE3B7CFAE4EBC624854DE3FA436F733A56D8BD9',
previousAffectingTransactionID: 'E5C6DD25B2DCF534056D98A2EFE3B7CFAE4EBC624854DE3FA436F733A56D8BD9',
previousAffectingTransactionLedgerVersion: 18489336 }
getAccountInfo done
done and disconnected.
```
## Understand the Script
In addition to RippleAPI-specific code, this script uses syntax and conventions that are recent developments in JavaScript. Let's divide the sample code into smaller chunks to explain each one.
### Script opening
If you just want to generate keys, you can create a new Wallet instance like this:
```js
'use strict';
const RippleAPI = require('ripple-lib').RippleAPI;
const test_wallet = new xrpl.Wallet()
```
The opening line enables [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). This is purely optional, but it helps you avoid some common pitfalls of JavaScript.
The second line imports RippleAPI into the current scope using Node.js's require function. RippleAPI is one of [the modules `ripple-lib` exports](https://github.com/XRPLF/xrpl.js/blob/develop/src/index.ts).
### Instantiating the API
Or, if you already have a seed encoded in [base58][], you can instantiate a Wallet from it like this:
```js
const api = new RippleAPI({
server: 'wss://s1.ripple.com' // Public rippled server
});
const test_wallet = xrpl.Wallet.fromSeed("sn3nxiW7v8KXzPzAqzyHXbSSKNuN9") // Test secret; don't use for real
```
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.)
### 3. Query the XRP Ledger
The one argument to the constructor is an options object, which has [a variety of options](rippleapi-reference.html#parameters). The `server` parameter tells it where it should connect to a `rippled` server.
Use the Client's `request()` method to access the XRP Ledger's [WebSocket API](https://xrpl.org/request-formatting.html). For example:
- The example `server` setting uses a secure WebSocket connection to connect to one of the public servers that Ripple (the company) runs.
- If you don't include the `server` option, RippleAPI runs in [offline mode](rippleapi-reference.html#offline-functionality) instead, which only provides methods that don't need network connectivity.
- You can specify a [XRP Ledger Test Net](xrp-test-net-faucet.html) server instead to connect to the parallel-world Test Network instead of the production XRP Ledger.
- If you [run your own `rippled`](install-rippled.html), you can instruct it to connect to your local server. For example, you might say `server: 'ws://localhost:5005'` instead.
{{ include_code("_code-samples/get-started/js/get-acct-info.js", start_with="// Get info", end_before="// Listen to ledger close events", language="js") }}
### Connecting and Promises
### 4. Listen for Events
```js
api.connect().then(() => {
```
You can set up handlers for various types of events in xrpl.js, such as whenever the XRP Ledger's [consensus process](intro-to-consensus.html) produces a new [ledger version](ledgers.html). 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 [connect() method](rippleapi-reference.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 do an asynchronous operation that returns a value later, such as querying the XRP Ledger.
{{ include_code("_code-samples/get-started/js/get-acct-info.js", start_with="// Listen to ledger close events", end_before="// Disconnect when done", language="js") }}
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 pass to `catch` gets called if something goes wrong.
## Keep on Building
The example uses [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), a shorter way of defining anonymous functions. This is convenient for defining lots of one-off functions as callbacks. 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 almost the same as `function(info) {...}` syntax.
Now that you know how to use xrpl.js to connect to the XRP Ledger, generate a wallet, and look up information about an account, you can also:
### Custom code
```js
/* begin custom code ------------------------------------ */
const myAddress = 'rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn';
console.log('getting account info for', myAddress);
return api.getAccountInfo(myAddress);
}).then(info => {
console.log(info);
console.log('getAccountInfo done');
/* end custom code -------------------------------------- */
```
This is the part that you change to do whatever you want the script to do.
The example code looks up an XRP Ledger account by its address. Try running the code with different addresses to see different results.
The `console.log()` function is built into both Node.js and web browsers, and 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-reference.html#getaccountinfo) method, and returns the results.
The `getAccountInfo` API method returns another Promise, so the line `}).then( info => {` defines another anonymous callback function to run when this Promise's asynchronous work is done. Unlike the previous case, this callback function takes one argument, called `info`, which holds the asynchronous return value from the `getAccountInfo` API method. The rest of this callback function outputs that return value to the console.
### Cleanup
```js
}).then(() => {
return api.disconnect();
}).then(() => {
console.log('done and disconnected.');
}).catch(console.error);
```
The rest of the sample code is more [standard setup code](rippleapi-reference.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 XRP Ledger, and has yet another callback which writes to the console when it finishes. If your script waits on [RippleAPI events](rippleapi-reference.html#api-events), do not disconnect until you are done waiting for events.
The `catch` method ends this Promise chain. The callback provided here runs if any of the Promises or their callback functions encounters an error. In this case, we pass the standard `console.error` function, which writes to the console, instead of defining a custom callback. You could define a smarter callback function here to intelligently catch certain error types.
# Waiting for Validation
Most transactions are validated and have a final result in one or two ledger versions, about 2-7 seconds after submission. However, when things don't go quite as planned, it can be tricky to know what a transaction's final, immutable results are. Even if you [follow the best practices](reliable-transaction-submission.html) you still have to wait for the [consensus process](consensus.html) to finally accept or reject your transaction.
The [submit-and-verify code sample](https://github.com/XRPLF/xrpl-dev-portal/tree/master/content/_code-samples/submit-and-verify/) demonstrates how to submit a transaction and wait for it to have a final result.
In rare cases (particularly with a large delay, a brief network outage, or a loss of power), the `rippled` server may be missing a ledger version between when you submitted the transaction and when you determined that the network validated the last ledger version that the transaction . In this case, you cannot be definitively sure whether the transaction has failed, or has been included in one of the missing ledger versions.
If you are the administrator of the `rippled` server, you can [manually request the missing ledger(s)](ledger_request.html). Otherwise, you can try checking the ledger history using a different server. Several [public full-history servers](public-servers.html) are available for this purpose.
See [Reliable Transaction Submission](reliable-transaction-submission.html) for a more thorough explanation.
# RippleAPI in Web Browsers
RippleAPI can also be used in a web browser. To access it, load [RippleAPI for JavaScript (ripple-lib)](rippleapi-reference.html) in your site's HTML. For example:
<!-- MULTICODE_BLOCK_START -->
_unpkg_
```html
<script src="https://unpkg.com/ripple-lib@1.10.0/build/ripple-latest-min.js"></script>
```
_jsDelivr_
```html
<script src="https://cdn.jsdelivr.net/npm/ripple-lib@1.10.0/build/ripple-latest-min.js"></script>
```
<!-- MULTICODE_BLOCK_END -->
Instead of using Node.js's "require" syntax, the browser version creates a global variable named `ripple`, which contains the `RippleAPI` class.
<!-- SPELLING_IGNORE: lodash, unpkg, jsdelivr -->
## Build a Browser-Compatible Version of RippleAPI
You can also build a browser-compatible version of the code yourself. Use the following steps to build it from the source code.
### 1. Download a copy of the RippleAPI git repository
If you have [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) installed, you can clone the repository and check out the **master** branch, which always has the latest official release:
```
git clone https://github.com/XRPLF/xrpl.js.git
cd ripple-lib
git checkout master
```
Alternatively, you can download an archive (`.zip` or `.tar.gz`) of a specific release from the [RippleAPI releases page](https://github.com/XRPLF/xrpl.js/releases) and extract it.
### 2. Install Yarn
Use these instructions to [install Yarn](#install-yarn).
### 3. Install dependencies using Yarn
```
yarn
```
### 4. Build with Yarn
RippleAPI comes with the necessary dependencies and code to build it for the browser. Trigger the build script as follows:
```sh
yarn run build
```
Output:
```text
yarn run v1.22.4
$ yarn build:schemas && yarn build:lib && yarn build:web
$ mkdir -p dist/npm/common && cp -r src/common/schemas dist/npm/common/
$ tsc --build
$ webpack
Done in 10.29s.
```
This may take a while. At the end, the build process creates a new `build/` folder, which contains the files you want.
The file `build/ripple-latest.js` is a direct export of RippleAPI (whatever version you built) ready to be used in browsers. The file ending in `build/ripple-latest-min.js` is the same thing, but with the content [minified](https://en.wikipedia.org/wiki/Minification_%28programming%29) for faster loading. <!-- SPELLING_IGNORE: minified -->
## Demo RippleAPI in a Browser
The following HTML file demonstrates basic usage of the browser version of RippleAPI to connect to a public `rippled` server and report information about that server.
[**`browser-demo.html`**](https://github.com/XRPLF/xrpl-dev-portal/blob/master/content/_code-samples/rippleapi_quickstart/browser-demo.html "Source on GitHub")
```
{% include '_code-samples/rippleapi_quickstart/browser-demo.html' %}
```
<!-- SPELLING_IGNORE: cdnjs -->
You can also see and edit a similar, live browser demo on the [Get Started](get-started.html) page.
* [Send XRP](send-xrp.html).
* [Issue a Fungible Token](issue-a-fungible-token.html)
* [Set up secure signing](set-up-secure-signing.html) for your account.
## See Also
- **Concepts:**
- [XRP Ledger Overview](xrp-ledger-overview.html)
- [Software Ecosystem](software-ecosystem.html)
- [Client Libraries](client-libraries.html)
- **Tutorials:**
- [Send XRP](send-xrp.html)
- **References:**
- [RippleAPI Reference](rippleapi-reference.html)
- [rippled API Conventions](api-conventions.html)
- [xrpl.js Reference](TODO: final link for new reference docs)
- [Public API Methods](public-rippled-methods.html)
- [API Conventions](api-conventions.html)
- [base58 Encodings](base58-encodings.html)
- [rippled Transaction Formats](transaction-formats.html)
- [Transaction Formats](transaction-formats.html)
<!--{# common link defs #}-->
{% include '_snippets/rippled-api-links.md' %}
{% include '_snippets/tx-type-links.md' %}
{% include '_snippets/rippled_versions.md' %}

View File

@@ -59,7 +59,7 @@ Here are the basic steps you'll need to cover for almost any XRP Ledger project:
To make queries and submit transactions, you need to establish a connection to the XRP Ledger. To do this with `xrpl-py`, use the [`xrp.clients` module](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.clients.html):
{{ include_code("_code-samples/xrpl-py/get-acct-info.py", start_with="# Define the network client", end_before="# Create a wallet using the testnet faucet:", language="py") }}
{{ include_code("_code-samples/get-started/py/get-acct-info.py", start_with="# Define the network client", end_before="# Create a wallet using the testnet faucet:", language="py") }}
#### Connect to the production XRP Ledger
@@ -92,7 +92,7 @@ To make it easy to create a wallet on the Testnet, `xrpl-py` provides the [`gene
{{ include_code("_code-samples/xrpl-py/get-acct-info.py", start_with="# Create a wallet using the testnet faucet:", end_before="# Create an account str from the wallet", language="py") }}
{{ include_code("_code-samples/get-started/py/get-acct-info.py", start_with="# Create a wallet using the testnet faucet:", end_before="# Create an account str from the wallet", language="py") }}
This method returns a [`Wallet` instance](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.wallet.html#xrpl.wallet.Wallet):
@@ -115,7 +115,7 @@ In this tutorial we only query details about the generated account from the XRP
To prepare the transaction:
{{ include_code("_code-samples/xrpl-py/prepare-payment.py", start_with="# Prepare payment", end_before="# print prepared payment", language="py") }}
{{ include_code("_code-samples/get-started/py/prepare-payment.py", start_with="# Prepare payment", end_before="# print prepared payment", language="py") }}
@@ -123,7 +123,7 @@ To prepare the transaction:
To sign the transaction:
{{ include_code("_code-samples/xrpl-py/prepare-payment.py", start_with="# Sign the transaction", end_before="# Print signed tx", language="py") }}
{{ include_code("_code-samples/get-started/py/prepare-payment.py", start_with="# Sign the transaction", end_before="# Print signed tx", language="py") }}
@@ -131,14 +131,14 @@ To sign the transaction:
To send the transaction:
{{ include_code("_code-samples/xrpl-py/prepare-payment.py", start_with="# Submit and send the transaction", end_before="# Print tx response", language="py") }}
{{ include_code("_code-samples/get-started/py/prepare-payment.py", start_with="# Submit and send the transaction", end_before="# Print tx response", language="py") }}
##### Derive an X-address
You can use `xrpl-py`'s [`xrpl.core.addresscodec`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.core.addresscodec.html) module to derive an [X-address](https://xrpaddress.info/) from the `Wallet.classic_address` field:
{{ include_code("_code-samples/xrpl-py/get-acct-info.py", start_with="# Derive an x-address from the classic address:", end_before="# Look up info about your account", language="py") }}
{{ include_code("_code-samples/get-started/py/get-acct-info.py", start_with="# Derive an x-address from the classic address:", end_before="# Look up info about your account", language="py") }}
The X-address format [packs the address and destination tag](https://github.com/XRPLF/XRPL-Standards/issues/6) into a more user-friendly value.
@@ -150,7 +150,7 @@ You can query the XRP Ledger to get information about [a specific account](accou
Here, we'll use `xrpl-py`'s [`xrpl.account`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.account.html) module to look up information about the [wallet we generated](#2-generate-wallet) in the previous step.
{{ include_code("_code-samples/xrpl-py/get-acct-info.py", start_with="# Look up info about your account", language="py") }}
{{ include_code("_code-samples/get-started/py/get-acct-info.py", start_with="# Look up info about your account", language="py") }}
@@ -164,7 +164,7 @@ Using these building blocks, we can create a simple Python app that:
```python
{% include '_code-samples/xrpl-py/get-acct-info.py' %}
{% include '_code-samples/get-started/py/get-acct-info.py' %}
```
To run the app, you can copy and paste the code into an editor or IDE and run it from there. Or you could download the file from the [XRP Ledger Dev Portal repo](https://github.com/XRPLF/xrpl-dev-portal/tree/master/content/_code-samples/xrpl-py) and run it locally:
@@ -172,7 +172,7 @@ To run the app, you can copy and paste the code into an editor or IDE and run it
```sh
git clone git@github.com:XRPLF/xrpl-dev-portal.git
cd xrpl-dev-portal/content/_code-samples/xrpl-py/get-acct-info.py
cd xrpl-dev-portal/content/_code-samples/get-started/py/get-acct-info.py
python3 get-acct-info.py
```