xrpl.js: working send xrp sample code, etc.

This commit is contained in:
mDuo13
2021-09-27 15:31:41 -07:00
parent 8ef2c87a21
commit feaef69da7
5 changed files with 65 additions and 49 deletions

View File

@@ -79,19 +79,18 @@ $("#get-tx-button").click( async function(event) {
try { try {
const tx = await api.request({ const tx = await api.request({
command: "tx", command: "tx",
transaction: txID, transaction: txID,
min_ledger: earliestLedgerVersion, min_ledger: earliestLedgerVersion,
max_ledger: lastLedgerSequence max_ledger: lastLedgerSequence
}) })
block.find(".output-area").html( block.find(".output-area").html(
"<div><strong>Transaction result:</strong> " + `<div><strong>Transaction result code:</strong>
tx.result + "</div>" + ${tx.result.meta.TransactionResult} (${tx.result.validated ? "validated": "pending"})</div>
// TODO: restore some "balance changes" functionality based on what xrpl.js 2.0 offers. <div><strong>XRP Delivered:</strong>
//"<div><strong>Balance changes:</strong> <pre><code>" + ${xrpl.dropsToXrp(tx.meta.delivered_amount)} XRP
//pretty_print(tx.outcome.balanceChanges) + </div>`
"</pre></code></div>"
) )
complete_step("Check") complete_step("Check")

View File

@@ -195,7 +195,7 @@ const set_up_tx_sender = async function() {
$("#pp_progress .progress-bar").addClass("progress-bar-animated") $("#pp_progress .progress-bar").addClass("progress-bar-animated")
// 1. Get a funded address to use as issuer // 1. Get a funded address to use as issuer
try { try {
pp_issuer_wallet = await api.getFaucetWallet() pp_issuer_wallet = await api.generateFaucetWallet()
} catch(error) { } catch(error) {
console.log("Error getting issuer address for partial payments:", error) console.log("Error getting issuer address for partial payments:", error)
return return

File diff suppressed because one or more lines are too long

View File

@@ -3,8 +3,10 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>Code Sample - Send XRP</title> <title>Code Sample - Send XRP</title>
<script src="https://unpkg.com/ripple-lib@1.10.0/build/ripple-latest-min.js"></script> <!-- TODO: re-add CDN version instead of local version
<script type="application/javascript" src="../submit-and-verify/submit-and-verify.js"></script> <script src="https://unpkg.com/ripple-lib@1.10.0/build/ripple-latest-min.js"></script> -->
<script type="application/javascript" src="../../../assets/js/xrpl-2.0b0.min.js"></script>
<script type="application/javascript" src="../submit-and-verify/submit-and-verify2.js"></script>
<script type="application/javascript" src="send-xrp.js"></script> <script type="application/javascript" src="send-xrp.js"></script>
</head> </head>
<body>Open your browser's console (F12) to see the logs.</body> <body>Open your browser's console (F12) to see the logs.</body>

View File

@@ -1,17 +1,14 @@
// Example credentials // Example credentials
let address = "rMCcNuTcajgw7YTgBy1sys3b89QqjUrMpH" const wallet = xrpl.Wallet.fromSeed("sn3nxiW7v8KXzPzAqzyHXbSSKNuN9")
let secret = "sn3nxiW7v8KXzPzAqzyHXbSSKNuN9"
// Connect --------------------------------------------------------------------- // Connect ---------------------------------------------------------------------
// ripple = require('ripple-lib') // For Node.js. In browsers, use <script>. // const xrpl = require('xrpl') // For Node.js. In browsers, use <script>.
api = new ripple.RippleAPI({server: 'wss://s.altnet.rippletest.net:51233'}) const api = new xrpl.Client('wss://s.altnet.rippletest.net:51233')
api.connect() api.connect()
api.on('connected', async () => { api.on('connected', async () => {
// Get credentials from the Testnet Faucet ----------------------------------- // Get credentials from the Testnet Faucet -----------------------------------
const data = await api.generateFaucetWallet() const wallet = await api.generateFaucetWallet()
address = data.account.address
secret = data.account.secret
console.log("Waiting until we have a validated starting sequence number...") console.log("Waiting until we have a validated starting sequence number...")
// If you go too soon, the funding transaction might slip back a ledger and // If you go too soon, the funding transaction might slip back a ledger and
@@ -20,7 +17,11 @@ api.on('connected', async () => {
// the faucet. // the faucet.
while (true) { while (true) {
try { try {
await api.request("account_info", {account: address, ledger_index: "validated"}) await api.request({
command: "account_info",
account: wallet.classicAddress,
ledger_index: "validated"
})
break break
} catch(e) { } catch(e) {
await new Promise(resolve => setTimeout(resolve, 1000)) await new Promise(resolve => setTimeout(resolve, 1000))
@@ -28,47 +29,49 @@ api.on('connected', async () => {
} }
// Prepare transaction ------------------------------------------------------- // Prepare transaction -------------------------------------------------------
const preparedTx = await api.prepareTransaction({ const prepared = await api.autofill({
"TransactionType": "Payment", "TransactionType": "Payment",
"Account": address, "Account": wallet.classicAddress,
"Amount": api.xrpToDrops("22"), // Same as "Amount": "22000000" "Amount": xrpl.xrpToDrops("22"),
"Destination": "rUCzEr6jrEyMpjhs4wSdQdz4g8Y382NxfM" "Destination": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"
}, {
// Expire this transaction if it doesn't execute within ~5 minutes:
"maxLedgerVersionOffset": 75
}) })
const maxLedgerVersion = preparedTx.instructions.maxLedgerVersion const max_ledger = prepared.LastLedgerSequence
console.log("Prepared transaction instructions:", preparedTx.txJSON) console.log("Prepared transaction instructions:", prepared)
console.log("Transaction cost:", preparedTx.instructions.fee, "XRP") console.log("Transaction cost:", xrpl.dropsToXrp(prepared.Fee), "XRP")
console.log("Transaction expires after ledger:", maxLedgerVersion) console.log("Transaction expires after ledger:", max_ledger)
// Sign prepared instructions ------------------------------------------------ // Sign prepared instructions ------------------------------------------------
const signed = api.sign(preparedTx.txJSON, secret) const tx_blob = wallet.signTransaction(prepared)
const txID = signed.id const txID = xrpl.computeSignedTransactionHash(tx_blob)
const tx_blob = signed.signedTransaction
console.log("Identifying hash:", txID) console.log("Identifying hash:", txID)
console.log("Signed blob:", tx_blob) console.log("Signed blob:", tx_blob)
// Submit signed blob -------------------------------------------------------- // Submit signed blob --------------------------------------------------------
// The earliest ledger a transaction could appear in is the first ledger // The earliest ledger a transaction could appear in is the first ledger
// after the one that's already validated at the time it's *first* submitted. // after the one that's already validated at the time it's *first* submitted.
const earliestLedgerVersion = (await api.getLedgerVersion()) + 1 const min_ledger = (await api.getLedgerIndex()) + 1
const result = await api.submit(tx_blob) const result = await api.request({
console.log("Tentative result code:", result.resultCode) "command": "submit",
console.log("Tentative result message:", result.resultMessage) "tx_blob": tx_blob
})
console.log("Tentative result code:", result.result.engine_result)
console.log("Tentative result message:", result.result.engine_result_message)
// Wait for validation ------------------------------------------------------- // Wait for validation -------------------------------------------------------
let has_final_status = false let has_final_status = false
api.request("subscribe", {accounts: [address]}) api.request({
"command": "subscribe",
"accounts": [wallet.classicAddress]
})
api.connection.on("transaction", (event) => { api.connection.on("transaction", (event) => {
if (event.transaction.hash == txID) { if (event.transaction.hash == txID) {
console.log("Transaction has executed!", event) console.log("Transaction has executed!", event)
has_final_status = true has_final_status = true
} }
}) })
api.on('ledger', ledger => { api.on('ledgerClosed', ledger => {
if (ledger.ledgerVersion > maxLedgerVersion && !has_final_status) { if (ledger.ledger_index > max_ledger && !has_final_status) {
console.log("Ledger version", ledger.ledgerVersion, "was validated.") console.log("Ledger version", ledger.ledger_index, "was validated.")
console.log("If the transaction hasn't succeeded by now, it's expired") console.log("If the transaction hasn't succeeded by now, it's expired")
has_final_status = true has_final_status = true
} }
@@ -82,10 +85,22 @@ api.on('connected', async () => {
// Check transaction results ------------------------------------------------- // Check transaction results -------------------------------------------------
try { try {
tx = await api.getTransaction(txID, { const tx = await api.request({
minLedgerVersion: earliestLedgerVersion}) command: "tx",
console.log("Transaction result:", tx.outcome.result) transaction: txID,
console.log("Balance changes:", JSON.stringify(tx.outcome.balanceChanges)) min_ledger: min_ledger,
max_ledger: max_ledger
})
if (tx.result.validated) {
console.log("This result is validated by consensus and final.")
} else {
console.log("This result is pending.")
}
console.log("Transaction result:", tx.result.meta.TransactionResult)
if (typeof tx.result.meta.delivered_amount === "string" &&
typeof tx.result.meta.delivered_amount !== "unavailable")
console.log("Delivered:", xrpl.dropsToXrp(tx.result.meta.delivered_amount), "XRP")
} catch(error) { } catch(error) {
console.log("Couldn't get transaction outcome:", error) console.log("Couldn't get transaction outcome:", error)
} }