Files
xrpl-dev-portal/content/_code-samples/monitor-payments-websocket/js/read-amount-received.js

77 lines
3.1 KiB
JavaScript

function CountXRPDifference(affected_nodes, address) {
// Helper to find an account in an AffectedNodes array and see how much
// its balance changed, if at all. Fortunately, each account appears at most
// once in the AffectedNodes array, so we can return as soon as we find it.
// Note: this reports the net balance change. If the address is the sender,
// the transaction cost is deducted and combined with XRP sent/received
for (let i=0; i<affected_nodes.length; i++) {
if ((affected_nodes[i].hasOwnProperty("ModifiedNode"))) {
// modifies an existing ledger entry
let ledger_entry = affected_nodes[i].ModifiedNode
if (ledger_entry.LedgerEntryType === "AccountRoot" &&
ledger_entry.FinalFields.Account === address) {
if (!ledger_entry.PreviousFields.hasOwnProperty("Balance")) {
console.log("XRP balance did not change.")
}
// Balance is in PreviousFields, so it changed. Time for
// high-precision math!
const old_balance = new Big(ledger_entry.PreviousFields.Balance)
const new_balance = new Big(ledger_entry.FinalFields.Balance)
const diff_in_drops = new_balance.minus(old_balance)
const xrp_amount = diff_in_drops.div(1e6)
if (xrp_amount.gte(0)) {
console.log("Received " + xrp_amount.toString() + " XRP.")
return
} else {
console.log("Spent " + xrp_amount.abs().toString() + " XRP.")
return
}
}
} else if ((affected_nodes[i].hasOwnProperty("CreatedNode"))) {
// created a ledger entry. maybe the account just got funded?
let ledger_entry = affected_nodes[i].CreatedNode
if (ledger_entry.LedgerEntryType === "AccountRoot" &&
ledger_entry.NewFields.Account === address) {
const balance_drops = new Big(ledger_entry.NewFields.Balance)
const xrp_amount = balance_drops.div(1e6)
console.log("Received " + xrp_amount.toString() + " XRP (account funded).")
return
}
} // accounts cannot be deleted at this time, so we ignore DeletedNode
}
console.log("Did not find address in affected nodes.")
return
}
function CountXRPReceived(tx, address) {
if (tx.meta.TransactionResult !== "tesSUCCESS") {
console.log("Transaction failed.")
return
}
if (tx.transaction.TransactionType === "Payment") {
if (tx.transaction.Destination !== address) {
console.log("Not the destination of this payment.")
return
}
if (typeof tx.meta.delivered_amount === "string") {
const amount_in_drops = new Big(tx.meta.delivered_amount)
const xrp_amount = amount_in_drops.div(1e6)
console.log("Received " + xrp_amount.toString() + " XRP.")
return
} else {
console.log("Received non-XRP currency.")
return
}
} else if (["PaymentChannelClaim", "PaymentChannelFund", "OfferCreate",
"CheckCash", "EscrowFinish"].includes(
tx.transaction.TransactionType)) {
CountXRPDifference(tx.meta.AffectedNodes, address)
} else {
console.log("Not a currency-delivering transaction type (" +
tx.transaction.TransactionType + ").")
}
}