Skip to content

Commit fa20eac

Browse files
committed
add python tuto
1 parent 242f208 commit fa20eac

8 files changed

+528
-0
lines changed

python/README.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# XRPL Python - Simple Python Scripts
2+
3+
This repository contains Python scripts to interact with the XRP Ledger (XRPL), enabling wallet generation, trustline creation, transactions, and AMM operations.
4+
5+
## 📁 Project Structure
6+
7+
- `generate.py` → Generates a new XRPL wallet (address & seed)
8+
- `generate_and_trustline.py` → Generates a wallet and establishes a trustline
9+
- `trustline.py` → Creates a trustline for the RLUSD token
10+
- `xrp_transaction.py` → Handles XRP transactions
11+
- `rlusd_transaction.py` → Manages RLUSD token transactions
12+
- `amm_create_RLUSD_XRP.py` → Creates an AMM pool for RLUSD/XRP pair
13+
- `amm_deposit_RLUSD_XRP.py` → Deposits assets into an existing AMM pool
14+
15+
## 🔧 Installation & Setup
16+
17+
1. Install required packages:
18+
```bash
19+
pip install -r requirements.txt
20+
```
21+
22+
## 📝 Usage
23+
24+
1. Generate a new wallet:
25+
```bash
26+
python generate.py
27+
```
28+
29+
2. Generate wallet and create trustline for RLUSD:
30+
```bash
31+
python generate_and_trustline.py
32+
```
33+
34+
3. Create trustline for existing wallet:
35+
```bash
36+
python trustline.py
37+
```
38+
Update the script with your wallet seed first.
39+
40+
4. Send XRP transaction:
41+
```bash
42+
python xrp_transaction.py
43+
```
44+
Update the script with your wallet seed and destination address.
45+
46+
5. Send RLUSD transaction:
47+
```bash
48+
python rlusd_transaction.py
49+
```
50+
Update the script with your wallet seed and destination address.
51+
52+
6. Create AMM pool:
53+
```bash
54+
python amm_create_RLUSD_XRP.py
55+
```
56+
Update the script with your wallet seed and desired initial amounts.
57+
58+
7. Deposit into AMM pool:
59+
```bash
60+
python amm_deposit_RLUSD_XRP.py
61+
```
62+
Update the script with your wallet seed and deposit amounts.
63+
64+
## ⚠️ Important Notes
65+
66+
- All scripts use the XRPL Testnet
67+
- Keep your seed (private key) secure and never share it. The seeds present in the example files are for testing purposes only.
68+
- Make sure you have sufficient XRP for fees and reserves
69+
- For RLUSD operations, you need an established trustline first
70+
71+
## 🔗 Links
72+
73+
- [XRPL Documentation](https://xrpl.org/)
74+
- [More Examples](https://docs.xrpl-commons.org/)
75+
- [Ripple Stablecoin](https://ripple.com/solutions/stablecoin/)

python/amm_create_RLUSD_XRP.py

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from xrpl.clients import JsonRpcClient
2+
from xrpl.transaction import submit_and_wait, sign, submit
3+
from xrpl.wallet import Wallet
4+
from xrpl.utils import xrp_to_drops
5+
from xrpl.models.requests import AccountInfo
6+
from xrpl.models.transactions import Transaction
7+
8+
def create_amm(seed, trading_fee=500):
9+
"""
10+
Creates an AMM (Automated Market Maker) for XRP/RLUSD pair
11+
12+
Parameters:
13+
seed: The seed of the wallet to create the AMM
14+
trading_fee: Trading fee in basis points (e.g., 500 = 0.5%)
15+
"""
16+
# Define the network client
17+
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
18+
19+
# Create wallet from seed
20+
wallet = Wallet.from_seed(seed)
21+
22+
# Convert currency code to hex
23+
currency_hex = "524C555344000000000000000000000000000000" # Hex for "RLUSD"
24+
25+
# Get account sequence
26+
account_info = client.request(AccountInfo(
27+
account=wallet.classic_address,
28+
ledger_index="validated"
29+
))
30+
sequence = account_info.result['account_data']['Sequence']
31+
print(f"Sequence: {sequence}")
32+
# Prepare AMM creation transaction
33+
tx_dict = {
34+
"transaction_type": "AMMCreate", # Transaction type for AMM creation https://xrpl.org/docs/references/protocol/transactions/types/ammcreate
35+
"account": wallet.classic_address,
36+
"amount": {
37+
"currency": currency_hex,
38+
"issuer": "rQhWct2fv4Vc4KRjRgMrxa8xPN9Zx9iLKV",
39+
"value": "1" # Amount of RLUSD
40+
},
41+
"amount2": "10000000", # Amount of XRP in drops (10 XRP)
42+
"trading_fee": trading_fee,
43+
"fee": "2000000", # Higher fee for AMM creation
44+
"flags": 2147483648, # tfFullyCanonicalSig
45+
"sequence": sequence,
46+
}
47+
48+
# Create Transaction object
49+
amm_tx = Transaction.from_dict(tx_dict)
50+
51+
print("\n=== Creating AMM ===")
52+
print(f"Account: {wallet.classic_address}")
53+
print(f"RLUSD Amount: 1")
54+
print(f"XRP Amount: 10")
55+
print(f"Trading Fee: {trading_fee/1000}%")
56+
57+
try:
58+
# Sign transaction
59+
signed_tx = sign(amm_tx, wallet)
60+
61+
# Submit transaction
62+
response = submit(signed_tx, client)
63+
64+
# Check the result
65+
if "engine_result" in response.result and response.result["engine_result"] == "tesSUCCESS":
66+
print("\nAMM created successfully!")
67+
print(f"Transaction hash: {response.result.get('tx_json', {}).get('hash')}")
68+
return response
69+
else:
70+
print("\nAMM creation failed")
71+
print(f"Error: {response.result.get('engine_result_message')}")
72+
return response
73+
74+
except Exception as e:
75+
print(f"\nError creating AMM: {str(e)}")
76+
raise e
77+
78+
print("==============================\n")
79+
80+
if __name__ == "__main__":
81+
# Example usage - replace with your values
82+
seed = "sEd71CfChR48xigRKg5AJcarEcgFMPk" # Replace with your wallet seed
83+
84+
try:
85+
# Create AMM with 0.5% trading fee
86+
response = create_amm(seed, trading_fee=500)
87+
except Exception as e:
88+
print(f"Final error: {str(e)}")

python/amm_deposit_RLUSD_XRP.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
from xrpl.clients import JsonRpcClient
2+
from xrpl.transaction import submit_and_wait, sign, submit
3+
from xrpl.wallet import Wallet
4+
from xrpl.models.requests import AccountInfo
5+
from xrpl.models.transactions import Transaction
6+
from decimal import Decimal
7+
8+
def amm_deposit_single_rlusd(seed, rlusd_amount="0.5"):
9+
"""
10+
Deposits only RLUSD into an existing AMM
11+
"""
12+
# Define the network client
13+
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
14+
15+
# Create wallet from seed
16+
wallet = Wallet.from_seed(seed)
17+
18+
# RLUSD constants
19+
currency_hex = "524C555344000000000000000000000000000000" # Hex for "RLUSD"
20+
issuer = "rQhWct2fv4Vc4KRjRgMrxa8xPN9Zx9iLKV"
21+
22+
# Get account sequence
23+
account_info = client.request(AccountInfo(
24+
account=wallet.classic_address,
25+
ledger_index="validated"
26+
))
27+
sequence = account_info.result['account_data']['Sequence']
28+
29+
# Prepare AMM deposit transaction
30+
tx_dict = {
31+
"transaction_type": "AMMDeposit",
32+
"account": wallet.classic_address,
33+
"amount": {
34+
"currency": currency_hex,
35+
"issuer": issuer,
36+
"value": str(rlusd_amount)
37+
},
38+
"asset": {
39+
"currency": currency_hex,
40+
"issuer": issuer
41+
},
42+
"asset2": {
43+
"currency": "XRP"
44+
},
45+
"flags": 524288, # tfSingleAsset -> full doc https://xrpl.org/docs/references/protocol/transactions/types/ammdeposit
46+
"fee": "10",
47+
"sequence": sequence
48+
}
49+
50+
# Create Transaction object
51+
deposit_tx = Transaction.from_dict(tx_dict)
52+
53+
print("\n=== Depositing RLUSD to AMM ===")
54+
print(f"Account: {wallet.classic_address}")
55+
print(f"RLUSD Amount: {rlusd_amount} RLUSD")
56+
57+
try:
58+
# Sign transaction
59+
signed_tx = sign(deposit_tx, wallet)
60+
61+
# Submit transaction
62+
response = submit(signed_tx, client)
63+
64+
# Check the result
65+
if "engine_result" in response.result and response.result["engine_result"] == "tesSUCCESS":
66+
print("\nDeposit successful!")
67+
print(f"Transaction hash: {response.result.get('tx_json', {}).get('hash')}")
68+
return response
69+
else:
70+
print("\nDeposit failed")
71+
print(f"Error: {response.result}")
72+
return response
73+
74+
except Exception as e:
75+
print(f"\nError making deposit: {str(e)}")
76+
raise e
77+
78+
if __name__ == "__main__":
79+
seed = "sEd71CfChR48xigRKg5AJcarEcgFMPk"
80+
rlusd_amount = "0.5"
81+
82+
try:
83+
response = amm_deposit_single_rlusd(seed, rlusd_amount)
84+
except Exception as e:
85+
print(f"Final error: {str(e)}")

python/generate_and_trustline.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
from xrpl.clients import JsonRpcClient
2+
from xrpl.models.transactions import TrustSet
3+
from xrpl.utils import xrp_to_drops
4+
from xrpl.transaction import submit_and_wait
5+
from xrpl.wallet import generate_faucet_wallet
6+
7+
def text_to_hex(text):
8+
"""Convert text to hex with proper padding"""
9+
if len(text) > 20:
10+
raise ValueError("Text must be 20 characters or less")
11+
# Convert to hex and remove '0x' prefix
12+
hex_text = text.encode('ascii').hex().upper()
13+
# Pad with zeros to make it exactly 40 characters
14+
return hex_text.ljust(40, '0')
15+
16+
def create_trustline(issuer_address, currency_code, limit_amount="1000000000"):
17+
"""
18+
Creates a trustline for a specific currency on XRPL testnet
19+
20+
Parameters:
21+
issuer_address: The address of the token issuer
22+
currency_code: The currency code (e.g., 'USD')
23+
limit_amount: The trust line limit amount (default: 1000000000)
24+
"""
25+
# Define the network client
26+
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
27+
wallet = generate_faucet_wallet(client)
28+
29+
# Convert currency code to proper hex format
30+
try:
31+
currency_hex = text_to_hex(currency_code)
32+
except ValueError as e:
33+
print(f"Error: {e}")
34+
return
35+
36+
# Prepare the trust set transaction
37+
trust_set_tx = TrustSet(
38+
account=wallet.classic_address,
39+
limit_amount={
40+
"currency": currency_hex,
41+
"issuer": issuer_address,
42+
"value": str(limit_amount)
43+
}
44+
)
45+
46+
print("\n=== Creating Trustline ===")
47+
print(f"Account: {wallet.classic_address}")
48+
print(f"Currency (original): {currency_code}")
49+
print(f"Currency (hex): {currency_hex}")
50+
print(f"Issuer: {issuer_address}")
51+
print(f"Limit: {limit_amount}")
52+
53+
try:
54+
# Submit and wait for validation
55+
response = submit_and_wait(trust_set_tx, client, wallet)
56+
57+
# Check the result
58+
if response.is_successful():
59+
print("\nTrustline created successfully!")
60+
print(f"Transaction hash: {response.result['hash']}")
61+
print(f"Wallet Address: {wallet.classic_address}")
62+
print(f"Wallet Seed: {wallet.seed}")
63+
else:
64+
print("\nFailed to create trustline")
65+
print(f"Error: {response.result.get('engine_result_message')}")
66+
67+
except Exception as e:
68+
print(f"\nError creating trustline: {str(e)}")
69+
70+
print("==============================\n")
71+
72+
if __name__ == "__main__":
73+
issuer_address = "rQhWct2fv4Vc4KRjRgMrxa8xPN9Zx9iLKV"
74+
currency_code = "RLUSD"
75+
76+
create_trustline(issuer_address, currency_code)

python/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
xrpl-py

0 commit comments

Comments
 (0)