XRPL Code Snippets

Code snippets to demonstrate basic usage of the xrpl-py library.

Look Up a Transaction on the Ledger

"""Example of how we can see a transaction that was validated on the ledger"""
from xrpl.clients import JsonRpcClient
from xrpl.models import Ledger, Tx

# References
# - https://xrpl.org/look-up-transaction-results.html
# - https://xrpl.org/parallel-networks.html#parallel-networks
# - https://xrpl.org/tx.html

# Create a client to connect to the main network
client = JsonRpcClient("https://xrplcluster.com/")

# Create a Ledger request and have the client call it
ledger_request = Ledger(ledger_index="validated", transactions=True)
ledger_response = client.request(ledger_request)
print(ledger_response)

# Extract out transactions from the ledger response
transactions = ledger_response.result["ledger"]["transactions"]

# If there are transactions, we can display the first one
# If there are none (visualized at https://testnet.xrpl.org/), try re running the script
if transactions:
    # Create a Transaction request and have the client call it
    tx_request = Tx(transaction=transactions[0])
    tx_response = client.request(tx_request)
    print(tx_response)
else:
    print("No transactions were found on the ledger!")

Send a Transaction and See if It Gets Validated

Set a Regular Key

"""Example of how we can setting a regular key"""
from xrpl.account import get_balance
from xrpl.clients import JsonRpcClient
from xrpl.models import Payment, SetRegularKey
from xrpl.transaction import submit_and_wait
from xrpl.wallet import generate_faucet_wallet

# References
# - https://xrpl.org/assign-a-regular-key-pair.html#assign-a-regular-key-pair
# - https://xrpl.org/setregularkey.html#setregularkey
# - https://xrpl.org/change-or-remove-a-regular-key-pair.html

# Create a client to connect to the test network
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Creating two wallets to send money between
wallet1 = generate_faucet_wallet(client, debug=True)
wallet2 = generate_faucet_wallet(client, debug=True)
regular_key_wallet = generate_faucet_wallet(client, debug=True)

# Both balances should be zero since nothing has been sent yet
print("Balances before payment:")
print(get_balance(wallet1.address, client))
print(get_balance(wallet2.address, client))

# Assign key pair (regular_key_wallet) to wallet1 using SetRegularKey transaction
tx = SetRegularKey(account=wallet1.address, regular_key=regular_key_wallet.address)

set_regular_key_response = submit_and_wait(tx, client, wallet1)

print("Response for successful SetRegularKey tx:")
print(set_regular_key_response)

# Since regular_key_wallet is linked to wallet1,
# walet1 can send payment to wallet2 and have regular_key_wallet sign it
payment = Payment(
    account=wallet1.address,
    destination=wallet2.address,
    amount="1000",
)

payment_response = submit_and_wait(payment, client, regular_key_wallet)

print("Response for tx signed using Regular Key:")
print(payment_response)

# Balance after sending 1000 from wallet1 to wallet2
print("Balances after payment:")
print(get_balance(wallet1.address, client))
print(get_balance(wallet2.address, client))

Set up an Escrow

"""Example of how we can set up an escrow"""
from datetime import datetime
from time import sleep

from xrpl.account import get_balance
from xrpl.clients import JsonRpcClient
from xrpl.models import AccountObjects, EscrowCreate, EscrowFinish
from xrpl.transaction.reliable_submission import submit_and_wait
from xrpl.utils import datetime_to_ripple_time
from xrpl.wallet import generate_faucet_wallet

# References
# - https://xrpl.org/escrowcreate.html#escrowcreate
# - https://xrpl.org/escrowfinish.html#escrowfinish
# - https://xrpl.org/account_objects.html#account_objects

# Create a client to connect to the test network
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Creating two wallets to send money between
wallet1 = generate_faucet_wallet(client, debug=True)
wallet2 = generate_faucet_wallet(client, debug=True)

# Both balances should be zero since nothing has been sent yet
print("Balances of wallets before Escrow tx was created:")
print(get_balance(wallet1.address, client))
print(get_balance(wallet2.address, client))

# Create a finish time (8 seconds from last ledger close)
finish_after = datetime_to_ripple_time(datetime.now()) + 8

# Create an EscrowCreate transaction, then sign, autofill, and send it
create_tx = EscrowCreate(
    account=wallet1.address,
    destination=wallet2.address,
    amount="1000000",
    finish_after=finish_after,
)

create_escrow_response = submit_and_wait(create_tx, client, wallet1)
print(create_escrow_response)

# Create an AccountObjects request and have the client call it to see if escrow exists
account_objects_request = AccountObjects(account=wallet1.address)
account_objects = (client.request(account_objects_request)).result["account_objects"]

print("Escrow object exists in wallet1's account:")
print(account_objects)

print("Waiting for the escrow finish time to pass...")
sleep(6)

# Create an EscrowFinish transaction, then sign, autofill, and send it
finish_tx = EscrowFinish(
    account=wallet1.address,
    owner=wallet1.address,
    offer_sequence=create_escrow_response.result["Sequence"],
)

submit_and_wait(finish_tx, client, wallet1)

# If escrow went through successfully, 1000000 exchanged
print("Balances of wallets after Escrow was sent:")
print(get_balance(wallet1.address, client))
print(get_balance(wallet2.address, client))

