Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add xrpl.js code snippets over to xrpl-py #443

Merged
merged 16 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
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
5 changes: 3 additions & 2 deletions docs/index.rst
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
@@ -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

Change Your Password by Setting a Regular Key
connorjchen marked this conversation as resolved.
Show resolved Hide resolved
-----------------------------------------------

.. 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
@@ -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:
connorjchen marked this conversation as resolved.
Show resolved Hide resolved
# 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
@@ -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 (issuer) to destination (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 should have 0 FOO 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
@@ -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
@@ -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
@@ -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))