Compare commits

...

8 Commits

Author SHA1 Message Date
Maria Shodunke
eec9c977fa WIP 2025-11-19 17:43:58 +00:00
Rome Reginelli
003927517f Merge pull request #3379 from XRPLF/rr-mpt-dupe-flag
Remove duplicate flags field in sample JSON
2025-11-14 12:19:31 -08:00
Rome Reginelli
9c8c231900 Remove duplicate flags field in sample JSON 2025-11-11 15:53:25 -08:00
Maria Shodunke
01ed3055ec Merge pull request #3299 from XRPLF/python-get-started-code-walkthrough
Add Get Started Walkthrough for Python
2025-11-06 10:17:26 +00:00
Maria Shodunke
eb174b8700 Add review comments 2025-11-06 09:57:51 +00:00
Maria Shodunke
9e96d40799 Add Get Started Walkthrough for Python 2025-11-06 09:57:51 +00:00
Maria Shodunke
d6b55ab177 Merge pull request #3375 from XRPLF/build-fix
Fix for build failure
2025-11-06 09:31:21 +00:00
Maria Shodunke
d8b216bdd7 Fix for build failure 2025-11-05 14:43:17 +00:00
11 changed files with 414 additions and 175 deletions

View File

@@ -47,6 +47,7 @@ export function blogPosts() {
actions.createSharedData('blog-posts', { blogPosts: sortedPosts }); actions.createSharedData('blog-posts', { blogPosts: sortedPosts });
actions.addRouteSharedData('/blog/', 'blog-posts', 'blog-posts'); actions.addRouteSharedData('/blog/', 'blog-posts', 'blog-posts');
actions.addRouteSharedData('/ja/blog/', 'blog-posts', 'blog-posts'); actions.addRouteSharedData('/ja/blog/', 'blog-posts', 'blog-posts');
actions.addRouteSharedData('/es-es/blog/', 'blog-posts', 'blog-posts');
} catch (e) { } catch (e) {
console.log(e); console.log(e);
} }

View File

@@ -44,6 +44,7 @@ export function codeSamples() {
}); });
actions.addRouteSharedData('/resources/code-samples/', 'code-samples', 'code-samples'); actions.addRouteSharedData('/resources/code-samples/', 'code-samples', 'code-samples');
actions.addRouteSharedData('/ja/resources/code-samples/', 'code-samples', 'code-samples'); actions.addRouteSharedData('/ja/resources/code-samples/', 'code-samples', 'code-samples');
actions.addRouteSharedData('/es-es/resources/code-samples/', 'code-samples', 'code-samples');
} catch (e) { } catch (e) {
console.log(e); console.log(e);
} }

View File

