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.requests 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

"""Example of how to send a transaction and see its validation response"""
from xrpl.account import get_balance
from xrpl.clients import JsonRpcClient
from xrpl.models.requests import Tx
from xrpl.models.transactions import Payment
from xrpl.transaction import (
    safe_sign_and_autofill_transaction,
    send_reliable_submission,
)
from xrpl.wallet import generate_faucet_wallet

# References:
# - https://xrpl.org/reliable-transaction-submission.html
# - https://xrpl.org/send-xrp.html
# - https://xrpl.org/look-up-transaction-results.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)

# Both balances should be zero since nothing has been sent yet
print("Balances of wallets before Payment tx")
print(get_balance(wallet1.classic_address, client))
print(get_balance(wallet2.classic_address, client))

# Create a Payment transaction
payment_tx = Payment(
    account=wallet1.classic_address,
    amount="1000",
    destination=wallet2.classic_address,
)

# Sign and autofill the transaction (prepares it to be ready to submit)
signed_payment_tx = safe_sign_and_autofill_transaction(payment_tx, wallet1, client)

# Submits transaction and waits for response (validated or rejected)
payment_response = send_reliable_submission(signed_payment_tx, client)
print("Transaction was submitted")

# Create a Transaction request to see transaction
tx_response = client.request(Tx(transaction=payment_response.result["hash"]))

# Check validated field on the transaction
print("Validated:", tx_response.result["validated"])

# Check balances after 1000 was sent from wallet1 to wallet2
print("Balances of wallets after Payment tx:")
print(get_balance(wallet1.classic_address, client))
print(get_balance(wallet2.classic_address, client))

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.transactions import Payment, SetRegularKey
from xrpl.transaction import (
    safe_sign_and_autofill_transaction,
    send_reliable_submission,
)
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.classic_address, client))
print(get_balance(wallet2.classic_address, client))

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

signed_tx = safe_sign_and_autofill_transaction(tx, wallet1, client)
set_regular_key_response = send_reliable_submission(signed_tx, client)

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.classic_address,
    destination=wallet2.classic_address,
    amount="1000",
)

signed_payment = safe_sign_and_autofill_transaction(payment, regular_key_wallet, client)
payment_response = send_reliable_submission(signed_payment, client)

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.classic_address, client))
print(get_balance(wallet2.classic_address, client))

Set up an Escrow

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

from xrpl.account import get_balance
from xrpl.clients import JsonRpcClient
from xrpl.models.requests import AccountObjects
from xrpl.models.transactions import EscrowCreate, EscrowFinish
from xrpl.transaction import (
    safe_sign_and_autofill_transaction,
    send_reliable_submission,
)
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.classic_address, client))
print(get_balance(wallet2.classic_address, client))

# Create a finish time (2 seconds from current time)
finish_after = datetime_to_ripple_time(datetime.now()) + 2

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

signed_create_tx = safe_sign_and_autofill_transaction(create_tx, wallet1, client)
create_escrow_response = send_reliable_submission(signed_create_tx, client)
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.classic_address)
account_objects = (client.request(account_objects_request)).result["account_objects"]

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

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

signed_finish_tx = safe_sign_and_autofill_transaction(finish_tx, wallet1, client)
send_reliable_submission(signed_finish_tx, client)

# If escrow went through successfully, 1000000 exchanged
print("Balances of wallets after Escrow was sent:")
print(get_balance(wallet1.classic_address, client))
print(get_balance(wallet2.classic_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.amounts import IssuedCurrencyAmount
from xrpl.models.currencies.xrp import XRP
from xrpl.models.requests import RipplePathFind
from xrpl.models.transactions import Payment
from xrpl.transaction import safe_sign_and_autofill_transaction
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.classic_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.classic_address,
    amount=destination_amount,
    destination=destination_account,
    paths=paths,
)

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

Handle Partial Payments

"""Example of how to handle partial payments"""
from xrpl.clients import JsonRpcClient
from xrpl.models.amounts import IssuedCurrencyAmount
from xrpl.models.requests import AccountLines
from xrpl.models.transactions import Payment, PaymentFlag, TrustSet
from xrpl.transaction import (
    safe_sign_and_autofill_transaction,
    send_reliable_submission,
)
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.classic_address,
    limit_amount=IssuedCurrencyAmount(
        currency="FOO",
        value="10000000000",
        issuer=wallet1.classic_address,
    ),
)

# Sign and autofill, then send transaction to the ledger
signed_trust_set_tx = safe_sign_and_autofill_transaction(trust_set_tx, wallet2, client)
send_reliable_submission(signed_trust_set_tx, client)

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

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

# Sign and autofill, then send transaction to the ledger
signed_payment_tx = safe_sign_and_autofill_transaction(payment_tx, wallet1, client)
payment_response = send_reliable_submission(signed_payment_tx, client)
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.classic_address))).result["lines"])
print((client.request(AccountLines(account=wallet2.classic_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.classic_address,
    amount=IssuedCurrencyAmount(
        currency="FOO",
        value="4000",
        issuer=wallet1.classic_address,
    ),
    destination=wallet1.classic_address,
    flags=[PaymentFlag.TF_PARTIAL_PAYMENT],
    send_max=IssuedCurrencyAmount(
        currency="FOO",
        value="1000000",
        issuer=wallet1.classic_address,
    ),
)

# Sign and autofill, then send transaction to the ledger
signed_partial_payment_tx = safe_sign_and_autofill_transaction(
    partial_payment_tx, wallet2, client
)
partial_payment_response = send_reliable_submission(signed_partial_payment_tx, client)
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.classic_address))).result["lines"])
print((client.request(AccountLines(account=wallet2.classic_address))).result["lines"])