Skip to main content

用于与 XRP 账本交互的完整 Python 库

项目描述

文件状态

xrpl-py

该库是用于与 XRP Ledger 交互的纯 Python 实现,通过为XRP Ledger 交易和核心服务器API ( ) 对象xrpl-py提供本机 Python 方法和模型,简化了 XRP Ledger 交互中最困难的部分,例如序列化和交易签名。rippled

# create a network client
from xrpl.clients import JsonRpcClient
client = JsonRpcClient("https://s.altnet.rippletest.net:51234/")

# create a wallet on the testnet
from xrpl.wallet import generate_faucet_wallet
test_wallet = generate_faucet_wallet(client)
print(test_wallet)
public_key: ED3CC1BBD0952A60088E89FA502921895FC81FBD79CAE9109A8FE2D23659AD5D56
private_key: -HIDDEN-
classic_address: rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo

# look up account info
from xrpl.models.requests.account_info import AccountInfo
acct_info = AccountInfo(
    account="rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo",
    ledger_index="current",
    queue=True,
    strict=True,
)
response = client.request(acct_info)
result = response.result
import json
print(json.dumps(result["account_data"], indent=4, sort_keys=True))
# {
#     "Account": "rBtXmAdEYcno9LWRnAGfT9qBxCeDvuVRZo",
#     "Balance": "1000000000",
#     "Flags": 0,
#     "LedgerEntryType": "AccountRoot",
#     "OwnerCount": 0,
#     "PreviousTxnID": "73CD4A37537A992270AAC8472F6681F44E400CBDE04EC8983C34B519F56AB107",
#     "PreviousTxnLgrSeq": 16233962,
#     "Sequence": 16233962,
#     "index": "FD66EC588B52712DCE74831DCB08B24157DC3198C29A0116AA64D310A58512D7"
# }

下载 贡献者

安装和支持的版本

xrpl-py库在PyPI上可用。安装pip

pip3 install xrpl-py

该库支持Python 3.7及更高版本。

支持的版本

特征

用于xrpl-py构建利用XRP Ledger的 Python 应用程序。该库有助于与 XRP 分类帐交互的所有方面,包括:

  • 密钥和钱包管理
  • 序列化
  • 交易签名

xrpl-py还提供:

  • 网络客户端 — 有关xrpl.clients详细信息,请参阅。
  • 检查帐户的方法——有关更多信息,请参阅XRPL 帐户方法
  • 用于编码和解码地址和其他对象的编解码器 - 有关更多信息,请参阅核心编解码器。

➡️ 参考文档

请参阅 Read the Docs 上的完整xrpl-py参考文档

用法

以下部分描述了库中一些最常用的模块xrpl-py并提供了示例代码。

网络客户端

使用该xrpl.clients库创建用于连接到 XRP 分类帐的网络客户端。

from xrpl.clients import JsonRpcClient
JSON_RPC_URL = "https://s.altnet.rippletest.net:51234/"
client = JsonRpcClient(JSON_RPC_URL)

管理钥匙和钱包

xrpl.wallet

使用该xrpl.wallet模块从给定的种子或通过测试网水龙头创建钱包。

从种子创建钱包(在本例中,使用 生成的值xrpl.keypairs):

wallet_from_seed = xrpl.wallet.Wallet(seed, 0)
print(wallet_from_seed)
# pub_key: ED46949E414A3D6D758D347BAEC9340DC78F7397FEE893132AAF5D56E4D7DE77B0
# priv_key: -HIDDEN-
# classic_address: rG5ZvYsK5BPi9f1Nb8mhFGDTNMJhEhufn6

从测试网水龙头创建钱包:

test_wallet = generate_faucet_wallet(client)
test_account = test_wallet.classic_address
print("Classic address:", test_account)
# Classic address: rEQB2hhp3rg7sHj6L8YyR4GG47Cb7pfcuw

xrpl.core.keypairs

使用该xrpl.core.keypairs模块生成种子并从这些种子值派生密钥对和地址。

这是一个如何生成seed值并从该种子派生XRP 分类帐“经典”地址的示例。

from xrpl.core import keypairs
seed = 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!

注意:您可以用于xrpl.core.keypairs.sign签署交易,但xrpl-py也提供了安全签署和提交交易的明确方法。有关更多信息,请参阅事务签名XRPL 事务方法

序列化和签署交易

为了安全地向 XRP 账本提交交易,您需要首先将 JSON 和其他格式的数据序列化为XRP 账本的规范格式,然后通过使用账户的私钥对交易进行数字签名来授权交易。该库提供了几种方法来简化此过程。xrpl-py

使用该xrpl.transaction模块签署和提交交易。该模块提供了三种方法来做到这一点:

from xrpl.models.transactions import Payment
from xrpl.transaction import safe_sign_transaction, send_reliable_submission
from xrpl.ledger import get_latest_validated_ledger_sequence
from xrpl.account import get_next_valid_seq_number

current_validated_ledger = get_latest_validated_ledger_sequence(client)
test_wallet.sequence = get_next_valid_seq_number(test_wallet.classic_address, client)