@@ -0,0 +1,62 @@
# Get Started Using Python Library
Connects to the XRP Ledger and gets account information using Python.
To download the source code, see [Get Started Using Python Library](http://xrpl.org/docs/tutorials/python/build-apps/get-started).
## Run the Code
Quick setup and usage:
```sh
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python ./get-acct-info.py
```
You should see output similar to the following:
```sh
Creating a new wallet and funding it with Testnet XRP...
Attempting to fund address ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
Faucet fund successful.
Wallet: ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
Account Testnet Explorer URL:
https://testnet.xrpl.org/accounts/ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
Getting account info...
Response Status: ResponseStatus.SUCCESS
{
"account_data": {
"Account": "ravbHNootpSNQkxyEFCWevSkHsFGDHfyop",
"Balance": "100000000",
"Flags": 0,
"LedgerEntryType": "AccountRoot",
"OwnerCount": 0,
"PreviousTxnID": "3DACF2438AD39F294C4EFF6132D5D88BCB65D2F2261C7650F40AC1F6A54C83EA",
"PreviousTxnLgrSeq": 12039759,
"Sequence": 12039759,
"index": "148E6F4B8E4C14018D679A2526200C292BDBC5AB77611BC3AE0CB97CD2FB84E5"
},
"account_flags": {
"allowTrustLineClawback": false,
"defaultRipple": false,
"depositAuth": false,
"disableMasterKey": false,
"disallowIncomingCheck": false,
"disallowIncomingNFTokenOffer": false,
"disallowIncomingPayChan": false,
"disallowIncomingTrustline": false,
"disallowIncomingXRP": false,
"globalFreeze": false,
"noFreeze": false,
"passwordSpent": false,
"requireAuthorization": false,
"requireDestinationTag": false
},
"ledger_hash": "CA624D717C4FCDD03BAD8C193F374A77A14F7D2566354A4E9617A8DAD896DE71",
"ledger_index": 12039759,
"validated": true
}
```

View File

@@ -1,34 +1,39 @@
# @chunk {"steps": ["connect-tag"]}
# Define the network client # Define the network client
from xrpl.clients import JsonRpcClient from xrpl.clients import JsonRpcClient
from xrpl.wallet import generate_faucet_wallet
from xrpl.core import addresscodec
from xrpl.models.requests.account_info import AccountInfo
import json
JSON_RPC_URL = "https://s.altnet.rippletest.net:51234/" JSON_RPC_URL = "https://s.altnet.rippletest.net:51234/"
client = JsonRpcClient(JSON_RPC_URL) client = JsonRpcClient(JSON_RPC_URL)
# @chunk-end
# Create a wallet using the testnet faucet: # @chunk {"steps": ["get-account-create-wallet-tag"]}
# Create a wallet using the Testnet faucet:
# https://xrpl.org/xrp-testnet-faucet.html # https://xrpl.org/xrp-testnet-faucet.html
from xrpl.wallet import generate_faucet_wallet print("\nCreating a new wallet and funding it with Testnet XRP...")
test_wallet = generate_faucet_wallet(client, debug=True) test_wallet = generate_faucet_wallet(client, debug=True)
test_account = test_wallet.classic_address
# Create an account str from the wallet print(f"Wallet: {test_account}")
test_account = test_wallet.address print(f"Account Testnet Explorer URL: ")
print(f" https://testnet.xrpl.org/accounts/{test_account}")
# Derive an x-address from the classic address: # @chunk-end
# https://xrpaddress.info/
from xrpl.core import addresscodec
test_xaddress = addresscodec.classic_address_to_xaddress(test_account, tag=12345, is_test_network=True)
print("\nClassic address:\n\n", test_account)
print("X-address:\n\n", test_xaddress)
# @chunk {"steps": ["query-xrpl-tag"]}
# Look up info about your account # Look up info about your account
from xrpl.models.requests.account_info import AccountInfo print("\nGetting account info...")
acct_info = AccountInfo( acct_info = AccountInfo(
account=test_account, account=test_account,
ledger_index="validated", ledger_index="validated",
strict=True, strict=True,
) )
response = client.request(acct_info) response = client.request(acct_info)
result = response.result result = response.result
print("response.status: ", response.status) print("Response Status: ", response.status)
import json
print(json.dumps(response.result, indent=4, sort_keys=True)) print(json.dumps(response.result, indent=4, sort_keys=True))
# @chunk-end

View File

@@ -0,0 +1 @@
xrpl-py==4.3.0

View File

@@ -1,35 +1,40 @@
import { stringToHex, hexToString } from '@xrplf/isomorphic/dist/utils/index.js' import {
import { MPTokenIssuanceCreateFlags, Client } from 'xrpl' MPTokenIssuanceCreateFlags,
Client,
encodeMPTokenMetadata,
decodeMPTokenMetadata
} from 'xrpl'
// Connect to network and get a wallet // Connect to network and get a wallet
const client = new Client('wss://s.devnet.rippletest.net:51233') const client = new Client('wss://s.devnet.rippletest.net:51233')
await client.connect() await client.connect()
console.log('Funding new wallet from faucet...') console.log('=== Funding new wallet from faucet...===')
const { wallet } = await client.fundWallet() const { wallet: issuer } = await client.fundWallet()
console.log(`Issuer address: ${issuer.address}`)
// Define metadata as JSON // Define metadata as JSON
const mpt_metadata = { const mpt_metadata = {
t: 'TBILL', ticker: 'TBILL',
n: 'T-Bill Yield Token', name: 'T-Bill Yield Token',
d: 'A yield-bearing stablecoin backed by short-term U.S. Treasuries and money market instruments.', desc: 'A yield-bearing stablecoin backed by short-term U.S. Treasuries and money market instruments.',
i: 'https://example.org/tbill-icon.png', icon: 'https://example.org/tbill-icon.png',
ac: 'rwa', asset_class: 'rwa',
as: 'treasury', asset_subclass: 'treasury',
in: 'Example Yield Co.', issuer_name: 'Example Yield Co.',
us: [ uris: [
{ {
u: 'https://exampleyield.co/tbill', uri: 'https://exampleyield.co/tbill',
c: 'website', category: 'website',
t: 'Product Page' title: 'Product Page'
}, },
{ {
u: 'https://exampleyield.co/docs', uri: 'https://exampleyield.co/docs',
c: 'docs', category: 'docs',
t: 'Yield Token Docs' title: 'Yield Token Docs'
} }
], ],
ai: { additional_info: {
interest_rate: '5.00%', interest_rate: '5.00%',
interest_type: 'variable', interest_type: 'variable',
yield_source: 'U.S. Treasury Bills', yield_source: 'U.S. Treasury Bills',
@@ -38,8 +43,13 @@ const mpt_metadata = {
} }
} }
// Convert JSON to a string (without excess whitespace), then string to hex // Encode the metadata.
const mpt_metadata_hex = stringToHex(JSON.stringify(mpt_metadata)) // The encodeMPTokenMetadata function converts the JSON metadata object into
// a compact, hex-encoded string, following the XLS-89 standard.
// https://xls.xrpl.org/xls/XLS-0089-multi-purpose-token-metadata-schema.html
console.log('\n=== Encoding metadata...===')
const mpt_metadata_hex = encodeMPTokenMetadata(mpt_metadata)
console.log("Encoded mpt_metadata_hex:", mpt_metadata_hex)
// Define the transaction, including other MPT parameters // Define the transaction, including other MPT parameters
const mpt_issuance_create = { const mpt_issuance_create = {
@@ -54,32 +64,40 @@ const mpt_issuance_create = {
} }
// Prepare, sign, and submit the transaction // Prepare, sign, and submit the transaction
console.log('Sending MPTokenIssuanceCreate transaction...') console.log('\n=== Sending MPTokenIssuanceCreate transaction...===')
const submit_response = await client.submitAndWait(mpt_issuance_create, { wallet, autofill: true }) const submit_response = await client.submitAndWait(mpt_issuance_create,
{ wallet, autofill: true }
)
// Check transaction results and disconnect // Check transaction results
console.log(JSON.stringify(submit_response, null, 2)) console.log('\n=== Checking MPTokenIssuanceCreate results...===')
// console.log(JSON.stringify(submit_response, null, 2))
if (submit_response.result.meta.TransactionResult !== 'tesSUCCESS') { if (submit_response.result.meta.TransactionResult !== 'tesSUCCESS') {
const result_code = response.result.meta.TransactionResult const result_code = submit_response.result.meta.TransactionResult
console.warn(`Transaction failed with result code ${result_code}.`) console.warn(`Transaction failed with result code ${result_code}.`)
await client.disconnect()
process.exit(1) process.exit(1)
} }
const issuance_id = submit_response.result.meta.mpt_issuance_id const issuance_id = submit_response.result.meta.mpt_issuance_id
console.log(`MPToken created successfully with issuance ID ${issuance_id}.`) console.log(`- MPToken created successfully with issuance ID: ${issuance_id}`)
// View the MPT issuance on the XRPL Explorer
console.log(`\n- Explorer URL: https://devnet.xrpl.org/mpt/${issuance_id}`)
// Look up MPT Issuance entry in the validated ledger // Look up MPT Issuance entry in the validated ledger
console.log('Confirming MPT Issuance metadata in the validated ledger.') console.log('\n=== Confirming MPT Issuance metadata in the validated ledger... ===')
const ledger_entry_response = await client.request({ const ledger_entry_response = await client.request({
"command": "ledger_entry", "command": "ledger_entry",
"mpt_issuance": issuance_id, "mpt_issuance": issuance_id,
"ledger_index": "validated" "ledger_index": "validated"
}) })
// Decode the metadata // Decode the metadata.
// The decodeMPTokenMetadata function takes a hex-encoded string representing MPT metadata,
// decodes it to a JSON object, and expands any compact field names to their full forms.
const metadata_blob = ledger_entry_response.result.node.MPTokenMetadata const metadata_blob = ledger_entry_response.result.node.MPTokenMetadata
const decoded_metadata = JSON.parse(hexToString(metadata_blob)) const decoded_metadata = decodeMPTokenMetadata(metadata_blob)
console.log('Decoded metadata:', decoded_metadata) console.log('Decoded MPT metadata: ', decoded_metadata)
// Disconnect from the client
client.disconnect() client.disconnect()

View File

@@ -1,6 +1,6 @@
{ {
"dependencies": { "dependencies": {
"xrpl": "^4.4.0" "xrpl": "^4.4.3"
}, },
"type": "module" "type": "module"
} }

View File

@@ -1 +1 @@
xrpl-py==4.3.0 xrpl-py==4.4.3

View File

@@ -24,7 +24,6 @@ This example assumes that the issuer of the token is the signer of the transacti
"AssetScale": 4, "AssetScale": 4,
"TransferFee": 0, "TransferFee": 0,
"MaximumAmount": "50000000", "MaximumAmount": "50000000",
"Flags": 83659,
"MPTokenMetadata": "7B2274223A225442494C4C222C226E223A22542D42696C6C205969656C6420546F6B656E222C2264223A2241207969656C642D62656172696E6720737461626C65636F696E206261636B65642062792073686F72742D7465726D20552E532E205472656173757269657320616E64206D6F6E6579206D61726B657420696E737472756D656E74732E222C2269223A226578616D706C652E6F72672F7462696C6C2D69636F6E2E706E67222C226163223A22727761222C226173223A227472656173757279222C22696E223A224578616D706C65205969656C6420436F2E222C227573223A5B7B2275223A226578616D706C657969656C642E636F2F7462696C6C222C2263223A2277656273697465222C2274223A2250726F647563742050616765227D2C7B2275223A226578616D706C657969656C642E636F2F646F6373222C2263223A22646F6373222C2274223A225969656C6420546F6B656E20446F6373227D5D2C226169223A7B22696E7465726573745F72617465223A22352E303025222C22696E7465726573745F74797065223A227661726961626C65222C227969656C645F736F75726365223A22552E532E2054726561737572792042696C6C73222C226D617475726974795F64617465223A22323034352D30362D3330222C226375736970223A22393132373936525830227D7D", "MPTokenMetadata": "7B2274223A225442494C4C222C226E223A22542D42696C6C205969656C6420546F6B656E222C2264223A2241207969656C642D62656172696E6720737461626C65636F696E206261636B65642062792073686F72742D7465726D20552E532E205472656173757269657320616E64206D6F6E6579206D61726B657420696E737472756D656E74732E222C2269223A226578616D706C652E6F72672F7462696C6C2D69636F6E2E706E67222C226163223A22727761222C226173223A227472656173757279222C22696E223A224578616D706C65205969656C6420436F2E222C227573223A5B7B2275223A226578616D706C657969656C642E636F2F7462696C6C222C2263223A2277656273697465222C2274223A2250726F647563742050616765227D2C7B2275223A226578616D706C657969656C642E636F2F646F6373222C2263223A22646F6373222C2274223A225969656C6420546F6B656E20446F6373227D5D2C226169223A7B22696E7465726573745F72617465223A22352E303025222C22696E7465726573745F74797065223A227661726961626C65222C227969656C645F736F75726365223A22552E532E2054726561737572792042696C6C73222C226D617475726974795F64617465223A22323034352D30362D3330222C226375736970223A22393132373936525830227D7D",
"Fee": "12", "Fee": "12",
"Flags": 122, "Flags": 122,

View File

@@ -0,0 +1,149 @@
---
seo:
description: Issue a Multi-Purpose Token (MPT) with arbitrary metadata on the XRP Ledger.
metadata:
indexPage: true
labels:
- Multi-Purpose Token
- MPT
- Token Issuance
---
# Issue a Multi-Purpose Token (MPT)
A [Multi-Purpose Token (MPT)](../../../concepts/tokens/fungible-tokens/multi-purpose-tokens.md) lets you to quickly access powerful, built-in tokenization features on the XRP Ledger with minimal code.
This tutorial shows you how to issue an MPT with on-chain metadata such as the token's ticker, name, or description, encoded according to the MPT [metadata schema](../../../concepts/tokens/fungible-tokens/multi-purpose-tokens.md#metadata-schema) defined in [XLS-89](https://xls.xrpl.org/xls/XLS-0089-multi-purpose-token-metadata-schema.html).
## Goals
By the end of this tutorial, you will be able to:
- Issue a new MPT using the `MPTokenIssuanceCreate` transaction.
- Encode or decode token metadata following MPT standards best practices.
## Prerequisites
To complete this tutorial, you should:
- Have a basic understanding of the XRP Ledger and token issuance.
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library](https://github.com/XRPLF/xrpl.js). See [Get Started Using JavaScript](../../javascript/build-apps/get-started.md) for setup steps.
## Source Code
You can find the complete source code for this tutorial's example in the [code samples section of this website's repository](https://github.com/XRPLF/xrpl-dev-portal/tree/master/_code-samples/issue-mpt-with-metadata).
## Steps
### 1. Install dependencies
{% tabs %}
{% tab label="Javascript" %}
From the code sample folder, use npm to install dependencies:
```bash
npm install xrpl
```
{% /tab %}
{% /tabs %}
### 2. Set up client and fund issuer wallet
Import the client library, instantiate a client to connect to the XRPL, and fund a new wallet to act as the token issuer.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" before="// Define metadata as JSON" /%}
{% /tab %}
{% /tabs %}
### 3. Define and encode MPT metadata
Define your token's metadata as a JSON object:
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Define metadata as JSON" before="// Encode the metadata" /%}
{% /tab %}
{% /tabs %}
The metadata schema supports both long field names (e.g., `ticker`, `name`, `desc`) and compact short keys (e.g., `t`, `n`, `d`). To save space on the ledger, its recommended to use short key names. The MPT metadata field has a 1024-byte limit, so using compact keys allows you to include more information.
The SDK libraries provide utility functions to encode or decode the metadata for you, so you don't have to. If long field names are provided in the metadata JSON, the _encoding_ utility function automatically shortens them to their compact key equivalents before encoding. Similarly, when decoding, the _decoding_ utility function converts the shorthands back to the respective long names.
{% tabs %}
{% tab label="Javascript" %}
Use the `encodeMPTokenMetadata()` function to encode metadata with `xrpl.js`.
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Encode the metadata" before="// Define the transaction" /%}
{% /tab %}
{% /tabs %}
{% admonition type="warning" name="Warning" %}
While the encoding utility formats the JSON for you correctly and replaces the full key names with shorthands, it does **not** validate the metadata content or size.
{% /admonition %}
### 4. Prepare the MPTokenIssuanceCreate transaction
Create the transaction object, specifying the issuer, asset scale, maximum amount, transfer/trade flags, and the encoded metadata.
| Field | Value |
|:------------------|:---------------------------------------------------------------------|
| `TransactionType` | The type of transaction, in this case `MPTokenIssuanceCreate`. |
| `Account` | The wallet address of the account that is issuing the MPT. |
| `AssetScale` | The number of decimal places for the token. |
| `MaximumAmount` | The maximum supply of the token to be issued. |
| `TransferFee` | The transfer fee (if any) to charge for token transfers. |
| `Flags` | Flags to control transfer/trade permissions. |
| `MPTokenMetadata` | The hex-encoded metadata for the token. |
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Define the transaction" before="// Prepare, sign, and submit the transaction" /%}
{% /tab %}
{% /tabs %}
### 5. Submit the transaction
Sign and submit the transaction, then wait for validation.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Prepare, sign, and submit the transaction" before="// Check transaction results" /%}
{% /tab %}
{% /tabs %}
### 6. Check transaction result
Verify that the transaction succeeded and retrieve the MPT issuance ID.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Check transaction results" before="// Look up MPT Issuance entry" /%}
{% /tab %}
{% /tabs %}
{% admonition type="info" name="Note" %}
A `tesSUCCESS` result indicates that the MPT issuance transaction was processed successfully and the token was created.
{% /admonition %}
### 7. Confirm MPT issuance and decode metadata
Look up the MPT issuance entry in the validated ledger and decode the metadata to verify it matches your original input.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/issue-mpt-with-metadata/js/issue-mpt-with-metadata.js" language="js" from="// Look up MPT Issuance entry" /%}
{% /tab %}
{% /tabs %}
The _decoding_ utility function converts the metadata shorthand key names back to the respective long names.
## See Also
- **Concepts**:
- [Multi-Purpose Tokens (MPT)](../../../concepts/tokens/fungible-tokens/multi-purpose-tokens.md)
- **References**:
- [MPTokenIssuanceCreate Transaction](../../../references/protocol/transactions/types/mptokenissuancecreate.md)
{% raw-partial file="/docs/_snippets/common-links.md" /%}

View File

@@ -1,63 +1,97 @@
--- ---
seo: seo:
description: Build a Python app that interacts with the XRP Ledger. description: Build a Python app that interacts with the XRP Ledger.
top_nav_name: Python
top_nav_grouping: Get Started
labels: labels:
- Development - Development
--- ---
{% code-walkthrough
filesets=[
{
"files": ["/_code-samples/get-started/py/get-acct-info.py"],
"downloadAssociatedFiles": ["/_code-samples/get-started/py/requirements.txt","/_code-samples/get-started/py/get-acct-info.py", "/_code-samples/get-started/py/README.md"]
}
]
%}
# Get Started Using Python Library # Get Started Using Python Library
This tutorial walks you through the basics of building an XRP Ledger-connected application using [`xrpl-py`](https://github.com/XRPLF/xrpl-py), a pure [Python](https://www.python.org) library built to interact with the XRP Ledger using native Python models and methods. This tutorial walks you through the basics of building an XRP Ledger-connected application using the [`xrpl-py`](https://github.com/XRPLF/xrpl-py) client library, a pure [Python](https://www.python.org) library built to interact with the XRP Ledger using native Python models and methods.
This tutorial is intended for beginners and should take no longer than 30 minutes to complete. This tutorial is intended for beginners and should take no longer than 30 minutes to complete.
## Learning Goals ## Goals
In this tutorial, you'll learn: In this tutorial, you'll learn:
* The basic building blocks of XRP Ledger-based applications. - The basic building blocks of XRP Ledger-based applications.
* How to connect to the XRP Ledger using `xrpl-py`. - How to connect to the XRP Ledger using `xrpl-py`.
* How to get an account on the [Testnet](/resources/dev-tools/xrp-faucets) using `xrpl-py`. - How to get an account on the [Testnet](/resources/dev-tools/xrp-faucets) using `xrpl-py`.
* How to use the `xrpl-py` library to look up information about an account on the XRP Ledger. - How to use the `xrpl-py` library to look up information about an account on the XRP Ledger.
* How to put these steps together to create a Python app. - How to put these steps together to create a Python app.
## Requirements ## Prerequisites
The `xrpl-py` library supports [Python 3.7](https://www.python.org/downloads/) and later. To complete this tutorial, you should meet the following guidelines:
- Have a basic understanding of Python.
- Have installed [Python 3.7](https://www.python.org/downloads/) or later.
## Installation ## Source Code
The [`xrpl-py` library](https://github.com/XRPLF/xrpl-py) is available on [PyPI](https://pypi.org/project/xrpl-py/). Install with `pip`: <!-- SPELLING_IGNORE: pypi --> Click **Download** on the top right of the code preview panel to download the source code.
## Steps
```py Follow the steps to create a simple application with `xrpl-py`.
pip3 install xrpl-py
{% step id="import-tag" %}
### 1. Install Dependencies
Start a new project by creating an empty folder, then move into that folder and set up a Python virtual environment with the necessary dependencies:
```sh
# Create and activate a virtual environment
python -m venv .venv
source .venv/bin/activate
# Install the xrpl-py library
pip install xrpl-py
``` ```
## Start Building Alternatively, if you're using the downloaded source code, you can install all dependencies from the `requirements.txt` file:
When you're working with the XRP Ledger, there are a few things you'll need to manage, whether you're adding XRP to your [account](../../../concepts/accounts/index.md), integrating with the [decentralized exchange](../../../concepts/tokens/decentralized-exchange/index.md), or [issuing tokens](../../../concepts/tokens/index.md). This tutorial walks you through basic patterns common to getting started with all of these use cases and provides sample code for implementing them. ```sh
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
{% /step %}
Here are the basic steps you'll need to cover for almost any XRP Ledger project: ### 2. Connect to the XRP Ledger
1. [Connect to the XRP Ledger.](#1-connect-to-the-xrp-ledger) {% step id="connect-tag" %}
1. [Get an account.](#2-get-account) #### Connect to the XRP Ledger Testnet
1. [Query the XRP Ledger.](#3-query-the-xrp-ledger)
To make queries and submit transactions, you need to connect 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).
### 1. Connect to the XRP Ledger {% admonition type="info" name="Note" %}
The standard approach with `xrpl-py` is to use the JSON-RPC client. While a WebSocket client is available, it requires you to use `async`/`await` throughout your code. For most use cases, stick with JSON-RPC to avoid the complexity of asynchronous programming.
{% /admonition %}
To make queries and submit transactions, you need to connect 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): The sample code shows you how to connect to the Testnet, which is one of the available [parallel networks](../../../concepts/networks-and-servers/parallel-networks.md).
{% /step %}
{% code-snippet file="/_code-samples/get-started/py/get-acct-info.py" from="# Define the network client" before="# Create a wallet using the testnet faucet:" language="py" /%} {% step id="connect-mainnet-tag"%}
#### Connect to the XRP Ledger Mainnet
#### Connect to the production XRP Ledger
The sample code in the previous section shows you how to connect to the Testnet, which is a [parallel network](../../../concepts/networks-and-servers/parallel-networks.md) for testing where the money has no real value. 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: The sample code in the previous section shows you how to connect to the Testnet, which is a [parallel network](../../../concepts/networks-and-servers/parallel-networks.md) for testing where the money has no real value. 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](../../../infrastructure/installation/index.md) (`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](../../../infrastructure/configuration/connect-your-rippled-to-the-xrp-test-net.md). [There are good reasons to run your own core server](../../../concepts/networks-and-servers/index.md#reasons-to-run-your-own-server). If you run your own server, you can connect to it like so: - By [installing the core server](../../../infrastructure/installation/index.md) (`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](../../../infrastructure/configuration/connect-your-rippled-to-the-xrp-test-net.md). [There are good reasons to run your own core server](../../../concepts/networks-and-servers/index.md#reasons-to-run-your-own-server). If you run your own server, you can connect to it like so:
``` ```python
from xrpl.clients import JsonRpcClient from xrpl.clients import JsonRpcClient
JSON_RPC_URL = "http://localhost:5005/" JSON_RPC_URL = "http://localhost:5005/"
client = JsonRpcClient(JSON_RPC_URL) client = JsonRpcClient(JSON_RPC_URL)
@@ -65,146 +99,115 @@ The sample code in the previous section shows you how to connect to the Testnet,
See the example [core server config file](https://github.com/XRPLF/rippled/blob/c0a0b79d2d483b318ce1d82e526bd53df83a4a2c/cfg/rippled-example.cfg#L1562) for more information about default values. See the example [core server config file](https://github.com/XRPLF/rippled/blob/c0a0b79d2d483b318ce1d82e526bd53df83a4a2c/cfg/rippled-example.cfg#L1562) for more information about default values.
* By using one of the available [public servers][]: - By using one of the available [public servers][]:
``` ```python
from xrpl.clients import JsonRpcClient from xrpl.clients import JsonRpcClient
JSON_RPC_URL = "https://s2.ripple.com:51234/" JSON_RPC_URL = "https://s2.ripple.com:51234/"
client = JsonRpcClient(JSON_RPC_URL) client = JsonRpcClient(JSON_RPC_URL)
``` ```
{% /step %}
{% step id="get-account-create-wallet-tag" %}
### 2. Get account ### 3. Get account
To store value and execute transactions on the XRP Ledger, you need an account: a [set of keys](../../../concepts/accounts/cryptographic-keys.md#key-components) and an [address](../../../concepts/accounts/addresses.md) that's been [funded with enough XRP](../../../concepts/accounts/index.md#creating-accounts) to meet the [account reserve](../../../concepts/accounts/reserves.md). The address is the identifier of your account and you use the [private key](../../../concepts/accounts/cryptographic-keys.md#private-key) to sign transactions that you submit to the XRP Ledger. To store value and execute transactions on the XRP Ledger, you need an account: a [set of keys](../../../concepts/accounts/cryptographic-keys.md#key-components) and an [address](../../../concepts/accounts/addresses.md) that's been [funded with enough XRP](../../../concepts/accounts/index.md#creating-accounts) to meet the [account reserve](../../../concepts/accounts/reserves.md). The address is the identifier of your account and you use the [private key](../../../concepts/accounts/cryptographic-keys.md#private-key) to sign transactions that you submit to the XRP Ledger.
{% admonition type="success" name="Tip" %}
For testing and development purposes, you can use the [XRP Faucets](/resources/dev-tools/xrp-faucets) to generate keys and fund the account on the Testnet or Devnet. For production purposes, you should take care to store your keys and set up a [secure signing method](../../../concepts/transactions/secure-signing.md). Another difference in production is that XRP has real worth, so you can't get it for free from a faucet. For testing and development purposes, you can use the [XRP Faucets](/resources/dev-tools/xrp-faucets) to generate keys and fund the account on the Testnet or Devnet. For production purposes, you should take care to store your keys and set up a [secure signing method](../../../concepts/transactions/secure-signing.md). Another difference in production is that XRP has real worth, so you can't get it for free from a faucet.
{% /admonition %}
To create and fund an account on the Testnet, `xrpl-py` provides the [`generate_faucet_wallet`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.wallet.html#xrpl.wallet.generate_faucet_wallet) method: To create and fund an account on the Testnet, `xrpl-py` provides the [`generate_faucet_wallet`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.wallet.html#xrpl.wallet.generate_faucet_wallet) method. This method returns a [`Wallet` instance](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.wallet.html#xrpl.wallet.Wallet).
{% /step %}
{% code-snippet file="/_code-samples/get-started/py/get-acct-info.py" from="# Create a wallet using the testnet faucet:" before="# Create an account str from the wallet" language="py" /%} {% step id="query-xrpl-tag" %}
### 4. Query the XRP Ledger
This method returns a [`Wallet` instance](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.wallet.html#xrpl.wallet.Wallet):
```py
print(test_wallet)
# print output
public_key:: 022FA613294CD13FFEA759D0185007DBE763331910509EF8F1635B4F84FA08AEE3
private_key:: -HIDDEN-
classic_address: raaFKKmgf6CRZttTVABeTcsqzRQ51bNR6Q
```
#### Using the account
In this tutorial we only query details about the generated account from the XRP Ledger, but you can use the values in the `Wallet` instance to prepare, sign, and submit transactions with `xrpl-py`.
##### Prepare
To prepare the transaction:
{% code-snippet file="/_code-samples/get-started/py/prepare-payment.py" from="# Prepare payment" before="# print prepared payment" language="py" /%}
##### Sign and submit
To sign and submit the transaction:
{% code-snippet file="/_code-samples/get-started/py/prepare-payment.py" from="# Sign and submit the transaction" 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.address` field:
{% code-snippet file="/_code-samples/get-started/py/get-acct-info.py" from="# Derive an x-address from the classic address:" 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.
### 3. Query the XRP Ledger
You can query the XRP Ledger to get information about [a specific account](../../../references/http-websocket-apis/public-api-methods/account-methods/index.md), [a specific transaction](../../../references/http-websocket-apis/public-api-methods/transaction-methods/tx.md), the state of a [current or a historical ledger](../../../references/http-websocket-apis/public-api-methods/ledger-methods/index.md), and [the XRP Ledger's decentralized exchange](../../../references/http-websocket-apis/public-api-methods/path-and-order-book-methods/index.md). You need to make these queries, among other reasons, to look up account info to follow best practices for [reliable transaction submission](../../../concepts/transactions/reliable-transaction-submission.md). You can query the XRP Ledger to get information about [a specific account](../../../references/http-websocket-apis/public-api-methods/account-methods/index.md), [a specific transaction](../../../references/http-websocket-apis/public-api-methods/transaction-methods/tx.md), the state of a [current or a historical ledger](../../../references/http-websocket-apis/public-api-methods/ledger-methods/index.md), and [the XRP Ledger's decentralized exchange](../../../references/http-websocket-apis/public-api-methods/path-and-order-book-methods/index.md). You need to make these queries, among other reasons, to look up account info to follow best practices for [reliable transaction submission](../../../concepts/transactions/reliable-transaction-submission.md).
Here, we use `xrpl-py`'s [`xrpl.account`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.account.html) module to look up information about the [account we got](#2-get-account) in the previous step. Use the [account_info method][] to look up information about the account you got in the previous step. Use a request model like `AccountInfo` to validate the request format and catch errors sooner.
{% /step %}
{% step id="run-app-tag" %}
### 5. Run the Application
{% code-snippet file="/_code-samples/get-started/py/get-acct-info.py" from="# Look up info about your account" language="py" /%} Finally, in your terminal, run the application like so:
### 4. Putting it all together
Using these building blocks, we can create a Python app that:
1. Gets an account on the Testnet.
2. Connects to the XRP Ledger.
3. Looks up and prints information about the account you created.
{% code-snippet file="/_code-samples/get-started/py/get-acct-info.py" language="python" /%}
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/_code-samples/get-started/py) and run it locally:
```sh ```sh
git clone git@github.com:XRPLF/xrpl-dev-portal.git python get-acct-info.py
cd xrpl-dev-portal/_code-samples/get-started/py/get-acct-info.py
python3 get-acct-info.py
``` ```
You should see output similar to this example: You should see output similar to this example:
```sh ```sh
Classic address: Creating a new wallet and funding it with Testnet XRP...
Attempting to fund address ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
Faucet fund successful.
Wallet: ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
Account Testnet Explorer URL:
https://testnet.xrpl.org/accounts/ravbHNootpSNQkxyEFCWevSkHsFGDHfyop
rnQLnSEA1YFMABnCMrkMWFKxnqW6sQ8EWk Getting account info...
X-address: Response Status: ResponseStatus.SUCCESS
T7dRN2ktZGYSTyEPWa9SyDevrwS5yDca4m7xfXTGM3bqff8
response.status: ResponseStatus.SUCCESS
{ {
"account_data": { "account_data": {
"Account": "rnQLnSEA1YFMABnCMrkMWFKxnqW6sQ8EWk", "Account": "ravbHNootpSNQkxyEFCWevSkHsFGDHfyop",
"Balance": "1000000000", "Balance": "100000000",
"Flags": 0, "Flags": 0,
"LedgerEntryType": "AccountRoot", "LedgerEntryType": "AccountRoot",
"OwnerCount": 0, "OwnerCount": 0,
"PreviousTxnID": "5A5203AFF41503539D11ADC41BE4185761C5B78B7ED382E6D001ADE83A59B8DC", "PreviousTxnID": "3DACF2438AD39F294C4EFF6132D5D88BCB65D2F2261C7650F40AC1F6A54C83EA",
"PreviousTxnLgrSeq": 16126889, "PreviousTxnLgrSeq": 12039759,
"Sequence": 16126889, "Sequence": 12039759,
"index": "CAD0F7EF3AB91DA7A952E09D4AF62C943FC1EEE41BE926D632DDB34CAA2E0E8F" "index": "148E6F4B8E4C14018D679A2526200C292BDBC5AB77611BC3AE0CB97CD2FB84E5"
}, },
"ledger_current_index": 16126890, "account_flags": {
"queue_data": { "allowTrustLineClawback": false,
"txn_count": 0 "defaultRipple": false,
"depositAuth": false,
"disableMasterKey": false,
"disallowIncomingCheck": false,
"disallowIncomingNFTokenOffer": false,
"disallowIncomingPayChan": false,
"disallowIncomingTrustline": false,
"disallowIncomingXRP": false,
"globalFreeze": false,
"noFreeze": false,
"passwordSpent": false,
"requireAuthorization": false,
"requireDestinationTag": false
}, },
"validated": false "ledger_hash": "CA624D717C4FCDD03BAD8C193F374A77A14F7D2566354A4E9617A8DAD896DE71",
"ledger_index": 12039759,
"validated": true
} }
``` ```
#### Interpreting the response
The response fields that you want to inspect in most cases are: The response fields that you want to inspect in most cases are:
* `account_data.Sequence` — This is the sequence number of the next valid transaction for the account. You need to specify the sequence number when you prepare transactions. With `xrpl-py`, you can use the [`get_next_valid_seq_number`](https://xrpl-py.readthedocs.io/en/latest/source/xrpl.account.html#xrpl.account.get_next_valid_seq_number) to get this automatically from the XRP Ledger. See an example of this usage in the project [README](https://github.com/XRPLF/xrpl-py#serialize-and-sign-transactions). - `account_data.Balance` — This is the account's balance of [XRP, in drops][]. You can use this to confirm that you have enough XRP to send (if you're making a payment) and to meet the [current transaction cost](../../../concepts/transactions/transaction-cost.md#current-transaction-cost) for a given transaction.
* `account_data.Balance` — This is the account's balance of [XRP, in drops][]. You can use this to confirm that you have enough XRP to send (if you're making a payment) and to meet the [current transaction cost](../../../concepts/transactions/transaction-cost.md#current-transaction-cost) for a given transaction. - `validated` — Indicates whether the returned data is from a [validated ledger](../../../concepts/ledgers/open-closed-validated-ledgers.md). When inspecting transactions, it's important to confirm that [the results are final](../../../concepts/transactions/finality-of-results/index.md) before further processing the transaction. If `validated` is `true` then you know for sure the results won't change. For more information about best practices for transaction processing, see [Reliable Transaction Submission](../../../concepts/transactions/reliable-transaction-submission.md).
* `validated` — Indicates whether the returned data is from a [validated ledger](../../../concepts/ledgers/open-closed-validated-ledgers.md). When inspecting transactions, it's important to confirm that [the results are final](../../../concepts/transactions/finality-of-results/index.md) before further processing the transaction. If `validated` is `true` then you know for sure the results won't change. For more information about best practices for transaction processing, see [Reliable Transaction Submission](../../../concepts/transactions/reliable-transaction-submission.md).
For a detailed description of every response field, see [account_info](../../../references/http-websocket-apis/public-api-methods/account-methods/account_info.md#response-format). For a detailed description of every response field, see [account_info](../../../references/http-websocket-apis/public-api-methods/account-methods/account_info.md#response-format).
{% /step %}
## See Also
## Keep on building - **Concepts:**
- [XRP Ledger Overview](/about/)
Now that you know how to use `xrpl-py` to connect to the XRP Ledger, get an account, and look up information about it, you can also use `xrpl-py` to: - [Client Libraries](../../../references/client-libraries.md)
- **Tutorials:**
* [Send XRP](../../how-tos/send-xrp.md). - [Send XRP](../../how-tos/send-xrp.md)
* [Set up secure signing](../../../concepts/transactions/secure-signing.md) for your account. - [Issue a Fungible Token](../../how-tos/use-tokens/issue-a-fungible-token.md)
- [Set up Secure Signing](../../../concepts/transactions/secure-signing.md)
- **References:**
- [`xrpl-py` Reference](https://xrpl-py.readthedocs.io/en/latest/)
- [Public API Methods](../../../references/http-websocket-apis/public-api-methods/index.md)
- [API Conventions](../../../references/http-websocket-apis/api-conventions/index.md)
- [base58 Encodings](../../../references/protocol/data-types/base58-encodings.md)
- [Transaction Formats](../../../references/protocol/transactions/index.md)
{% raw-partial file="/docs/_snippets/common-links.md" /%} {% raw-partial file="/docs/_snippets/common-links.md" /%}
{% /code-walkthrough %}