Find the Best Path to Trade With

"""Example of how to find the best path to trade with"""
from xrpl.clients import JsonRpcClient
from xrpl.models import XRP, IssuedCurrencyAmount, Payment, RipplePathFind
from xrpl.transaction import autofill_and_sign
from xrpl.wallet import generate_faucet_wallet

# References
# - https://xrpl.org/paths.html#paths
# - https://xrpl.org/ripple_path_find.html#ripple_path_find

# Create a client to connect to the test network
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Creating wallet to send money from
wallet = generate_faucet_wallet(client, debug=True)

# Create account and amount variables for later transaction
destination_account = "rKT4JX4cCof6LcDYRz8o3rGRu7qxzZ2Zwj"
destination_amount = IssuedCurrencyAmount(
    value="0.001",
    currency="USD",
    issuer="rVnYNK9yuxBz4uP8zC8LEFokM2nqH3poc",
)

# Create a RipplePathFind request and have the client call it
path_request = RipplePathFind(
    source_account=wallet.address,
    source_currencies=[XRP()],
    destination_account=destination_account,
    destination_amount=destination_amount,
)
path_response = client.request(path_request)
print(path_response)

# Extract out paths from the RipplePathFind response
paths = path_response.result["alternatives"][0]["paths_computed"]
print(paths)

# Create a Payment to send money from wallet to destination_account using path
payment_tx = Payment(
    account=wallet.address,
    amount=destination_amount,
    destination=destination_account,
    paths=paths,
)

print("signed: ", autofill_and_sign(payment_tx, client, wallet))

Handle Partial Payments

"""Example of how to handle partial payments"""
from xrpl.clients import JsonRpcClient
from xrpl.models import (
    AccountLines,
    IssuedCurrencyAmount,
    Payment,
    PaymentFlag,
    TrustSet,
)
from xrpl.transaction import submit_and_wait
from xrpl.wallet import generate_faucet_wallet

# References
# - https://xrpl.org/partial-payments.html#partial-payments
# - https://xrpl.org/payment.html#payment-flags
# - https://xrpl.org/trustset.html#trustset
# - https://xrpl.org/account_lines.html#account_lines

# Create a client to connect to the test network
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# Creating two wallets to send money between
wallet1 = generate_faucet_wallet(client, debug=True)
wallet2 = generate_faucet_wallet(client, debug=True)

# Create a TrustSet to issue an IOU `FOO` and set limit on it
trust_set_tx = TrustSet(
    account=wallet2.address,
    limit_amount=IssuedCurrencyAmount(
        currency="FOO",
        value="10000000000",
        issuer=wallet1.address,
    ),
)

# Sign and autofill, then send transaction to the ledger
submit_and_wait(trust_set_tx, client, wallet2)

# Both balances should be zero since nothing has been sent yet
print("Balances after trustline is claimed:")
print((client.request(AccountLines(account=wallet1.address))).result["lines"])
print((client.request(AccountLines(account=wallet2.address))).result["lines"])

# Create a Payment to send 3840 FOO from wallet1 (issuer) to destination (wallet2)
issue_quantity = "3840"
payment_tx = Payment(
    account=wallet1.address,
    amount=IssuedCurrencyAmount(
        currency="FOO",
        value=issue_quantity,
        issuer=wallet1.address,
    ),
    destination=wallet2.address,
)

# Sign and autofill, then send transaction to the ledger
payment_response = submit_and_wait(payment_tx, client, wallet1)
print(payment_response)

# Issuer (wallet1) should have -3840 FOO and destination (wallet2) should have 3840 FOO
print("Balances after wallet1 sends 3840 FOO to wallet2:")
print((client.request(AccountLines(account=wallet1.address))).result["lines"])
print((client.request(AccountLines(account=wallet2.address))).result["lines"])

# Send money less than the amount specified on 2 conditions:
# 1. Sender has less money than the amount specified in the payment Tx.
# 2. Sender has the tfPartialPayment flag activated.

# Other ways to specify flags are by using Hex code and decimal code.
# eg. For partial payment(tfPartialPayment)
# decimal ->131072, hex -> 0x00020000

# Create Payment to send 4000 (of 3840) FOO from wallet2 to wallet1
partial_payment_tx = Payment(
    account=wallet2.address,
    amount=IssuedCurrencyAmount(
        currency="FOO",
        value="4000",
        issuer=wallet1.address,
    ),
    destination=wallet1.address,
    flags=[PaymentFlag.TF_PARTIAL_PAYMENT],
    send_max=IssuedCurrencyAmount(
        currency="FOO",
        value="1000000",
        issuer=wallet1.address,
    ),
)

# Sign and autofill, then send transaction to the ledger
partial_payment_response = submit_and_wait(partial_payment_tx, client, wallet2)
print(partial_payment_response)

# Tried sending 4000 of 3840 FOO -> wallet1 and wallet2 should have 0 FOO
print("Balances after Partial Payment, when wallet2 tried to send 4000 FOOs")
print((client.request(AccountLines(account=wallet1.address))).result["lines"])
print((client.request(AccountLines(account=wallet2.address))).result["lines"])