Compare commits

..

8 Commits

Author SHA1 Message Date
Maria Shodunke
382a10bda9 Add temARRAY_EMPTY error for Batch transaction 2025-11-06 16:52:31 +00:00
Maria Shodunke
d2cf306ec6 Mention minimum number of transactions required in a Batch 2025-11-06 12:15:58 +00:00
Maria Shodunke
3e41224ef0 Add Batch transactions tutorials 2025-11-06 10:28:01 +00: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
17 changed files with 1033 additions and 161 deletions

View File

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

View File

@@ -44,6 +44,7 @@ export function codeSamples() {
});
actions.addRouteSharedData('/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) {
console.log(e);
}

View File

@@ -1,4 +1,5 @@
# Batch
Code samples showing how to create and submit a [Batch transaction](../../docs/concepts/transactions/batch-transactions.md).
Both for simple and multi account batch transactions.
Code samples showing how to create and submit a [Batch transaction](https://xrpl.org/docs/concepts/transactions/batch-transactions).
Both for single and multi account batch transactions.

View File

@@ -0,0 +1,281 @@
# Send a Batch Transaction
Code samples showing how to create and submit a [Batch transaction](https://xrpl.org/docs/concepts/transactions/batch-transactions) with Javascript.
Both for single and multi account batch transactions.
## Single Account Batch Transaction
Quick setup and usage:
```sh
npm install xrpl
node singleAccountBatch.js
```
The script should output the following:
```sh
Funding new wallets from faucet...
Sender: raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e, Balance: 100 XRP
Wallet1: r4JMmKToZRMVT3mGWPnKHFEHsSMQEWigLC, Balance: 100 XRP
Wallet2: rKfPgHASYuttoF1HfU56V31WbJvZn3w8xn, Balance: 100 XRP
Creating batch transaction:
{
"TransactionType": "Batch",
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Flags": 65536,
"RawTransactions": [
{
"RawTransaction": {
"TransactionType": "Payment",
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Destination": "r4JMmKToZRMVT3mGWPnKHFEHsSMQEWigLC",
"Amount": "2000000",
"Flags": 1073741824
}
},
{
"RawTransaction": {
"TransactionType": "Payment",
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Destination": "rKfPgHASYuttoF1HfU56V31WbJvZn3w8xn",
"Amount": "5000000",
"Flags": 1073741824
}
}
]
}
Submitting batch transaction...
Batch transaction submitted successfully!
Result:
{
"close_time_iso": "2025-11-03T14:16:21Z",
"ctid": "C00D458B00020002",
"hash": "A93D3C2BDB5D600E592B64B84E66D789237D029267129EBC659EE483E532DD95",
"ledger_hash": "BE6B7C12E551305F09E942D6FA3FC8546F024AE5C53FC495DA6ABF78461E7019",
"ledger_index": 869771,
"meta": {
"AffectedNodes": [
{
"ModifiedNode": {
"FinalFields": {
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Balance": "99999996",
"Flags": 0,
"OwnerCount": 0,
"Sequence": 869767
},
"LedgerEntryType": "AccountRoot",
"LedgerIndex": "6238B6901FEBD1492C03546C7965A01F184C4E37B696304B86F78F4ADB7831B1",
"PreviousFields": {
"Balance": "100000000",
"Sequence": 869766
},
"PreviousTxnID": "559F102041D84FF9DA17483355C3C96A0F8923D9C9C7971BBB15C972DD1F37D6",
"PreviousTxnLgrSeq": 869766
}
}
],
"TransactionIndex": 2,
"TransactionResult": "tesSUCCESS"
},
"tx_json": {
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Fee": "4",
"Flags": 65536,
"LastLedgerSequence": 869789,
"RawTransactions": [
{
"RawTransaction": {
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Amount": "2000000",
"Destination": "r4JMmKToZRMVT3mGWPnKHFEHsSMQEWigLC",
"Fee": "0",
"Flags": 1073741824,
"Sequence": 869767,
"SigningPubKey": "",
"TransactionType": "Payment"
}
},
{
"RawTransaction": {
"Account": "raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e",
"Amount": "5000000",
"Destination": "rKfPgHASYuttoF1HfU56V31WbJvZn3w8xn",
"Fee": "0",
"Flags": 1073741824,
"Sequence": 869768,
"SigningPubKey": "",
"TransactionType": "Payment"
}
}
],
"Sequence": 869766,
"SigningPubKey": "EDFECFB87A29F93E52BBA0BA5A14A59B520BB0E39F33943A2FDC1101D34349270D",
"TransactionType": "Batch",
"TxnSignature": "E08E300BDE1700C7CC27F3DA9B784907F637518E1C7E0978E57BFE5D1511A3B6A4269235FC2D9EAA550182A5F2B59415A442CE59555B9B9A0A79AB4030C9F701",
"ctid": "C00D458B00020002",
"date": 815494581,
"ledger_index": 869771
},
"validated": true
}
Final balances after batch transaction:
Sender: raNwujquxJ7QTLhfbkKN6sZa7RBPHV671e, Balance: 92.999996 XRP
Wallet1: r4JMmKToZRMVT3mGWPnKHFEHsSMQEWigLC, Balance: 102 XRP
Wallet2: rKfPgHASYuttoF1HfU56V31WbJvZn3w8xn, Balance: 105 XRP
Transaction URL:
https://devnet.xrpl.org/transactions/A93D3C2BDB5D600E592B64B84E66D789237D029267129EBC659EE483E532DD95
```
## Multi-Account Batch Transaction
```sh
npm install xrpl
node multiAccountBatch.js
```
The script should output the following:
```sh
Funding new wallets from faucet...
Alice: rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa, Balance: 100 XRP
Bob: rKPUDuS2jQNpAMhkNncqC9rKJDpL2gXDN7, Balance: 100 XRP
Charlie: rnz3Da7phfR6tgTZoPYF5psYTiHTshTB8K, Balance: 100 XRP
Third-party wallet: rU8LsCmVjSdf7hSmiGBtBDtt2WhHxp7Zpc, Balance: 100 XRP
Creating batch transaction:
{
"TransactionType": "Batch",
"Account": "rU8LsCmVjSdf7hSmiGBtBDtt2WhHxp7Zpc",
"Flags": 65536,
"RawTransactions": [
{
"RawTransaction": {
"TransactionType": "Payment",
"Account": "rnz3Da7phfR6tgTZoPYF5psYTiHTshTB8K",
"Destination": "rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa",
"Amount": "50000000",
"Flags": 1073741824
}
},
{
"RawTransaction": {
"TransactionType": "Payment",
"Account": "rKPUDuS2jQNpAMhkNncqC9rKJDpL2gXDN7",
"Destination": "rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa",
"Amount": "50000000",
"Flags": 1073741824
}
}
]
}
Submitting batch transaction...
Batch transaction submitted successfully!
Result:
{
"close_time_iso": "2025-11-03T14:15:00Z",
"ctid": "C00D457000000002",
"hash": "8CBCCD88B8ABC248797B84ABB92066961C1CB5FE75ACE2115ADCA6B74C85993A",
"ledger_hash": "2217A0DBB38B870187B412533B939724095359A050B21E071A2A114BF57CFB60",
"ledger_index": 869744,
"meta": {
"AffectedNodes": [
{
"ModifiedNode": {
"FinalFields": {
"Account": "rU8LsCmVjSdf7hSmiGBtBDtt2WhHxp7Zpc",
"Balance": "99999994",
"Flags": 0,
"OwnerCount": 0,
"Sequence": 869743
},
"LedgerEntryType": "AccountRoot",
"LedgerIndex": "1E9BA043B9C6518582D0FF73A08DCD8B6958195735086CF7295E5EB6433FB453",
"PreviousFields": {
"Balance": "100000000",
"Sequence": 869742
},
"PreviousTxnID": "F7019BC55D80438FDDB01C2549CCC3F7DAF9791F8645E0269D63979EAEC5BBA6",
"PreviousTxnLgrSeq": 869742
}
}
],
"TransactionIndex": 0,
"TransactionResult": "tesSUCCESS"
},
"tx_json": {
"Account": "rU8LsCmVjSdf7hSmiGBtBDtt2WhHxp7Zpc",
"BatchSigners": [
{
"BatchSigner": {
"Account": "rnz3Da7phfR6tgTZoPYF5psYTiHTshTB8K",
"SigningPubKey": "EDC566D7DA8186BBD30DDAE1FB770FCE7F248949194E1A2E70B18CFA060B140B59",
"TxnSignature": "31639BFA1359DD24345776EAEEACCF61C1CDC792988679263D113E80A22D837E20ACD2B25E482FCA769990C004D747836370C6BAD14524559639BBEBA5813002"
}
},
{
"BatchSigner": {
"Account": "rKPUDuS2jQNpAMhkNncqC9rKJDpL2gXDN7",
"SigningPubKey": "EDEF1966B325000407940E4C0792E3CCC3E27F51D132BDC53DCC2B1998E7C32A34",
"TxnSignature": "6BF9860B0E2E134FB302329D711BAA7B6314395D39523982DBBC037E84FB17AB5E8E736DB3DB0019B4477686AF2D91E5D2B49409698A95219376B2E318D3E501"
}
}
],
"Fee": "6",
"Flags": 65536,
"LastLedgerSequence": 869762,
"RawTransactions": [
{
"RawTransaction": {
"Account": "rnz3Da7phfR6tgTZoPYF5psYTiHTshTB8K",
"Amount": "50000000",
"Destination": "rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa",
"Fee": "0",
"Flags": 1073741824,
"Sequence": 869740,
"SigningPubKey": "",
"TransactionType": "Payment"
}
},
{
"RawTransaction": {
"Account": "rKPUDuS2jQNpAMhkNncqC9rKJDpL2gXDN7",
"Amount": "50000000",
"Destination": "rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa",
"Fee": "0",
"Flags": 1073741824,
"Sequence": 869738,
"SigningPubKey": "",
"TransactionType": "Payment"
}
}
],
"Sequence": 869742,
"SigningPubKey": "ED2B56D6FB4E8C236A6B07E8D8AD9A4938606144E31779918F99525CA6B3C56664",
"TransactionType": "Batch",
"TxnSignature": "9C51C1F2CB0E8BCEA1FADD3992249DE72AC46FC86AB2FB023A597FBD5C4CCB3337967E9AAFFB5F1C0CBC91128F3FD194F78F207E461BE1FF906C496B94EC410E",
"ctid": "C00D457000000002",
"date": 815494500,
"ledger_index": 869744
},
"validated": true
}
Final balances after batch transaction:
Alice: rfCBfRGpcGJLwdbfz1M6HYoAL8nZyHRHHa, Balance: 200 XRP
Bob: rKPUDuS2jQNpAMhkNncqC9rKJDpL2gXDN7, Balance: 50 XRP
Charlie: rnz3Da7phfR6tgTZoPYF5psYTiHTshTB8K, Balance: 50 XRP
Third-party wallet: rU8LsCmVjSdf7hSmiGBtBDtt2WhHxp7Zpc, Balance: 99.999994 XRP
Transaction URL:
https://devnet.xrpl.org/transactions/8CBCCD88B8ABC248797B84ABB92066961C1CB5FE75ACE2115ADCA6B74C85993A
```

View File

@@ -0,0 +1,111 @@
/**
* XRP Ledger Batch Transactions Tutorial
*
* This tutorial demonstrates how to use the Batch transaction feature (XLS-56)
* to perform a multi-account batch transaction.
*/
import xrpl from "xrpl"
import { BatchFlags } from 'xrpl/dist/npm/models/transactions/batch.js'
import { GlobalFlags } from 'xrpl/dist/npm/models/transactions/common.js'
import { signMultiBatch, combineBatchSigners } from 'xrpl/dist/npm/Wallet/batchSigner.js'
const client = new xrpl.Client("wss://s.devnet.rippletest.net:51233/")
await client.connect()
// Create and fund wallets
console.log("Funding new wallets from faucet...")
const { wallet: alice } = await client.fundWallet()
const { wallet: bob } = await client.fundWallet()
const { wallet: charlie } = await client.fundWallet()
const { wallet: thirdPartyWallet } = await client.fundWallet()
console.log(`Alice: ${alice.address}, Balance: ${await client.getXrpBalance(alice.address)} XRP`)
console.log(`Bob: ${bob.address}, Balance: ${await client.getXrpBalance(bob.address)} XRP`)
console.log(`Charlie: ${charlie.address}, Balance: ${await client.getXrpBalance(charlie.address)} XRP`)
console.log(`Third-party wallet: ${thirdPartyWallet.address}, Balance: ${await client.getXrpBalance(thirdPartyWallet.address)} XRP`)
// Create inner transactions --------------------------------------------
// REQUIRED: Inner transactions MUST have the tfInnerBatchTxn flag (0x40000000).
// This marks them as part of a batch (allows Fee: 0 and empty SigningPubKey).
// Transaction 1: Charlie pays Alice
const charliePayment = {
TransactionType: "Payment",
Account: charlie.address,
Destination: alice.address,
Amount: xrpl.xrpToDrops(50),
Flags: GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}
// Transaction 2: Bob pays Alice
const bobPayment = {
TransactionType: "Payment",
Account: bob.address,
Destination: alice.address,
Amount: xrpl.xrpToDrops(50),
Flags: GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}
// Send Batch transaction --------------------------------------------
console.log("\nCreating batch transaction:")
const batchTx = {
TransactionType: "Batch",
Account: thirdPartyWallet.address,
Flags: BatchFlags.tfAllOrNothing, // tfAllOrNothing: All inner transactions must succeed
// Must include a minimum of 2 transactions and a maximum of 8 transactions.
RawTransactions: [
{ RawTransaction: charliePayment },
{ RawTransaction: bobPayment },
]
}
console.log(JSON.stringify(batchTx, null, 2))
// Validate the transaction structure
xrpl.validate(batchTx)
// Set the expected number of signers for this transaction.
// "autofill" will automatically add Fee: "0" and SigningPubKey: "".
const autofilledBatchTx = await client.autofill(batchTx, 2)
// Gather batch signatures --------------------------------
// Each signer needs their own tx copy because signMultiBatch modifies the object.
// Charlie signs the Batch transaction
const charlieBatch = { ...autofilledBatchTx }
signMultiBatch(charlie, charlieBatch)
// Bob signs the Batch transaction
const bobBatch = { ...autofilledBatchTx }
signMultiBatch(bob, bobBatch)
// Combine inner transaction signatures.
// This returns a signed transaction blob (hex string) ready for submission.
const combinedSignedTx = combineBatchSigners([charlieBatch, bobBatch])
// Submit the signed blob with the third-party's wallet
console.log("\nSubmitting batch transaction...")
const submitResponse = await client.submitAndWait(combinedSignedTx,
{ wallet: thirdPartyWallet }
)
// Check Batch transaction result --------------------------------
if (submitResponse.result.meta.TransactionResult !== "tesSUCCESS") {
const resultCode = submitResponse.result.meta.TransactionResult
console.warn(`\nTransaction failed with result code ${resultCode}`)
process.exit(1)
}
console.log("\nBatch transaction submitted successfully!")
console.log("Result:\n", JSON.stringify(submitResponse.result, null, 2))
// Verify balances after transaction
console.log("\nFinal balances after batch transaction:")
console.log(`Alice: ${alice.address}, Balance: ${await client.getXrpBalance(alice.address)} XRP`)
console.log(`Bob: ${bob.address}, Balance: ${await client.getXrpBalance(bob.address)} XRP`)
console.log(`Charlie: ${charlie.address}, Balance: ${await client.getXrpBalance(charlie.address)} XRP`)
console.log(`Third-party wallet: ${thirdPartyWallet.address}, Balance: ${await client.getXrpBalance(thirdPartyWallet.address)} XRP`)
// View the transaction on the XRPL Explorer
console.log(`\nTransaction URL:\nhttps://devnet.xrpl.org/transactions/${submitResponse.result.hash}`)
await client.disconnect()

View File

@@ -0,0 +1,6 @@
{
"dependencies": {
"xrpl": "^4.4.2"
},
"type": "module"
}

View File

@@ -0,0 +1,91 @@
/**
* Single Account Batch Transaction Example
*
* This example demonstrates how to use the Batch transactions feature (XLS-56)
* to create a single-account batch transaction that sends payments
* to multiple destinations in one atomic operation.
*/
import xrpl from "xrpl"
import { BatchFlags } from 'xrpl/dist/npm/models/transactions/batch.js'
import { GlobalFlags } from 'xrpl/dist/npm/models/transactions/common.js'
const client = new xrpl.Client("wss://s.devnet.rippletest.net:51233/")
await client.connect()
// Create and fund wallets
console.log("Funding new wallets from faucet...")
const { wallet: sender } = await client.fundWallet()
const { wallet: wallet1 } = await client.fundWallet()
const { wallet: wallet2 } = await client.fundWallet()
console.log(`Sender: ${sender.address}, Balance: ${await client.getXrpBalance(sender.address)} XRP`)
console.log(`Wallet1: ${wallet1.address}, Balance: ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Wallet2: ${wallet2.address}, Balance: ${await client.getXrpBalance(wallet2.address)} XRP`)
// Create inner transactions --------------------------------------------
// REQUIRED: Inner transactions MUST have the tfInnerBatchTxn flag (0x40000000).
// This marks them as part of a batch (allows Fee: 0 and empty SigningPubKey).
// Transaction 1
const payment1 = {
TransactionType: "Payment",
Account: sender.address,
Destination: wallet1.address,
Amount: xrpl.xrpToDrops(2),
Flags: GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}
// Transaction 2
const payment2 = {
TransactionType: "Payment",
Account: sender.address,
Destination: wallet2.address,
Amount: xrpl.xrpToDrops(5),
Flags: GlobalFlags.tfInnerBatchTxn // THIS IS REQUIRED
}
// Send Batch transaction --------------------------------------------
console.log("\nCreating batch transaction:")
const batchTx = {
TransactionType: "Batch",
Account: sender.address,
Flags: BatchFlags.tfAllOrNothing, // tfAllOrNothing: All inner transactions must succeed
// Must include a minimum of 2 transactions and a maximum of 8 transactions.
RawTransactions: [
{ RawTransaction: payment1 },
{ RawTransaction: payment2 }
]
}
console.log(JSON.stringify(batchTx, null, 2))
// Validate the transaction structure before submitting
xrpl.validate(batchTx)
// Submit and wait for validation
console.log("\nSubmitting batch transaction...")
const submitResponse = await client.submitAndWait(batchTx, {
wallet: sender,
// "autofill" will automatically add Fee: "0" and SigningPubKey: "".
autofill: true
})
// Check Batch transaction result --------------------------------
if (submitResponse.result.meta.TransactionResult !== "tesSUCCESS") {
const resultCode = submitResponse.result.meta.TransactionResult
console.warn(`\nTransaction failed with result code ${resultCode}`)
process.exit(1)
}
console.log("\nBatch transaction submitted successfully!")
console.log("Result:\n", JSON.stringify(submitResponse.result, null, 2))
// Verify balances after transaction
console.log("\nFinal balances after batch transaction:")
console.log(`Sender: ${sender.address}, Balance: ${await client.getXrpBalance(sender.address)} XRP`)
console.log(`Wallet1: ${wallet1.address}, Balance: ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Wallet2: ${wallet2.address}, Balance: ${await client.getXrpBalance(wallet2.address)} XRP`)
// View the transaction on the XRPL Explorer
console.log(`\nTransaction URL:\nhttps://devnet.xrpl.org/transactions/${submitResponse.result.hash}`)
await client.disconnect()

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
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/"
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
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)
# Create an account str from the wallet
test_account = test_wallet.address
# Derive an x-address from the classic address:
# 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)
test_account = test_wallet.classic_address
print(f"Wallet: {test_account}")
print(f"Account Testnet Explorer URL: ")
print(f" https://testnet.xrpl.org/accounts/{test_account}")
# @chunk-end
# @chunk {"steps": ["query-xrpl-tag"]}
# Look up info about your account
from xrpl.models.requests.account_info import AccountInfo
print("\nGetting account info...")
acct_info = AccountInfo(
account=test_account,
ledger_index="validated",
strict=True,
)
response = client.request(acct_info)
result = response.result
print("response.status: ", response.status)
import json
print("Response Status: ", response.status)
print(json.dumps(response.result, indent=4, sort_keys=True))
# @chunk-end

View File

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

View File

@@ -189,8 +189,6 @@ Transactions and ledger entries may contain fields of any of the following types
| [UInt256][] | 5 | 256 | No | A 256-bit binary value. This usually represents the hash of a transaction, ledger version, or ledger entry. |
| [UInt384][] | 22 | 384 | No | **UNUSED.** A 384-bit binary value. |
| [UInt512][] | 23 | 512 | No | **UNUSED.** A 512-bit binary value. |
| [Int32][] | 10 | 32 | No | **UNUSED.** A 32-bit signed integer. |
| [Int64][] | 11 | 64 | No | **UNUSED.** A 64-bit signed integer. |
| [Vector256][] | 19 | Variable | Yes | A list of 256-bit binary values. This may be a list of ledger entries or other hash values. |
| [XChainBridge][] | 25 | Variable | No | A bridge between two blockchains, identified by the door accounts and issued assets on both chains. |
@@ -396,21 +394,6 @@ The types UInt96, UInt384, and UInt512 are currently defined but not used.
The `TransactionType` field is a special case. In JSON, this field is conventionally represented as a string with the name of the transaction type. In binary, this field is a UInt16. The `TRANSACTION_TYPES` object in the [definitions file](#definitions-file) maps these strings to the numeric values used in the binary format.
### Int Fields
[Int32]: #int-fields
[Int64]: #int-fields
The XRP Ledger supports signed 32-bit integers (Int32), which use standard big-endian binary signed integer representation with two's complement to handle negative values.
In JSON format, Int32 fields can be represented as:
- JSON numbers (for values within JavaScript's safe integer range).
- Strings containing decimal numbers.
Although the protocol supports the Int32 type, no fields currently use it. An Int64 type has also been defined, but is unsupported.
### Vector256 Fields
[Vector256]: #vector256-fields

View File

@@ -121,12 +121,12 @@ In this example, two users are atomically swapping their tokens: XRP for GKO.
| Field | JSON Type | [Internal Type][] | Required? | Description |
|:------------------|:----------|:------------------|:----------|:------------|
| `Flags` | Number | UInt32 | Yes | A bit-flag for this transaction. Exactly one must be specified to represent the batch mode of the transaction. See: [Batch Flags](#batch-flags). |
| `RawTransactions` | Array | Array | Yes | The list of transactions to apply. |
| `RawTransactions` | Array | Array | Yes | The list of transactions to apply. See [RawTransactions](#rawtransactions). |
| `BatchSigners` | Array | Array | No | The signatures authorizing a multi-account `Batch` transaction. |
### RawTransactions
`RawTransactions` contains the list of inner transactions to be applied. There can be up to 8 transactions included. These transactions can come from one account or multiple accounts.
`RawTransactions` contains the list of inner transactions to be applied. There must be a minimum of **2** transactions and a maximum of **8** transactions. These transactions can come from one account or multiple accounts.
Each inner transaction:
@@ -169,6 +169,7 @@ A transaction is considered successful if it receives a `tesSUCCESS` result.
| Error Code | Description |
|:--------------------------|:--------------------------------------------------|
| `temARRAY_EMPTY` | The batch transaction contains zero or one inner transaction. You must submit at least two inner transactions. |
| `temINVALID_INNER_BATCH` | An inner transaction is malformed. |
| `temSEQ_AND_TICKET` | The transaction contains both a `TicketSequence` field and a non-zero `Sequence` value. A transaction can't include both fields, but must have at least one. |

View File

@@ -0,0 +1,14 @@
---
seo:
description: Batch multiple transactions together and execute them as a single unit.
metadata:
indexPage: true
labels:
- Batch
- Transactions
---
# Use Batch Transactions
Batch multiple transactions together and execute them as a single unit.
{% child-pages /%}

View File

@@ -0,0 +1,158 @@
---
seo:
description: Send a Batch transaction containing transactions from multiple accounts.
metadata:
indexPage: true
labels:
- Batch
- Transactions
---
# Send a Multi-Account Batch Transaction
This tutorial shows you how to create a [Batch transaction][] containing transactions from multiple accounts, where each account must sign the Batch transaction. Any account, even one not involved in the inner transactions, can submit the batch.
## Goals
By the end of this tutorial, you will be able to:
- Create a Batch transaction with multiple inner transactions, signed by multiple accounts, and submitted by a third party account.
- Configure the Batch transaction to ensure atomicity, so that either all inner transactions succeed or they all fail.
## Prerequisites
To complete this tutorial, you should:
- Have a basic understanding of the XRP Ledger.
- 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 examples in the [code samples section of this website's repository](https://github.com/XRPLF/xrpl-dev-portal/tree/master/_code-samples/batch/).
## Steps
The example in this tutorial demonstrates a scenario where Bob and Charlie both owe Alice 50 XRP each, and a third-party (such as a payment processor) submits the Batch transaction atomically to ensure Alice is paid by both parties.
### 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 accounts
To get started, import the client library and instantiate a client to connect to the XRPL. Then, create the accounts for Alice, Bob, Charlie, and the third-party.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="import xrpl" before="// Create inner transactions" /%}
{% /tab %}
{% /tabs %}
### 3. Prepare inner transactions
Next, prepare the inner transactions that will be included in the batch.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Create inner transactions" to="// Send Batch transaction" /%}
{% /tab %}
{% /tabs %}
The first transaction sends a payment of 50 XRP from Charlie to Alice, and the second sends a payment of 50 XRP from Bob to Alice. Both transactions must include the `tfInnerBatchTxn` (0x40000000) flag to indicate that they are inner transactions of a batch.
Inner transactions must have a Fee of **0** and an empty string for the `SigningPubKey`. The outer Batch transaction handles the overall fee and signing for all inner transactions.
{% admonition type="info" name="Note" %}
The `Fee` and `SigningPubKey` fields are omitted as the client library's _autofill_ functionality automatically populates these when submitting the Batch transaction.
You typically don't need to set these manually, but if you do, ensure `Fee` is set to 0 and `SigningPubKey` is an empty string.
{% /admonition %}
### 4. Prepare Batch transaction
Create the Batch transaction and provide the inner transactions. The key fields to note are:
| Field | Value |
|:---------------- |:---------- |
| TransactionType | The type of transaction, in this case `Batch`.|
| Account | The wallet address of the account that is sending the Batch transaction. |
| Flags | The flags for the Batch transaction. For this example the transaction is configured with the `tfAllOrNothing` (0x00010000) flag to ensure that either all inner transactions succeed or they all fail atomically. See [Batch Flags](../../../references/protocol/transactions/types/batch.md#batch-flags) for other options. |
| RawTransactions | Contains the list of inner transactions to be applied. Must include a minimum of **2** transactions and a maximum of **8** transactions. These transactions can come from one account or multiple accounts. |
| BatchSigners | The list of signatures required for the Batch transaction. This is required because there are multiple accounts' transactions included in the batch. |
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Send Batch transaction" before="// Gather batch signatures" /%}
{% /tab %}
{% /tabs %}
Because we used `autofill`, the client library automatically fills in any missing fields, like `Fee` and `SigningPubKey`. Additionally, we specify the expected number of signers (2 in this case).
### 5. Gather batch signatures
To add the `BatchSigners` field, you need to collect signatures from each account that's sending a transaction within the batch. In this case we need two signatures, one from Charlie and one from Bob. Each sender must sign the Batch transaction to authorize their payment.
{% tabs %}
{% tab label="Javascript" %}
The **xrpl.js** library provides a helper function, `signMultiBatch()`, to sign the Batch transaction for each account.
Then, to combine the signatures into a single signed Batch transaction, use the `combineBatchSigners()` utility function.
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Gather batch signatures" to="// Submit" /%}
{% /tab %}
{% /tabs %}
### 6. Submit Batch transaction
With all the required signatures gathered, the third-party wallet can now submit the Batch transaction.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Submit" before="// Check Batch transaction" /%}
{% /tab %}
{% /tabs %}
### 6. Check Batch transaction result
To check the result of the Batch transaction submission:
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Check Batch transaction" before="// Verify balances after transaction" /%}
{% /tab %}
{% /tabs %}
The code checks for a `tesSUCCESS` result and displays the response details.
{% admonition type="warning" name="Warning" %}
A `tesSUCCESS` result indicates that the Batch transaction was processed successfully, but does not guarantee the inner transactions succeeded. For example, see the [following transaction on the XRPL Explorer](https://devnet.xrpl.org/transactions/20CFCE5CF75E93E6D1E9C1E42F8E8C8C4CB1786A65BE23D2EA77EAAB65A455C5/simple).
{% /admonition %}
To verify that the inner transactions have been successful, check the account balances to confirm the expected changes.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/multiAccountBatch.js" language="js" from="// Verify balances after transaction" /%}
{% /tab %}
{% /tabs %}
Because the Batch transaction is configured with a `tfAllOrNothing` flag, if any inner transaction fails, **all** inner transactions wil fail, and only the Batch transaction fee is deducted from the **third-party wallet**.
## See Also
- **Concepts**:
- [Batch Transactions](../../../concepts/transactions/batch-transactions.md)
- **Tutorials**:
- [Send a Single Account Batch Transaction](send-a-single-account-batch-transaction.md)
- **References**:
- [Batch Transaction][]
{% raw-partial file="/docs/_snippets/common-links.md" /%}

View File

@@ -0,0 +1,148 @@
---
seo:
description: Send a Batch transaction from a single account.
metadata:
indexPage: true
labels:
- Batch
- Transactions
---
# Send a Single Account Batch Transaction
A [Batch transaction][] allows you to group multiple transactions together and execute them as a single atomic operation.
This tutorial shows you how to create a Batch transaction where a single account submits multiple transactions that either all succeed together or all fail together.
## Goals
By the end of this tutorial, you will be able to:
- Create a Batch transaction with multiple inner transactions, signed and submitted by a single account.
- Configure the Batch transaction to ensure atomicity, so that either all inner transactions succeed or they all fail.
## Prerequisites
To complete this tutorial, you should:
- Have a basic understanding of the XRP Ledger.
- 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 examples in the [code samples section of this website's repository](https://github.com/XRPLF/xrpl-dev-portal/tree/master/_code-samples/batch/).
## Steps
The example in this tutorial demonstrates a scenario where an account sends multiple payments that must be processed atomically in one Batch transaction.
### 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 accounts
To get started, import the client library and instantiate a client to connect to the XRPL. For this tutorial you need a funded account for the Batch transaction **sender**, and two other accounts to **receive** the payments.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="import xrpl" before="// Create inner transactions" /%}
{% /tab %}
{% /tabs %}
### 3. Prepare inner transactions
Next, prepare the inner transactions that will be included in the batch.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="// Create inner transactions" to="// Send Batch transaction" /%}
{% /tab %}
{% /tabs %}
The first transaction sends a payment of 2 XRP from the sender to `wallet1`, and the second transaction sends 5 XRP from the sender to `wallet2`. Both transactions must include the `tfInnerBatchTxn` (0x40000000) flag to indicate that they are inner transactions of a batch.
Inner transactions must have a Fee of **0** and an empty string for the `SigningPubKey`. The outer Batch transaction handles the overall fee and signing for all inner transactions.
{% admonition type="info" name="Note" %}
The `Fee` and `SigningPubKey` fields are omitted as the client library's _autofill_ functionality automatically populates these when submitting the Batch transaction.
You typically don't need to set these manually, but if you do, ensure `Fee` is set to 0 and `SigningPubKey` is an empty string.
{% /admonition %}
### 4. Prepare Batch transaction
Create the Batch transaction and provide the inner transactions. The key fields to note are:
| Field | Value |
|:---------------- |:---------- |
| TransactionType | The type of transaction, in this case `Batch`.|
| Account | The wallet address of the account that is sending the Batch transaction. |
| Flags | The flags for the Batch transaction. For this example the transaction is configured with the `tfAllOrNothing` (0x00010000) flag to ensure that either all inner transactions succeed or they all fail atomically. See [Batch Flags](../../../references/protocol/transactions/types/batch.md#batch-flags) for other options. |
| RawTransactions | Contains the list of inner transactions to be applied. Must include a minimum of **2** transactions and a maximum of **8** transactions. These transactions can come from one account or multiple accounts. |
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="// Send Batch transaction" before="// Submit" /%}
{% /tab %}
{% /tabs %}
### 5. Submit Batch transaction
Now the sender can submit the Batch transaction:
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="// Submit" before="// Check Batch transaction" /%}
{% /tab %}
{% /tabs %}
Because `autofill` is set to `true`, the client library automatically fills in any missing fields, like the `Fee` and `SigningPubKey`, before submitting the batch.
### 6. Check Batch transaction result
To check the result of the Batch transaction submission:
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="// Check Batch transaction" before="// Verify balances after transaction" /%}
{% /tab %}
{% /tabs %}
The code checks for a `tesSUCCESS` result and displays the response details.
{% admonition type="warning" name="Warning" %}
A `tesSUCCESS` result indicates that the Batch transaction was processed successfully, but does not guarantee the inner transactions succeeded.
For example, see the [following transaction on the XRPL Explorer](https://devnet.xrpl.org/transactions/20CFCE5CF75E93E6D1E9C1E42F8E8C8C4CB1786A65BE23D2EA77EAAB65A455C5/simple).
{% /admonition %}
To verify that the inner transactions have been successful, check the account balances to confirm the expected changes.
{% tabs %}
{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/batch/js/singleAccountBatch.js" language="js" from="// Verify balances after transaction" /%}
{% /tab %}
{% /tabs %}
Because the Batch transaction is configured with a `tfAllOrNothing` flag, if any inner transaction fails, **all** inner transactions wil fail, and only the Batch transaction fee is deducted from the **sender**.
## See Also
- **Concepts**:
- [Batch Transactions](../../../concepts/transactions/batch-transactions.md)
- **Tutorials**:
- [Send a Multi-Account Batch Transaction](send-a-multi-account-batch-transaction.md)
- **References**:
- [Batch Transaction][]
{% raw-partial file="/docs/_snippets/common-links.md" /%}

View File

@@ -1,63 +1,97 @@
---
seo:
description: Build a Python app that interacts with the XRP Ledger.
top_nav_name: Python
top_nav_grouping: Get Started
labels:
- 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
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.
## Learning Goals
## Goals
In this tutorial, you'll learn:
* The basic building blocks of XRP Ledger-based applications.
* 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 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.
- The basic building blocks of XRP Ledger-based applications.
- 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 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.
## 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
pip3 install xrpl-py
Follow the steps to create a simple application with `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)
1. [Get an account.](#2-get-account)
1. [Query the XRP Ledger.](#3-query-the-xrp-ledger)
{% step id="connect-tag" %}
#### Connect to the XRP Ledger Testnet
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" /%}
#### Connect to the production XRP Ledger
{% step id="connect-mainnet-tag"%}
#### Connect to the XRP Ledger Mainnet
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
JSON_RPC_URL = "http://localhost:5005/"
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.
* By using one of the available [public servers][]:
- By using one of the available [public servers][]:
```
```python
from xrpl.clients import JsonRpcClient
JSON_RPC_URL = "https://s2.ripple.com:51234/"
client = JsonRpcClient(JSON_RPC_URL)
```
{% /step %}
### 2. Get account
{% step id="get-account-create-wallet-tag" %}
### 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.
{% 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.
{% /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" /%}
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
{% step id="query-xrpl-tag" %}
### 4. 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).
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" /%}
### 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:
Finally, in your terminal, run the application like so:
```sh
git clone git@github.com:XRPLF/xrpl-dev-portal.git
cd xrpl-dev-portal/_code-samples/get-started/py/get-acct-info.py
python3 get-acct-info.py
python get-acct-info.py
```
You should see output similar to this example:
```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
X-address:
T7dRN2ktZGYSTyEPWa9SyDevrwS5yDca4m7xfXTGM3bqff8
response.status: ResponseStatus.SUCCESS
Getting account info...
Response Status: ResponseStatus.SUCCESS
{
"account_data": {
"Account": "rnQLnSEA1YFMABnCMrkMWFKxnqW6sQ8EWk",
"Balance": "1000000000",
"Account": "ravbHNootpSNQkxyEFCWevSkHsFGDHfyop",
"Balance": "100000000",
"Flags": 0,
"LedgerEntryType": "AccountRoot",
"OwnerCount": 0,
"PreviousTxnID": "5A5203AFF41503539D11ADC41BE4185761C5B78B7ED382E6D001ADE83A59B8DC",
"PreviousTxnLgrSeq": 16126889,
"Sequence": 16126889,
"index": "CAD0F7EF3AB91DA7A952E09D4AF62C943FC1EEE41BE926D632DDB34CAA2E0E8F"
"PreviousTxnID": "3DACF2438AD39F294C4EFF6132D5D88BCB65D2F2261C7650F40AC1F6A54C83EA",
"PreviousTxnLgrSeq": 12039759,
"Sequence": 12039759,
"index": "148E6F4B8E4C14018D679A2526200C292BDBC5AB77611BC3AE0CB97CD2FB84E5"
},
"ledger_current_index": 16126890,
"queue_data": {
"txn_count": 0
"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
},
"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:
* `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).
{% /step %}
## See Also
## Keep on building
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:
* [Send XRP](../../how-tos/send-xrp.md).
* [Set up secure signing](../../../concepts/transactions/secure-signing.md) for your account.
- **Concepts:**
- [XRP Ledger Overview](/about/)
- [Client Libraries](../../../references/client-libraries.md)
- **Tutorials:**
- [Send XRP](../../how-tos/send-xrp.md)
- [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" /%}
{% /code-walkthrough %}

View File

@@ -295,6 +295,11 @@
- page: docs/tutorials/how-tos/manage-account-settings/require-destination-tags.md
- page: docs/tutorials/how-tos/manage-account-settings/offline-account-setup.md
- page: docs/tutorials/how-tos/manage-account-settings/use-tickets.md
- page: docs/tutorials/how-tos/use-batch-transactions/index.md
expanded: false
items:
- page: docs/tutorials/how-tos/use-batch-transactions/send-a-single-account-batch-transaction.md
- page: docs/tutorials/how-tos/use-batch-transactions/send-a-multi-account-batch-transaction.md
- page: docs/tutorials/how-tos/use-specialized-payment-types/index.md
expanded: false
items: