clean up snippets

This commit is contained in:
Phu Pham
2023-01-31 17:36:40 -05:00
parent 1fcbb3a5fc
commit 70997788f2
11 changed files with 141 additions and 65 deletions

View File

@@ -2,4 +2,4 @@
Create, claim and verify a Payment Channel. Create, claim and verify a Payment Channel.
For more context, see [PayChannel](https://xrpl.org/paychannel.html#paychannel). For more context, see [PayChannel](https://xrpl.org/paychannel.html).

View File

@@ -1,3 +1,7 @@
/*
* Create, claim and verify a Payment Channel.
* Reference: https://xrpl.org/paychannel.html
*/
import { import {
AccountObjectsRequest, AccountObjectsRequest,
Client, Client,
@@ -19,8 +23,8 @@ async function claimPayChannel(): Promise<void> {
const { wallet: wallet2 } = await client.fundWallet() const { wallet: wallet2 } = await client.fundWallet()
console.log('Balances of wallets before Payment Channel is claimed:') console.log('Balances of wallets before Payment Channel is claimed:')
console.log(`Balance of ${wallet1.address} is ${await client.getXrpBalance(wallet1.address)} XRP) console.log(`Balance of ${wallet1.address} is ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Balance of ${wallet2.address} is ${await client.getXrpBalance(wallet2.address)} XRP) console.log(`Balance of ${wallet2.address} is ${await client.getXrpBalance(wallet2.address)} XRP`)
// create a Payment Channel and submit and wait for tx to be validated // create a Payment Channel and submit and wait for tx to be validated
const paymentChannelCreate: PaymentChannelCreate = { const paymentChannelCreate: PaymentChannelCreate = {
@@ -31,11 +35,13 @@ async function claimPayChannel(): Promise<void> {
SettleDelay: 86400, SettleDelay: 86400,
PublicKey: wallet1.publicKey, PublicKey: wallet1.publicKey,
} }
console.log("Submitting a PaymentChannelCreate transaction...")
const paymentChannelResponse = await client.submitAndWait( const paymentChannelResponse = await client.submitAndWait(
paymentChannelCreate, paymentChannelCreate,
{ wallet: wallet1 }, { wallet: wallet1 },
) )
console.log("PaymentChannelCreate transaction response:")
console.log(paymentChannelResponse) console.log(paymentChannelResponse)
// check that the object was actually created // check that the object was actually created
@@ -61,14 +67,17 @@ async function claimPayChannel(): Promise<void> {
Amount: '100', Amount: '100',
} }
console.log("Submitting a PaymentChannelClaim transaction...")
const channelClaimResponse = await client.submit(paymentChannelClaim, { const channelClaimResponse = await client.submit(paymentChannelClaim, {
wallet: wallet1, wallet: wallet1,
}) })
console.log("PaymentChannelClaim transaction response:")
console.log(channelClaimResponse) console.log(channelClaimResponse)
console.log('Balances of wallets after Payment Channel is claimed:') console.log('Balances of wallets after Payment Channel is claimed:')
console.log(`Balance of ${wallet1.address} is ${await client.getXrpBalance(wallet1.address)} XRP) console.log(`Balance of ${wallet1.address} is ${await client.getXrpBalance(wallet1.address)} XRP`)
console.log(`Balance of ${wallet2.address} is ${await client.getXrpBalance(wallet2.address)} XRP) console.log(`Balance of ${wallet2.address} is ${await client.getXrpBalance(wallet2.address)} XRP`)
await client.disconnect() await client.disconnect()
} }

View File

@@ -1,4 +1,7 @@
/*
* Retrieve and display a transaction on the ledger.
* Reference: https://xrpl.org/tx.html
*/
import { Client, LedgerResponse, TxResponse } from 'xrpl' import { Client, LedgerResponse, TxResponse } from 'xrpl'
const client = new Client('wss://s.altnet.rippletest.net:51233') const client = new Client('wss://s.altnet.rippletest.net:51233')
@@ -18,7 +21,8 @@ async function getTransaction(): Promise<void> {
command: 'tx', command: 'tx',
transaction: transactions[0], transaction: transactions[0],
}) })
console.log("Response from 'tx' request:", tx) console.log("First transaction in the ledger:")
console.log(tx)
// The meta field would be a string(hex) when the `binary` parameter is `true` for the `tx` request. // The meta field would be a string(hex) when the `binary` parameter is `true` for the `tx` request.
if (tx.result.meta == null) { if (tx.result.meta == null) {

View File

@@ -24,6 +24,7 @@ if transactions:
# Create a Transaction request and have the client call it # Create a Transaction request and have the client call it
tx_request = Tx(transaction=transactions[0]) tx_request = Tx(transaction=transactions[0])
tx_response = client.request(tx_request) tx_response = client.request(tx_request)
print("First transaction in the ledger:")
print(tx_response) print(tx_response)
else: else:
print("No transactions were found on the ledger!") print("No transactions were found on the ledger!")

View File

@@ -1,40 +1,82 @@
/*
import { Client, LedgerResponse, TxResponse } from 'xrpl' * Create and submit a SignerListSet and multisign a transaction.
* Reference: https://xrpl.org/multi-signing.html
*/
import {
multisign,
Client,
AccountSet,
convertStringToHex,
SignerListSet,
} from 'xrpl'
const client = new Client('wss://s.altnet.rippletest.net:51233') const client = new Client('wss://s.altnet.rippletest.net:51233')
async function getTransaction(): Promise<void> { async function multisigning(): Promise<void> {
await client.connect() await client.connect()
const ledger: LedgerResponse = await client.request({ /*
command: 'ledger', * This wallet creation is for demonstration purposes.
transactions: true, * In practice, users generally will not have all keys in one spot,
ledger_index: 'validated', * hence, users need to implement a way to get signatures.
*/
const { wallet: wallet1 } = await client.fundWallet()
const { wallet: wallet2 } = await client.fundWallet()
const { wallet: walletMaster } = await client.fundWallet()
const signerListSet: SignerListSet = {
TransactionType: 'SignerListSet',
Account: walletMaster.classicAddress,
SignerEntries: [
{
SignerEntry: {
Account: wallet1.classicAddress,
SignerWeight: 1,
},
},
{
SignerEntry: {
Account: wallet2.classicAddress,
SignerWeight: 1,
},
},
],
SignerQuorum: 2,
}
const signerListResponse = await client.submit(signerListSet, {
wallet: walletMaster,
}) })
console.log(ledger) console.log('SignerListSet constructed successfully:')
console.log(signerListResponse)
const transactions = ledger.result.ledger.transactions const accountSet: AccountSet = {
if (transactions) { TransactionType: 'AccountSet',
const tx: TxResponse = await client.request({ Account: walletMaster.classicAddress,
command: 'tx', Domain: convertStringToHex('example.com'),
transaction: transactions[0], }
}) const accountSetTx = await client.autofill(accountSet, 2)
console.log(tx) console.log('AccountSet transaction is ready to be multisigned:')
console.log(accountSetTx)
const { tx_blob: tx_blob1 } = wallet1.sign(accountSetTx, true)
const { tx_blob: tx_blob2 } = wallet2.sign(accountSetTx, true)
const multisignedTx = multisign([tx_blob1, tx_blob2])
const submitResponse = await client.submit(multisignedTx)
// The meta field would be a string(hex) when the `binary` parameter is `true` for the `tx` request. if (submitResponse.result.engine_result === 'tesSUCCESS') {
if (tx.result.meta == null) { console.log('The multisigned transaction was accepted by the ledger:')
throw new Error('meta not included in the response') console.log(submitResponse)
} if (submitResponse.result.tx_json.Signers) {
/* console.log(
* delivered_amount is the amount actually received by the destination account. `The transaction had ${submitResponse.result.tx_json.Signers.length} signatures`,
* Use this field to determine how much was delivered, regardless of whether the transaction is a partial payment. )
* https://xrpl.org/transaction-metadata.html#delivered_amount
*/
if (typeof tx.result.meta !== 'string') {
console.log('delivered_amount:', tx.result.meta.delivered_amount)
} }
} else {
console.log(
"The multisigned transaction was rejected by rippled. Here's the response from rippled:",
)
console.log(submitResponse)
} }
await client.disconnect() await client.disconnect()
} }
void getTransaction() void multisigning()

View File

@@ -1,4 +1,8 @@
"""Example of how we can multisign a transaction""" """
Example of how we can multisign a transaction.
This will only work with version 2.0.0-beta.0 or later.
Reference: https://xrpl.org/multi-signing.html
"""
from xrpl.clients import JsonRpcClient from xrpl.clients import JsonRpcClient
from xrpl.models.requests import SubmitMultisigned from xrpl.models.requests import SubmitMultisigned
from xrpl.models.transactions import AccountSet, SignerEntry, SignerListSet from xrpl.models.transactions import AccountSet, SignerEntry, SignerListSet

View File

@@ -3,6 +3,7 @@ import { Client, Payment, PaymentFlags, TrustSet } from 'xrpl'
const client = new Client('wss://s.altnet.rippletest.net:51233') const client = new Client('wss://s.altnet.rippletest.net:51233')
// This snippet walks us through partial payment. // This snippet walks us through partial payment.
// Reference: https://xrpl.org/partial-payments.html
async function partialPayment(): Promise<void> { async function partialPayment(): Promise<void> {
await client.connect() await client.connect()
@@ -21,14 +22,18 @@ async function partialPayment(): Promise<void> {
value: '10000000000', value: '10000000000',
}, },
} }
console.log("Submitting a TrustSet transaction...")
await client.submitAndWait(trust_set_tx, { const trust_set_res = await client.submitAndWait(trust_set_tx, {
wallet: wallet2, wallet: wallet2,
}) })
console.log("TrustSet transaction response:")
console.log(trust_set_res)
console.log('Balances after trustline is created') console.log('Balances after trustline is created')
console.log(await client.getBalances(wallet1.classicAddress)) console.log(`Balance of ${wallet1.classicAddress} is ${await client.getBalances(wallet1.classicAddress)}`)
console.log(await client.getBalances(wallet2.classicAddress)) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getBalances(wallet2.classicAddress)}`)
// Initially, the issuer(wallet1) sends an amount to the other account(wallet2) // Initially, the issuer(wallet1) sends an amount to the other account(wallet2)
const issue_quantity = '3840' const issue_quantity = '3840'
@@ -47,11 +52,11 @@ async function partialPayment(): Promise<void> {
const initialPayment = await client.submitAndWait(payment, { const initialPayment = await client.submitAndWait(payment, {
wallet: wallet1, wallet: wallet1,
}) })
console.log(initialPayment) console.log("Initial payment response:", initialPayment)
console.log('Balances after issuer(wallet1) sends IOU("FOO") to wallet2') console.log('Balances after issuer(wallet1) sends IOU("FOO") to wallet2')
console.log(await client.getBalances(wallet1.classicAddress)) console.log(`Balance of ${wallet1.classicAddress} is ${await client.getBalances(wallet1.classicAddress)}`)
console.log(await client.getBalances(wallet2.classicAddress)) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getBalances(wallet2.classicAddress)}`)
/* /*
* Send money less than the amount specified on 2 conditions: * Send money less than the amount specified on 2 conditions:
@@ -75,16 +80,17 @@ async function partialPayment(): Promise<void> {
} }
// submit payment // submit payment
console.log("Submitting a Partial Payment transaction...")
const submitResponse = await client.submitAndWait(partialPaymentTx, { const submitResponse = await client.submitAndWait(partialPaymentTx, {
wallet: wallet2, wallet: wallet2,
}) })
console.log(submitResponse) console.log("Partial Payment response: ", submitResponse)
console.log( console.log(
"Balances after Partial Payment, when wallet2 tried to send 4000 FOO's", "Balances after Partial Payment, when wallet2 tried to send 4000 FOO's",
) )
console.log(await client.getBalances(wallet1.classicAddress)) console.log(`Balance of ${wallet1.classicAddress} is ${await client.getBalances(wallet1.classicAddress)}`)
console.log(await client.getBalances(wallet2.classicAddress)) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getBalances(wallet2.classicAddress)}`)
await client.disconnect() await client.disconnect()
} }

View File

@@ -35,7 +35,9 @@ send_reliable_submission(signed_trust_set_tx, client)
# Both balances should be zero since nothing has been sent yet # Both balances should be zero since nothing has been sent yet
print("Balances after trustline is claimed:") print("Balances after trustline is claimed:")
print("Balance of ${wallet1.classic_address} is:")
print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"]) print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"])
print("Balance of ${wallet2.classic_address} is:")
print((client.request(AccountLines(account=wallet2.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) # Create a Payment to send 3840 FOO from wallet1 (issuer) to destination (wallet2)
@@ -53,11 +55,13 @@ payment_tx = Payment(
# Sign and autofill, then send transaction to the ledger # Sign and autofill, then send transaction to the ledger
signed_payment_tx = autofill_and_sign(payment_tx, wallet1, client) signed_payment_tx = autofill_and_sign(payment_tx, wallet1, client)
payment_response = send_reliable_submission(signed_payment_tx, client) payment_response = send_reliable_submission(signed_payment_tx, client)
print(payment_response) print("Initial Payment response: ", payment_response)
# Issuer (wallet1) should have -3840 FOO and destination (wallet2) should have 3840 FOO # Issuer (wallet1) should have -3840 FOO and destination (wallet2) should have 3840 FOO
print("Balances after wallet1 sends 3840 FOO to wallet2:") print("Balances after wallet1 sends 3840 FOO to wallet2:")
print("Balance of ${wallet1.classic_address} is:")
print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"]) print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"])
print("Balance of ${wallet2.classic_address} is:")
print((client.request(AccountLines(account=wallet2.classic_address))).result["lines"]) print((client.request(AccountLines(account=wallet2.classic_address))).result["lines"])
# Send money less than the amount specified on 2 conditions: # Send money less than the amount specified on 2 conditions:
@@ -88,9 +92,11 @@ partial_payment_tx = Payment(
# Sign and autofill, then send transaction to the ledger # Sign and autofill, then send transaction to the ledger
signed_partial_payment_tx = autofill_and_sign(partial_payment_tx, wallet2, client) signed_partial_payment_tx = autofill_and_sign(partial_payment_tx, wallet2, client)
partial_payment_response = send_reliable_submission(signed_partial_payment_tx, client) partial_payment_response = send_reliable_submission(signed_partial_payment_tx, client)
print(partial_payment_response) print("Partial Payment response: ", partial_payment_response)
# Tried sending 4000 of 3840 FOO -> wallet1 and wallet2 should have 0 FOO # 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("Balances after Partial Payment, when wallet2 tried to send 4000 FOOs")
print("Balance of ${wallet1.classic_address} is:")
print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"]) print((client.request(AccountLines(account=wallet1.classic_address))).result["lines"])
print("Balance of ${wallet2.classic_address} is:")
print((client.request(AccountLines(account=wallet2.classic_address))).result["lines"]) print((client.request(AccountLines(account=wallet2.classic_address))).result["lines"])

View File

@@ -1,3 +1,7 @@
/*
* Extract best paths from RipplePathFind to trade with and send a payment using paths.
* Reference: https://xrpl.org/paths.html
*/
import { Client, Payment, RipplePathFindResponse } from 'xrpl' import { Client, Payment, RipplePathFindResponse } from 'xrpl'
const client = new Client('wss://s.altnet.rippletest.net:51233') const client = new Client('wss://s.altnet.rippletest.net:51233')
@@ -26,10 +30,10 @@ async function createTxWithPaths(): Promise<void> {
} }
const resp: RipplePathFindResponse = await client.request(request) const resp: RipplePathFindResponse = await client.request(request)
console.log(resp) console.log("Ripple Path Find response: ", resp)
const paths = resp.result.alternatives[0].paths_computed const paths = resp.result.alternatives[0].paths_computed
console.log(paths) console.log("Computed paths: ", paths)
const tx: Payment = { const tx: Payment = {
TransactionType: 'Payment', TransactionType: 'Payment',

View File

@@ -49,10 +49,9 @@ async function sendReliableTx(): Promise<void> {
const { wallet: wallet2 } = await client.fundWallet(); const { wallet: wallet2 } = await client.fundWallet();
console.log("Balances of wallets before Payment tx"); console.log("Balances of wallets before Payment tx");
console.log(
await client.getXrpBalance(wallet1.classicAddress), console.log(`Balance of ${wallet1.classicAddress} is ${await client.getXrpBalance(wallet1.classicAddress)}XRP`);
await client.getXrpBalance(wallet2.classicAddress) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getXrpBalance(wallet2.classicAddress)}XRP`);
);
// create a Payment tx and submit and wait for tx to be validated // create a Payment tx and submit and wait for tx to be validated
const payment: Payment = { const payment: Payment = {
@@ -62,6 +61,7 @@ async function sendReliableTx(): Promise<void> {
Destination: wallet2.classicAddress, Destination: wallet2.classicAddress,
}; };
console.log("Submitting a Payment transaction...")
const paymentResponse = await client.submitAndWait(payment, { const paymentResponse = await client.submitAndWait(payment, {
wallet: wallet1, wallet: wallet1,
}); });
@@ -74,10 +74,8 @@ async function sendReliableTx(): Promise<void> {
console.log("Validated:", txResponse.result.validated); console.log("Validated:", txResponse.result.validated);
console.log("Balances of wallets after Payment tx:"); console.log("Balances of wallets after Payment tx:");
console.log( console.log(`Balance of ${wallet1.classicAddress} is ${await client.getXrpBalance(wallet1.classicAddress)}XRP`);
await client.getXrpBalance(wallet1.classicAddress), console.log(`Balance of ${wallet2.classicAddress} is ${await client.getXrpBalance(wallet2.classicAddress)}XRP`);
await client.getXrpBalance(wallet2.classicAddress)
);
await client.disconnect(); await client.disconnect();
} }

View File

@@ -1,11 +1,11 @@
/*
* Use `SetRegularKey` to assign a key pair to a wallet and make a payment signed using the regular key wallet.
* Reference: https://xrpl.org/setregularkey.html
*/
import { Client, Payment, SetRegularKey } from 'xrpl' import { Client, Payment, SetRegularKey } from 'xrpl'
const client = new Client('wss://s.altnet.rippletest.net:51233') const client = new Client('wss://s.altnet.rippletest.net:51233')
/*
* The snippet walks us through an example usage of RegularKey.
* Later,
*/
async function setRegularKey(): Promise<void> { async function setRegularKey(): Promise<void> {
await client.connect() await client.connect()
const { wallet: wallet1 } = await client.fundWallet() const { wallet: wallet1 } = await client.fundWallet()
@@ -13,8 +13,8 @@ async function setRegularKey(): Promise<void> {
const { wallet: regularKeyWallet } = await client.fundWallet() const { wallet: regularKeyWallet } = await client.fundWallet()
console.log('Balances before payment') console.log('Balances before payment')
console.log(await client.getXrpBalance(wallet1.classicAddress)) console.log(`Balance of ${wallet1.classicAddress} is ${await client.getXrpBalance(wallet1.classicAddress)}XRP`)
console.log(await client.getXrpBalance(wallet2.classicAddress)) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getXrpBalance(wallet2.classicAddress)}XRP`)
// assigns key-pair(regularKeyWallet) to wallet1 using `SetRegularKey`. // assigns key-pair(regularKeyWallet) to wallet1 using `SetRegularKey`.
const tx: SetRegularKey = { const tx: SetRegularKey = {
@@ -22,6 +22,8 @@ async function setRegularKey(): Promise<void> {
Account: wallet1.classicAddress, Account: wallet1.classicAddress,
RegularKey: regularKeyWallet.classicAddress, RegularKey: regularKeyWallet.classicAddress,
} }
console.log('Submitting a SetRegularKey transaction...')
const response = await client.submitAndWait(tx, { const response = await client.submitAndWait(tx, {
wallet: wallet1, wallet: wallet1,
}) })
@@ -46,8 +48,8 @@ async function setRegularKey(): Promise<void> {
console.log('Response for tx signed using Regular Key:') console.log('Response for tx signed using Regular Key:')
console.log(submitTx) console.log(submitTx)
console.log('Balances after payment:') console.log('Balances after payment:')
console.log(await client.getXrpBalance(wallet1.classicAddress)) console.log(`Balance of ${wallet1.classicAddress} is ${await client.getXrpBalance(wallet1.classicAddress)}XRP`)
console.log(await client.getXrpBalance(wallet2.classicAddress)) console.log(`Balance of ${wallet2.classicAddress} is ${await client.getXrpBalance(wallet2.classicAddress)}XRP`)
await client.disconnect() await client.disconnect()
} }