Skip to content

Commit

Permalink
docs: add xrpl.js code snippets over to xrpl-py (#443)
Browse files Browse the repository at this point in the history
* Add code snippets to documentation + repo

* Update documentation for code snippets
  • Loading branch information
connorjchen committed Oct 7, 2022
1 parent 96697c1 commit b2216de
Show file tree
Hide file tree
Showing 11 changed files with 400 additions and 6 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ To see the output:
cd docs/_build/html/

# Open the index file to view it in a browser:
open _build/html/index.html
open index.html
```

## Update `definitions.json`
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A pure Python implementation for interacting with the XRP Ledger, the `xrpl-py`
```py
# create a network client
from xrpl.clients import JsonRpcClient
client = JsonRpcClient("https://s.altnet.rippletest.net:51234/")
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")

# create a wallet on the testnet
from xrpl.wallet import generate_faucet_wallet
Expand Down Expand Up @@ -90,7 +90,7 @@ Use the `xrpl.clients` library to create a network client for connecting to the

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

Expand Down
5 changes: 3 additions & 2 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to xrpl-py's documentation!
Welcome to xrpl-py's Documentation!
===================================

A pure Python implementation for interacting with the XRP Ledger, the ``xrpl-py`` library simplifies the hardest parts of XRP Ledger interaction, like serialization and transaction signing, by providing native Python methods and models for `XRP Ledger transactions <https://xrpl.org/transaction-formats.html>`_ and core server `API <https://xrpl.org/api-conventions.html>`_ (`rippled <https://github.com/ripple/rippled>`_) objects.
Expand All @@ -30,6 +30,7 @@ If you run into any bugs or other problems with the library, please report them
:maxdepth: 1
:caption: Table of Contents

source/snippets
source/xrpl.account
source/xrpl.ledger
source/xrpl.transaction
Expand All @@ -42,7 +43,7 @@ If you run into any bugs or other problems with the library, please report them
source/xrpl.asyncio


Indices and tables
Indices and Tables
==================

* :ref:`genindex`
Expand Down
37 changes: 37 additions & 0 deletions docs/source/snippets.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
XRPL Code Snippets
===================

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

.. toctree::
:maxdepth: 1

Look Up a Transaction on the Ledger
-------------------------------------

.. literalinclude:: ../../snippets/get_transaction.py

Send a Transaction and See if It Gets Validated
-----------------------------------------------

.. literalinclude:: ../../snippets/reliable_transaction_submission.py

Set a Regular Key
-----------------------------------------------

.. literalinclude:: ../../snippets/set_regular_key.py

Set up an Escrow
-----------------

.. literalinclude:: ../../snippets/send_escrow.py

Find the Best Path to Trade With
----------------------------------

.. literalinclude:: ../../snippets/paths.py

Handle Partial Payments
------------------------

.. literalinclude:: ../../snippets/partial_payment.py
29 changes: 29 additions & 0 deletions snippets/get_transaction.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""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!")
101 changes: 101 additions & 0 deletions snippets/partial_payment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""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"])
50 changes: 50 additions & 0 deletions snippets/paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""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))
52 changes: 52 additions & 0 deletions snippets/reliable_transaction_submission.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""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))
67 changes: 67 additions & 0 deletions snippets/send_escrow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""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))

0 comments on commit b2216de

Please sign in to comment.