Package: xrpl-py
xrpl-pyA pure Python implementation for interacting with theXRP Ledger.Thexrpl-pylibrary simplifies the hardest parts of XRP Ledger interaction, like serialization and transaction signing. It also provides native Python methods and models forXRP Ledger transactionsand core serverAPI(rippled) objects.As an example, this is how you would use this library to send a payment on testnet:fromxrpl.accountimportget_balancefromxrpl.clientsimportJsonRpcClientfromxrpl.modelsimportPayment,Txfromxrpl.transactionimportsubmit_and_waitfromxrpl.walletimportgenerate_faucet_wallet# Create a client to connect to the test networkclient=JsonRpcClient("https://s.altnet.rippletest.net:51234")# Create two wallets to send money between on the test networkwallet1=generate_faucet_wallet(client,debug=True)wallet2=generate_faucet_wallet(client,debug=True)# Both balances should be zero since nothing has been sent yetprint("Balances of wallets before Payment tx")print(get_balance(wallet1.address,client))print(get_balance(wallet2.address,client))# Create a Payment transaction from wallet1 to wallet2payment_tx=Payment(account=wallet1.address,amount="1000",destination=wallet2.address,)# Submit the payment to the network and wait to see a response#   Behind the scenes, this fills in fields which can be looked up automatically like the fee.#   It also signs the transaction with wallet1 to prove you own the account you're paying from.payment_response=submit_and_wait(payment_tx,client,wallet1)print("Transaction was submitted")# Create a "Tx" request to look up the transaction on the ledgertx_response=client.request(Tx(transaction=payment_response.result["hash"]))# Check whether the transaction was actually validated on ledgerprint("Validated:",tx_response.result["validated"])# Check balances after 1000 drops (.001 XRP) was sent from wallet1 to wallet2print("Balances of wallets after Payment tx:")print(get_balance(wallet1.address,client))print(get_balance(wallet2.address,client))Installation and supported versionsThexrpl-pylibrary is available onPyPI. Install withpip:pip3 install xrpl-pyThe library supportsPython 3.7and later.FeaturesUsexrpl-pyto build Python applications that leverage theXRP Ledger. The library helps with all aspects of interacting with the XRP Ledger, including:Key and wallet managementSerializationTransaction Signingxrpl-pyalso provides:A network client — Seexrpl.clientsfor more information.Methods for inspecting accounts — SeeXRPL Account Methodsfor more information.Codecs for encoding and decoding addresses and other objects — SeeCore Codecsfor more information.➡️ Reference DocumentationSee the completexrpl-pyreference documentation on Read the Docs.UsageThe following sections describe some of the most commonly used modules in thexrpl-pylibrary and provide sample code.Network clientUse thexrpl.clientslibrary to create a network client for connecting to the XRP Ledger.fromxrpl.clientsimportJsonRpcClientJSON_RPC_URL="https://s.altnet.rippletest.net:51234"client=JsonRpcClient(JSON_RPC_URL)Manage keys and walletsxrpl.walletUse thexrpl.walletmodule to create a wallet from a given seed or or via aTestnet faucet.To create a wallet from a seed (in this case, the value generated usingxrpl.keypairs):wallet_from_seed=xrpl.wallet.Wallet.from_seed(seed)print(wallet_from_seed)# pub_key: ED46949E414A3D6D758D347BAEC9340DC78F7397FEE893132AAF5D56E4D7DE77B0# priv_key: -HIDDEN-# address: rG5ZvYsK5BPi9f1Nb8mhFGDTNMJhEhufn6To create a wallet from a Testnet faucet:test_wallet=generate_faucet_wallet(client)test_account=test_wallet.addressprint("Classic address:",test_account)# Classic address: rEQB2hhp3rg7sHj6L8YyR4GG47Cb7pfcuwxrpl.core.keypairsUse thexrpl.core.keypairsmodule to generate seeds and derive keypairs and addresses from those seed values.Here's an example of how to generate aseedvalue and derive anXRP Ledger "classic" addressfrom that seed.fromxrpl.coreimportkeypairsseed=keypairs.generate_seed()public,private=keypairs.derive_keypair(seed)test_account=keypairs.derive_classic_address(public)print("Here's the public key:")print(public)print("Here's the private key:")print(private)print("Store this in a secure place!")# Here's the public key:# ED3CC1BBD0952A60088E89FA502921895FC81FBD79CAE9109A8FE2D23659AD5D56# Here's the private key:# EDE65EE7882847EF5345A43BFB8E6F5EEC60F45461696C384639B99B26AAA7A5CD# Store this in a secure place!Note:You can usexrpl.core.keypairs.signto sign transactions butxrpl-pyalso provides explicit methods for safely signing and submitting transactions. SeeTransaction SigningandXRPL Transaction Methodsfor more information.Serialize and sign transactionsTo securely submit transactions to the XRP Ledger, you need to first serialize data from JSON and other formats into theXRP Ledger's canonical format, then toauthorize the transactionby digitallysigning itwith the account's private key. Thexrpl-pylibrary provides several methods to simplify this process.Use thexrpl.transactionmodule to sign and submit transactions. The module offers three ways to do this:sign_and_submit— Signs a transaction locally, then submits it to the XRP Ledger. This method does not implementreliable transaction submissionbest practices, so only use it for development or testing purposes.sign— Signs a transaction locally. This methoddoes  notsubmit the transaction to the XRP Ledger.submit_and_wait— An implementation of thereliable transaction submission guidelines, this method submits a signed transaction to the XRP Ledger and then verifies that it has been included in a validated ledger (or has failed to do so). Use this method to submit transactions for production purposes.fromxrpl.models.transactionsimportPaymentfromxrpl.transactionimportsign,submit_and_waitfromxrpl.ledgerimportget_latest_validated_ledger_sequencefromxrpl.accountimportget_next_valid_seq_numbercurrent_validated_ledger=get_latest_validated_ledger_sequence(client)# prepare the transaction# the amount is expressed in drops, not XRP# see https://xrpl.org/basic-data-types.html#specifying-currency-amountsmy_tx_payment=Payment(account=test_wallet.address,amount="2200000",destination="rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",last_ledger_sequence=current_validated_ledger+20,sequence=get_next_valid_seq_number(test_wallet.address,client),fee="10",)# sign the transactionmy_tx_payment_signed=sign(my_tx_payment,test_wallet)# submit the transactiontx_response=submit_and_wait(my_tx_payment_signed,client)Get fee from the XRP LedgerIn most cases, you can specify the minimumtransaction costof"10"for thefeefield unless you have a strong reason not to. But if you want to get thecurrent load-balanced transaction costfrom the network, you can use theget_feefunction:fromxrpl.ledgerimportget_feefee=get_fee(client)print(fee)# 10Auto-filled fieldsThexrpl-pylibrary automatically populates thefee,sequenceandlast_ledger_sequencefields when you create transactions. In the example above, you could omit those fields and let the library fill them in for you.fromxrpl.models.transactionsimportPaymentfromxrpl.transactionimportsubmit_and_wait,autofill_and_sign# prepare the transaction# the amount is expressed in drops, not XRP# see https://xrpl.org/basic-data-types.html#specifying-currency-amountsmy_tx_payment=Payment(account=test_wallet.address,amount="2200000",destination="rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe")# sign the transaction with the autofill method# (this will auto-populate the fee, sequence, and last_ledger_sequence)my_tx_payment_signed=autofill_and_sign(my_tx_payment,client,test_wallet)print(my_tx_payment_signed)# Payment(#     account='rMPUKmzmDWEX1tQhzQ8oGFNfAEhnWNFwz',#     transaction_type=<TransactionType.PAYMENT: 'Payment'>,#     fee='10',#     sequence=16034065,#     account_txn_id=None,#     flags=0,#     last_ledger_sequence=10268600,#     memos=None,#     signers=None,#     source_tag=None,#     signing_pub_key='EDD9540FA398915F0BCBD6E65579C03BE5424836CB68B7EB1D6573F2382156B444',#     txn_signature='938FB22AE7FE76CF26FD11F8F97668E175DFAABD2977BCA397233117E7E1C4A1E39681091CC4D6DF21403682803AB54CC21DC4FA2F6848811DEE10FFEF74D809',#     amount='2200000',#     destination='rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe',#     destination_tag=None,#     invoice_id=None,#     paths=None,#     send_max=None,#     deliver_min=None# )# submit the transactiontx_response=submit_and_wait(my_tx_payment_signed,client)Subscribe to ledger updatesYou can sendsubscribeandunsubscriberequests only using the WebSocket network client. These request methods allow you to be alerted of certain situations as they occur, such as when a new ledger is declared.fromxrpl.clientsimportWebsocketClienturl="wss://s.altnet.rippletest.net/"fromxrpl.modelsimportSubscribe,StreamParameterreq=Subscribe(streams=[StreamParameter.LEDGER])# NOTE: this code will run forever without a timeout, until the process is killedwithWebsocketClient(url)asclient:client.send(req)formessageinclient:print(message)# {'result': {'fee_base': 10, 'fee_ref': 10, 'ledger_hash': '7CD50477F23FF158B430772D8E82A961376A7B40E13C695AA849811EDF66C5C0', 'ledger_index': 18183504, 'ledger_time': 676412962, 'reserve_base': 20000000, 'reserve_inc': 5000000, 'validated_ledgers': '17469391-18183504'}, 'status': 'success', 'type': 'response'}# {'fee_base': 10, 'fee_ref': 10, 'ledger_hash': 'BAA743DABD168BD434804416C8087B7BDEF7E6D7EAD412B9102281DD83B10D00', 'ledger_index': 18183505, 'ledger_time': 676412970, 'reserve_base': 20000000, 'reserve_inc': 5000000, 'txn_count': 0, 'type': 'ledgerClosed', 'validated_ledgers': '17469391-18183505'}# {'fee_base': 10, 'fee_ref': 10, 'ledger_hash': 'D8227DAF8F745AE3F907B251D40B4081E019D013ABC23B68C0B1431DBADA1A46', 'ledger_index': 18183506, 'ledger_time': 676412971, 'reserve_base': 20000000, 'reserve_inc': 5000000, 'txn_count': 0, 'type': 'ledgerClosed', 'validated_ledgers': '17469391-18183506'}# {'fee_base': 10, 'fee_ref': 10, 'ledger_hash': 'CFC412B6DDB9A402662832A781C23F0F2E842EAE6CFC539FEEB287318092C0DE', 'ledger_index': 18183507, 'ledger_time': 676412972, 'reserve_base': 20000000, 'reserve_inc': 5000000, 'txn_count': 0, 'type': 'ledgerClosed', 'validated_ledgers': '17469391-18183507'}Asynchronous CodeThis library supports Python'sasynciopackage, which is used to run asynchronous code. All the async code is inxrpl.asyncioIf you are writing asynchronous code, please note that you will not be able to use any synchronous sugar functions, due to how event loops are handled. However, every synchronous method has a corresponding asynchronous method that you can use.This sample code is the asynchronous equivalent of the above section on submitting a transaction.importasynciofromxrpl.models.transactionsimportPaymentfromxrpl.asyncio.transactionimportsign,submit_and_waitfromxrpl.asyncio.ledgerimportget_latest_validated_ledger_sequencefromxrpl.asyncio.accountimportget_next_valid_seq_numberfromxrpl.asyncio.clientsimportAsyncJsonRpcClientasync_client=AsyncJsonRpcClient(JSON_RPC_URL)asyncdefsubmit_sample_transaction():current_validated_ledger=awaitget_latest_validated_ledger_sequence(async_client)# prepare the transaction# the amount is expressed in drops, not XRP# see https://xrpl.org/basic-data-types.html#specifying-currency-amountsmy_tx_payment=Payment(account=test_wallet.address,amount="2200000",destination="rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",last_ledger_sequence=current_validated_ledger+20,sequence=awaitget_next_valid_seq_number(test_wallet.address,async_client),fee="10",)# sign and submit the transactiontx_response=awaitsubmit_and_wait(my_tx_payment_signed,async_client,test_wallet)asyncio.run(submit_sample_transaction())Encode addressesUsexrpl.core.addresscodecto encode and decode addresses into and from the"classic" and X-address formats.# convert classic address to x-addressfromxrpl.coreimportaddresscodectestnet_xaddress=(addresscodec.classic_address_to_xaddress("rMPUKmzmDWEX1tQhzQ8oGFNfAEhnWNFwz",tag=0,is_test_network=True,))print(testnet_xaddress)# T7QDemmxnuN7a52A62nx2fxGPWcRahLCf3qaswfrsNW9LpsMigratingIf you're currently usingxrpl-pyversion 1, you can usethis guide to migrate to v2.ContributingIf you want to contribute to this project, seeCONTRIBUTING.md.Mailing ListsWe have a low-traffic mailing list for announcements of newxrpl-pyreleases. (About 1 email per week)Subscribe to xrpl-announceIf you're using the XRP Ledger in production, you should run arippled serverand subscribe to the ripple-server mailing list as well.Subscribe to ripple-serverCode SamplesFor samples of common use cases, see theXRPL.org Code Samplespage.You can also browse those samplesdirectly on GitHub.Report an issueExperienced an issue? Report ithere.LicenseThexrpl-pylibrary is licensed under the ISC License. SeeLICENSEfor more information.