xrpl.js 2: update many mentions, more code

This commit is contained in:
mDuo13
2021-10-08 18:33:45 -07:00
parent 6fc9afbd7e
commit 64e915eeb2
22 changed files with 219 additions and 242 deletions

View File

@@ -1,5 +1,5 @@
---
html: get-started-using-node-js.html
html: get-started-using-javascript.html
parent: get-started.html
blurb: XRP Ledgerに照会するエントリーレベルのJavaScriptアプリケーションを構築します。
top_nav_name: JavaScript

View File

@@ -1,16 +1,18 @@
---
html: get-started-using-node-js.html
html: get-started-using-javascript.html
parent: get-started.html
blurb: Build an entry-level JavaScript application for querying the XRP Ledger in Node.js.
blurb: Build an entry-level JavaScript application for querying the XRP Ledger.
top_nav_name: JavaScript
top_nav_grouping: Get Started
filters:
- include_code
labels:
- Development
showcase_icon: assets/img/logos/javascript.svg
---
# Get Started Using JavaScript
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.
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 either Node.js or web browsers.
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).
@@ -22,29 +24,18 @@ 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 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
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
```
On some platforms, the binary is named `nodejs` instead:
```sh
nodejs --version
```
To follow this tutorial, you should have some familiarity with writing code in JavaScript and managing small JavaScript projects. In browsers, any modern web browser with JavaScript support should work fine. In Node.js, **version 14** is recommended. It may work with other versions, but they aren't regularly tested.
## Install with npm
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:
Start a new project by creating an empty folder, then change into that folder and use [NPM](https://www.npmjs.com/) to install the latest version of xrpl.js:
```sh
npm install xrpl
@@ -55,40 +46,55 @@ npm install xrpl
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.
Here are the basic steps you'll need to cover for almost any XRP Ledger project:
Here are some steps you use in many XRP Ledger projects:
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. [Import the library](#1-import-the-library)
1. [Connect to the XRP Ledger.](#2-connect-to-the-xrp-ledger)
1. [Generate a wallet.](#3-generate-wallet)
1. [Query the XRP Ledger.](#4-query-the-xrp-ledger)
1. [Listen for Events.](#5-listen-for-events)
### 1. Import the Library
### 1. Connect to the XRP Ledger
How you load `xrpl.js` into your project depends on your development environment:
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.
#### Web Browsers
**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.
Add a `<script>` tag such as the following to your HTML:
```html
<script src="https://unpkg.com/xrpl@2.0.0/build/xrpl-latest-min.js"></script>
```
You can load the library from a CDN as in the above example, or download a release and host it on your own website.
***TODO: get a working CDN URL when released***
This loads the module into the top level as `xrpl`.
#### Node.js
Add the library using [npm](https://www.npmjs.com/). This updates your `package.json` file, or creates a new one if it didn't already exist:
```sh
npm install xrpl
```
Then import the library:
```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()
```
### 2. Connect to the XRP Ledger
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.
**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.
{{ include_code("_code-samples/get-started/js/base.js", language="js") }}
#### 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:
@@ -108,9 +114,9 @@ The sample code in the previous section shows you how to connect to the Testnet,
await client.connect()
### 2. Generate Wallet
### 3. Generate Wallet
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:
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:
{{ include_code("_code-samples/get-started/js/get-acct-info.js", start_with="// Create a wallet", end_before="// Get info", language="js") }}
@@ -126,23 +132,23 @@ Or, if you already have a seed encoded in [base58][], you can instantiate a Wall
const test_wallet = xrpl.Wallet.fromSeed("sn3nxiW7v8KXzPzAqzyHXbSSKNuN9") // Test secret; don't use for real
```
### 3. Query the XRP Ledger
### 4. Query the XRP Ledger
Use the Client's `request()` method to access the XRP Ledger's [WebSocket API](https://xrpl.org/request-formatting.html). For example:
{{ include_code("_code-samples/get-started/js/get-acct-info.js", start_with="// Get info", end_before="// Listen to ledger close events", language="js") }}
### 4. Listen for Events
### 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](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.
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.
{{ 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") }}
## Keep on Building
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:
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:
* [Send XRP](send-xrp.html).
* [Issue a Fungible Token](issue-a-fungible-token.html)
@@ -157,7 +163,7 @@ Now that you know how to use xrpl.js to connect to the XRP Ledger, generate a wa
- **Tutorials:**
- [Send XRP](send-xrp.html)
- **References:**
- [xrpl.js Reference](TODO: final link for new reference docs)
- [`xrpl.js` Reference](https://xrplf.github.io/xrpl.js/)
- [Public API Methods](public-rippled-methods.html)
- [API Conventions](api-conventions.html)
- [base58 Encodings](base58-encodings.html)

View File

@@ -11,7 +11,7 @@ labels:
The XRP Ledger is always online and entirely public. Anyone can access it **directly from a web browser** with source code like what's on this page.
The following example gets the latest [ledger version](ledgers.html) and a list of transactions that were newly-validated in that ledger version, using the [`getLedger()` method](rippleapi-reference.html#getledger). Try running it as-is, or change the code and see what happens.
The following example gets the latest [ledger version](ledgers.html) and a list of transactions that were newly-validated in that ledger version, using the [ledger method][]. Try running it as-is, or change the code and see what happens.
**Tip:** If you can, open your browser's Developer Tools by pressing **F12**. The "Console" tab provides a native JavaScript console and can give insight into what code is running on any webpage. <!-- SPELLING_IGNORE: f12 -->
@@ -21,69 +21,69 @@ The following example gets the latest [ledger version](ledgers.html) and a list
<!-- JS_EDITOR_START step2 -->
```js
const mainnet = new ripple.RippleAPI({
server: 'wss://s1.ripple.com'
});
(async function(api) {
async function main() {
const api = new xrpl.Client('wss://xrplcluster.com');
await api.connect();
let response = await api.getLedger({
includeTransactions: true
let response = await api.request({
"command": "ledger",
"ledger_index": "validated"
"transactions": true
});
console.log(response);
})(mainnet);
}
main()
```
```js
const mainnet = new ripple.RippleAPI({
server: 'wss://s.altnet.rippletest.net/'
});
(async function(api) {
async function main() {
const api = new xrpl.Client('wss://s.altnet.rippletest.net/');
await api.connect();
let response = await api.getLedger({
includeTransactions: true
});
let response = await api.request({
"command": "ledger",
"ledger_index": "validated"
"transactions": true
});
console.log(response);
})(mainnet);
}
main()
```
```js
const mainnet = new ripple.RippleAPI({
server: 'wss://s1.ripple.com'
});
(async function(api) {
async function main() {
const api = new xrpl.Client('wss://xrplcluster.com');
await api.connect();
let response = await api.getLedger({
includeTransactions: true
});
let tx_id = response.transactionHashes[0];
let response2 = await api.getTransaction(tx_id);
let response = await api.request({
"command": "ledger",
"ledger_index": "validated"
"transactions": true
});
let tx_id = response.result.transactions[0];
let response2 = await api.request({
"command": "tx",
"transaction": tx_id
});
console.log(response2);
})(mainnet);
}
main()
```
```js
const mainnet = new ripple.RippleAPI({
server: 'wss://s1.ripple.com'
});
(async function(api) {
async function main() {
const api = new xrpl.Client('wss://xrplcluster.com');
await api.connect();
let response = await api.getLedger({
includeTransactions: true
});
console.log('Total XRP: '+api.dropsToXrp(response.totalDrops));
})(mainnet);
let response = await api.request({
"command": "ledger",
"ledger_index": "validated"
"transactions": true
});
console.log('Total XRP: '+xrpl.dropsToXrp(response.result.ledger.total_coins));
}
main()
```
<!-- JS_EDITOR_END -->
@@ -100,7 +100,7 @@ Try editing the code above to do something different:
## Setup Steps
This page has the necessary prerequisites already loaded, but you can access the XRP Ledger from **any webpage** if you load [RippleAPI for JavaScript (ripple-lib)](rippleapi-reference.html) in that page's HTML. For example:
This page has the necessary prerequisites already loaded, but you can access the XRP Ledger from **any webpage** if you load [xrpl.js](https://github.com/XRPLF/xrpl.js/) in that page's HTML. For example:
```html
<script src="https://unpkg.com/ripple-lib@1.10.0/build/ripple-latest-min.js"></script>
@@ -115,3 +115,8 @@ When you're ready to move on, continue using the XRP Ledger with these resources
- [Use the RippleAPI Reference](rippleapi-reference.html) to see what else you can do.
- [Install `rippled`](install-rippled.html) to participate in the network.
- [Get Testnet XRP](xrp-testnet-faucet.html) to try sending and receiving payments.
<!--{# common link defs #}-->
{% include '_snippets/rippled-api-links.md' %}
{% include '_snippets/tx-type-links.md' %}
{% include '_snippets/rippled_versions.md' %}

View File

@@ -14,7 +14,7 @@ top_nav_grouping: Popular Pages
---
# Send XRP
This tutorial explains how to send a simple XRP Payment using ripple-lib for JavaScript, `xrpl-py` for Python, or xrpl4j for Java. First, we step through the process with the [XRP Ledger Testnet](parallel-networks.html). Then, we compare that to the additional requirements for doing the equivalent in production.
This tutorial explains how to send a simple XRP Payment using `xrpl.js` for JavaScript, `xrpl-py` for Python, or xrpl4j for Java. First, we step through the process with the [XRP Ledger Testnet](parallel-networks.html). Then, we compare that to the additional requirements for doing the equivalent in production.
**Tip:** Check out the [Code Samples](https://github.com/XRPLF/xrpl-dev-portal/tree/master/content/_code-samples) for a complete version of the code used in this tutorial.
@@ -26,7 +26,7 @@ This tutorial explains how to send a simple XRP Payment using ripple-lib for Jav
To interact with the XRP Ledger, you need to set up a dev environment with the necessary tools. This tutorial provides examples using the following options:
- **JavaScript** with the [ripple-lib (RippleAPI) library](https://github.com/XRPLF/xrpl.js/). See the [RippleAPI Beginners Guide](get-started-with-rippleapi-for-javascript.html) for detailed instructions on getting started.
- **JavaScript** with the [xrpl.js library](https://github.com/XRPLF/xrpl.js/). See [Get Started Using JavaScript](get-started-using-javascript.html) for setup steps.
- **Python** with the [`xrpl-py` library](https://xrpl-py.readthedocs.io/). See [Get Started using Python](get-started-using-python.html) for setup steps.
- **Java** with the [xrpl4j library](https://github.com/XRPLF/xrpl4j). See [Get Started Using Java](get-started-using-java.html) for setup steps.
@@ -110,7 +110,7 @@ The bare minimum set of instructions you must provide for an XRP Payment is:
Technically, a viable transaction must contain some additional fields, and certain optional fields such as `LastLedgerSequence` are strongly recommended. Some other language-specific notes:
- If you're using ripple-lib for JavaScript, you can use the [`prepareTransaction()` method](rippleapi-reference.html#preparetransaction) to automatically fill in good defaults for the remaining fields of a transaction.
- If you're using `xrpl.js` for JavaScript or TypeScript, you can use the [`Client.autofill()` method](TODO: link autofill) to automatically fill in good defaults for the remaining fields of a transaction.
- With `xrpl-py` for Python, you can use the models in `xrpl.models.transactions` to construct transactions as native Python objects.
- With xrpl4j for Java, you can use the model objects in the `xrpl4j-model` module to construct transactions as Java objects.
- Unlike the other libraries, you must provide the account `sequence` and the `signingPublicKey` of the source
@@ -156,7 +156,7 @@ _Java_
Signing a transaction uses your credentials to authorize the transaction on your behalf. The input to this step is a completed set of transaction instructions (usually JSON), and the output is a binary blob containing the instructions and a signature from the sender.
- **JavaScript:** Use the [sign() method](rippleapi-reference.html#sign) to sign the transaction with ripple-lib. The first argument is a string version of the JSON transaction to sign.
- **JavaScript:** Use the [sign() method of a Wallet instance](TODO: link sign) to sign the transaction with `xrpl.js`.
- **Python:** Use the [`xrpl.transaction.safe_sign_transaction()` method](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.transaction.html#xrpl.transaction.safe_sign_transaction) with a model and wallet object.
- **Java:** Use a [`SignatureService`](https://javadoc.io/doc/org.xrpl/xrpl4j-crypto-core/latest/org/xrpl/xrpl4j/crypto/signing/SignatureService.html) instance to sign the transaction. For this tutorial, use the [`SingleKeySignatureService`](https://javadoc.io/doc/org.xrpl/xrpl4j-crypto-bouncycastle/latest/org/xrpl/xrpl4j/crypto/signing/SingleKeySignatureService.html).
@@ -181,7 +181,7 @@ _Java_
The result of the signing operation is a transaction object containing a signature. Typically, XRP Ledger APIs expect a signed transaction to be the hexadecimal representation of the transaction's canonical [binary format](serialization.html), called a "blob".
- In ripple-lib, the signing API also returns the transaction's ID, or identifying hash, which you can use to look up the transaction later. This is a 64-character hexadecimal string that is unique to this transaction.
- In `xrpl.js`, the signing API also returns the transaction's ID, or identifying hash, which you can use to look up the transaction later. This is a 64-character hexadecimal string that is unique to this transaction.
- In `xrpl-py`, you can get the transaction's hash in the response to submitting it in the next step.
- In xrpl4j, `SignatureService.sign` returns a `SignedTransaction`, which contains the transaction's hash, which you can use to look up the transaction later.
@@ -196,8 +196,8 @@ The result of the signing operation is a transaction object containing a signatu
Now that you have a signed transaction, you can submit it to an XRP Ledger server, and that server will relay it through the network. It's also a good idea to take note of the latest validated ledger index before you submit. The earliest ledger version that your transaction could get into as a result of this submission is one higher than the latest validated ledger when you submit it. Of course, if the same transaction was previously submitted, it could already be in a previous ledger. (It can't succeed a second time, but you may not realize it succeeded if you aren't looking in the right ledger versions.)
- **JavaScript:** Use the [`submit()` method](rippleapi-reference.html#submit) to submit a transaction to the network. Use the [`getLedgerVersion()` method](rippleapi-reference.html#getledgerversion) to get the latest validated ledger index.
- **Python:** Use the [`xrpl.transaction.submit_transaction()` method](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.transaction.html#xrpl.transaction.submit_transaction) to submit a transaction to the network. Use the [`xrpl.ledger.get_latest_validated_ledger_sequence()` method](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.ledger.html#xrpl.ledger.get_latest_validated_ledger_sequence) to get the latest validated ledger index.
- **JavaScript:** Use the [`submitReliable()` method of the Client](TODO: link) to submit a transaction to the network and wait for the response.
- **Python:** Use the [`xrpl.transaction.send_reliable_submission()` method](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.transaction.html#xrpl.transaction.send_reliable_submission) to submit a transaction to the network and wait for a response.
- **Java:** Use the [`XrplClient.submit(SignedTransaction)` method](https://javadoc.io/doc/org.xrpl/xrpl4j-client/latest/org/xrpl/xrpl4j/client/XrplClient.html#submit(org.xrpl.xrpl4j.crypto.signing.SignedTransaction)) to submit a transaction to the network. Use the [`XrplClient.ledger()`](https://javadoc.io/doc/org.xrpl/xrpl4j-client/latest/org/xrpl/xrpl4j/client/XrplClient.html#ledger(org.xrpl.xrpl4j.model.client.ledger.LedgerRequestParams)) method to get the latest validated ledger index.
<!-- MULTICODE_BLOCK_START -->
@@ -348,15 +348,15 @@ Generating an address and secret doesn't get you XRP directly; you're only choos
### Connecting to the Production XRP Ledger
When you instantiate the `RippleAPI` object, you must specify a server that's synced with the appropriate XRP Ledger. For many cases, you can use Ripple's public servers, such as in the following snippet:
When you instantiate the `RippleAPI` object, you must specify a server that's synced with the appropriate XRP Ledger. For many cases, you can use [public servers](public-servers.html), such as in the following snippet:
<!-- MULTICODE_BLOCK_START -->
_JavaScript_
```js
ripple = require('ripple-lib')
api = new ripple.RippleAPI({server: 'wss://xrplcluster.com'})
const xrpl = require('xrpl')
const api = new xrpl.Client('wss://xrplcluster.com')
api.connect()
```
@@ -364,8 +364,7 @@ _Python_
```py
from xrpl.clients import JsonRpcClient
mainnet_url = "https://xrplcluster.com"
client = JsonRpcClient(mainnet_url)
client = JsonRpcClient("https://xrplcluster.com")
```
_Java_
@@ -384,8 +383,8 @@ If you [install `rippled`](install-rippled.html) yourself, it connects to the pr
_JavaScript_
```js
ripple = require('ripple-lib')
api = new ripple.RippleAPI({server: 'ws://localhost:6006'})
const xrpl = require('xrpl')
const api = new xrpl.Client('ws://localhost:6006')
api.connect()
```
@@ -393,8 +392,7 @@ _Python_
```py
from xrpl.clients import JsonRpcClient
mainnet_url = "http://localhost:5005"
client = JsonRpcClient(mainnet_url)
client = JsonRpcClient("http://localhost:5005")
```
_Java_
@@ -413,7 +411,7 @@ XrplClient xrplClient = new XrplClient(rippledUrl);
After completing this tutorial, you may want to try the following:
- Build [Reliable transaction submission](reliable-transaction-submission.html) for production systems.
- Consult [RippleAPI JavaScript Reference](rippleapi-reference.html), [`xrpl-py` Python Reference](https://xrpl-py.readthedocs.io/), or [xrpl4j Javadocs](https://javadoc.io/doc/org.xrpl/) for the full range of XRP Ledger functionality. <!-- SPELLING_IGNORE: javadocs -->
- Consult the your [client library](client-libraries.html)'s API reference for the full range of XRP Ledger functionality. <!-- SPELLING_IGNORE: javadocs -->
- Customize your [Account Settings](manage-account-settings.html).
- Learn how [Transaction Metadata](transaction-metadata.html) describes the outcome of a transaction in detail.
- Explore more [Payment Types](payment-types.html) such as Escrows and Payment Channels.