# prepare the transaction
# the amount is expressed in drops, not XRP
# see https://xrpl.org/basic-data-types.html#specifying-currency-amounts
my_tx_payment = Payment(
    account=test_wallet.classic_address,
    amount="2200000",
    destination="rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
    last_ledger_sequence=current_validated_ledger + 20,
    sequence=test_wallet.sequence,
    fee="10",
)
# sign the transaction
my_tx_payment_signed = safe_sign_transaction(my_tx_payment,test_wallet)

# submit the transaction
tx_response = send_reliable_submission(my_tx_payment_signed, client)

从 XRP 账本中收取费用

在大多数情况下,您可以为该字段指定最低交易成本,除非您有充分的理由不这样做。但是如果你想从网络中获取当​​前负载均衡的交易成本,你可以使用函数:"10"feeget_fee

from xrpl.ledger import get_fee
fee = get_fee(client)
print(fee)
# 10

自动填充字段

当您创建事务时,xrpl-py库会自动填充和字段。在上面的示例中,您可以省略这些字段并让库为您填写它们。feesequencelast_ledger_sequence

from xrpl.models.transactions import Payment
from xrpl.transaction import send_reliable_submission, safe_sign_and_autofill_transaction
# prepare the transaction
# the amount is expressed in drops, not XRP
# see https://xrpl.org/basic-data-types.html#specifying-currency-amounts
my_tx_payment = Payment(
    account=test_wallet.classic_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 = safe_sign_and_autofill_transaction(my_tx_payment, test_wallet, client)
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 transaction
tx_response = send_reliable_submission(my_tx_payment_signed, client)

订阅分类帐更新

您只能使用 WebSocket 网络客户端发送subscribe和请求。unsubscribe这些请求方法允许您在某些情况发生时收到警报,例如在声明新分类帐时。

from xrpl.clients import WebsocketClient
url = "wss://s.altnet.rippletest.net/"
from xrpl.models.requests import Subscribe, StreamParameter
req = Subscribe(streams=[StreamParameter.LEDGER])
# NOTE: this code will run forever without a timeout, until the process is killed
with WebsocketClient(url) as client:
    client.send(req)
    for message in client:
        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'}

异步代码

该库支持 Python 的asyncio包,用于运行异步代码。所有异步代码都在中xrpl.asyncio如果您正在编写异步代码,请注意,由于事件循环的处理方式,您将无法使用任何同步糖函数。但是,每个同步方法都有一个可以使用的相应异步方法。

此示例代码与上述提交事务部分的异步等效。

import asyncio
from xrpl.models.transactions import Payment
from xrpl.asyncio.transaction import safe_sign_transaction, send_reliable_submission
from xrpl.asyncio.ledger import get_latest_validated_ledger_sequence
from xrpl.asyncio.account import get_next_valid_seq_number
from xrpl.asyncio.clients import AsyncJsonRpcClient

async_client = AsyncJsonRpcClient(JSON_RPC_URL)

async def submit_sample_transaction():
    current_validated_ledger = await get_latest_validated_ledger_sequence(async_client)
    test_wallet.sequence = await get_next_valid_seq_number(test_wallet.classic_address, async_client)

    # prepare the transaction
    # the amount is expressed in drops, not XRP
    # see https://xrpl.org/basic-data-types.html#specifying-currency-amounts
    my_tx_payment = Payment(
        account=test_wallet.classic_address,
        amount="2200000",
        destination="rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
        last_ledger_sequence=current_validated_ledger + 20,
        sequence=test_wallet.sequence,
        fee="10",
    )
    # sign the transaction
    my_tx_payment_signed = await safe_sign_transaction(my_tx_payment,test_wallet)

    # submit the transaction
    tx_response = await send_reliable_submission(my_tx_payment_signed, async_client)

asyncio.run(submit_sample_transaction())

编码地址

用于xrpl.core.addresscodec将地址编码和解码为“经典”和 X-address 格式

# convert classic address to x-address
from xrpl.core import addresscodec
testnet_xaddress = (
    addresscodec.classic_address_to_xaddress(
        "rMPUKmzmDWEX1tQhzQ8oGFNfAEhnWNFwz",
        tag=0,
        is_test_network=True,
    )
)
print(testnet_xaddress)
# T7QDemmxnuN7a52A62nx2fxGPWcRahLCf3qaswfrsNW9Lps

贡献

如果您想为此项目做出贡献,请参阅CONTRIBUTING.md

邮件列表

我们有一个低流量的邮件列表,用于发布新xrpl.js版本的公告。(每周大约 1 封电子邮件)

如果您在生产中使用 XRP Ledger,您应该运行一个波纹服务器并订阅波纹服务器邮件列表。

执照

xrpl-py库根据 ISC 许可证获得许可。有关更多信息,请参阅许可证

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

xrpl-py-1.6.0.tar.gz (122.9 kB 查看哈希

已上传 source

内置分布

xrpl_py-1.6.0-py3-none-any.whl (202.4 kB 查看哈希

已上传 py3