- Use Devnet for live examples - Move code to a dedicated JS file instead of having it all inline - Improve transaction submission logic
16 KiB
html, funnel, doc_type, category, blurb, filters
| html | funnel | doc_type | category | blurb | filters | |
|---|---|---|---|---|---|---|
| use-tickets.html | Build | Tutorials | Manage Account Settings | Use Tickets to send a transaction outside of normal Sequence order. |
|
Use Tickets
(Requires the [TicketBatch amendment][] :not_enabled:)
Tickets provide a way to send transactions out of the normal order. This tutorial walks through the steps of creating a Ticket, then using it to send another transaction.
Prerequisites
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script> <script type="application/javascript" src="{{target.ripple_lib_url}}"></script> <script type="application/javascript" src="assets/js/interactive-tutorial.js"></script> <script type="application/javascript" src="assets/js/tutorials/use-tickets.js"></script>This page provides JavaScript examples that use the ripple-lib (RippleAPI) library. The RippleAPI Beginners Guide describes how to get started using RippleAPI to access XRP Ledger data from JavaScript.
Since JavaScript works in the web browser, you can read along and use the interactive steps without any setup.
Tickets must be enabled. At this time, the [TicketBatch amendment][] :not_enabled: is only available on Devnet.
Steps
{% set n = cycler(* range(1,99)) %}
{{n.next() }}. Get Credentials
To interact with the XRP Ledger, you need a address and secret key, and some XRP. You can get all of these on the Devnet using the following interface:
{% set faucet_url = "https://faucet.devnet.rippletest.net/accounts" %} {% include '_snippets/generate-step.md' %}
When you're building actual production-ready software, you'll instead use an existing account, and manage your keys using a secure signing configuration.
{{n.next()}}. Connect to Network
You must be connected to the network to submit transactions to it.
The following code sample instantiates a new RippleAPI instance and connects to one of the public XRP Devnet servers that Ripple runs:
ripple = require('ripple-lib')
async function main() {
api = new ripple.RippleAPI({server: 'wss://s.devnet.rippletest.net:51233'})
await api.connect()
// Code in the following examples continues here...
}
main()
Note: The code samples in this tutorial use JavaScript's async/await pattern. Since await needs to be used from within an async function, the remaining code samples are written to continue inside the main() function started here. You can also use Promise methods .then() and .catch() instead of async/await if you prefer.
For this tutorial, you can connect directly from your browser by pressing the following button:
{{ start_step("Connect") }} Connect to Devnet
{{ end_step() }}{{n.next()}}. Check Sequence Number
If you already have at least one Ticket available in the ledger, you can skip this step. Otherwise, you need to get ready to create some Tickets for your other transactions to use.
Before you create any Tickets, you should check what [Sequence Number][] your account is at. You want the current Sequence number for the next step, and the Ticket Sequence numbers it sets aside start from this number.
async function get_sequence() {
const account_info = await api.request("account_info", {
"account": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"
})
console.log("Current sequence:", account_info.account_data.Sequence)
return account_info.account_data.Sequence
}
let current_sequence = get_sequence()
{{ start_step("Check Sequence") }} Check Sequence Number
{{ end_step() }}{{n.next()}}. Prepare and Sign TicketCreate
If you already have at least one Ticket available in the ledger, you can skip this step. Otherwise, you need to prepare the transaction to create some Tickets.
Construct a [TicketCreate transaction][] the sequence number you determined in the previous step. Use the TicketCount field to set how many Tickets to create. For example, this example prepares a transaction that would make 10 Tickets:
let prepared = await api.prepareTransaction({
"TransactionType": "TicketCreate",
"Account": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
"TicketCount": 10,
"Sequence": current_sequence
})
console.log("Prepared transaction:", prepared.txJSON)
let max_ledger = prepared.instructions.maxLedgerVersion
let signed = api.sign(prepared.txJSON, "s████████████████████████████")
console.log("Transaction hash:", signed.id)
let tx_blob = signed.signedTransaction
Take note of the transaction's hash and LastLedgerSequence value so you can be sure whether or not it got validated later.
{{ start_step("Prepare & Sign") }} Prepare & Sign
{{ end_step() }}{{n.next()}}. Submit TicketCreate
If you already have at least one Ticket available in the ledger, you can skip this step. Otherwise, you need to send a transaction to create some Tickets.
Submit the signed transaction blob that you created in the previous step. Take note of the latest validated ledger index at the time of submission, so you can set a lower bound on what ledger versions the transaction could be validated in. For example:
let prelim_result = await api.request("submit", {"tx_blob": tx_blob})
console.log("Preliminary result:", prelim_result)
const min_ledger = prelim_result.validated_ledger_index
Warning: Be sure that you DO NOT UPDATE the min_ledger value. It is safe to submit a signed transaction blob multiple times (the transaction can only execute at most once), but when you look up the status of the transaction you should use the earliest possible ledger index the transaction could be in, not the validated ledger index at the time of the most recent submission. Using the wrong minimum ledger value could cause you to incorrectly conclude that the transaction did not execute. For best practices, see Reliable Transaction Submission.
{{ start_step("Submit") }} Submit
{{ end_step() }}{{n.next()}}. Wait for Validation
Most transactions are accepted into the next ledger version after they're submitted, which means it may take 4-7 seconds for a transaction's outcome to be final. If the XRP Ledger is busy or poor network connectivity delays a transaction from being relayed throughout the network, a transaction may take longer to be confirmed. (For information on how to set an expiration for transactions, see Reliable Transaction Submission.)
You use the ledger event type in RippleAPI to trigger your code to run whenever there is a new validated ledger version. For example:
// signed.id is the hash we're waiting for
// min_ledger is the validated ledger index at time of first submission
// max_ledger is the transaction's LastLedgerSequence value
let tx_status = ""
api.on('ledger', async (ledger) => {
console.log("Ledger version", ledger.ledgerVersion, "was validated.")
if (!tx_status) {
try {
tx_result = await api.request("tx", {
"transaction": signed.id,
"min_ledger": min_ledger,
"max_ledger": max_ledger
})
if (tx_result.validated) {
console.log("Got validated result:", tx_result.meta.TransactionResult)
tx_status = "validated"
} else {
// Transaction found, but not yet validated. No change.
}
} catch(e) {
if (e.data.error == "txnNotFound") {
if (e.data.searched_all) {
console.log(`Tx not found in ledgers ${min_ledger}-${max_ledger}`)
tx_status = "rejected"
// This result is final if min_ledger and max_ledger are correct
} else {
if (max_ledger > ledger.ledgerVersion) {
// Transaction may yet be confirmed. Keep waiting.
} else {
console.log("Can't get final result. Check a full history server.")
tx_result = "unknown - check full history"
}
}
} else {
// Unknown error; pass it back up
throw e
}
}
}
})
{{ start_step("Wait") }}
| Transaction Hash: | |
|---|---|
| Latest Validated Ledger Version: | (Not connected) |
| Ledger Version at Time of Submission: | (Not submitted) |
LastLedgerSequence: |
(Not prepared) |
(Optional) Intermission
The power of Tickets is that you can send other transactions during this time, and generally carry on with your account's normal business during this time. If you are planning on using a given Ticket, then as long as you don't use that Ticket for something else, you're free to continue using your account as normal. When you want to send the transaction using a Ticket, you can do that in parallel with other transactions using regular sequence numbers or different Tickets, and submit any of them in any order when you're ready.
Tip: You can come back here to send Sequenced transactions between or during any of the following steps, without interfering with the success of your Ticketed transaction.
{{ start_step("Intermission") }} Payment EscrowCreate AccountSet
{{ end_step() }}{{n.next()}}. Check Available Tickets
When you want to send a Ticketed transaction, you need to know what Ticket Sequence number to use for it. If you've been keeping careful track of your account, you already know which Tickets you have, but if you're not sure, you can use the [account_objects method][] (or getAccountObjects()) to look up your available tickets. For example:
let response = await api.request("account_objects", {
"account": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
"type": "ticket"
})
console.log("Available Tickets:", response.account_objects)
let use_ticket = response.account_objects[0].TicketSequence
{{ start_step("Check Tickets") }} Submit
{{ end_step() }}{{n.next()}}. Prepare Ticketed Transaction
Now that you have a Ticket available, you can prepare a transaction that uses it.
This can be any type of transaction you like. The following example uses a no-op [AccountSet transaction][] since that doesn't require any other setup in the ledger. Set the Sequence field to 0 and include a TicketSequence field with the Ticket Sequence number of one of your available Tickets.
let prepared_t = await api.prepareTransaction({
"TransactionType": "AccountSet",
"Account": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe",
"TicketSequence": use_ticket,
"Sequence": 0
}, {
// Adjust instructions to allow more time before submitting the transaction
maxLedgerVersionOffset: 20
//maxLedgerVersion: null // or, let the transaction remain valid indefinitely
})
console.log("Prepared JSON:", prepared_t.txJSON)
let signed_t = api.sign(prepared_t.txJSON,
"s████████████████████████████")
console.log("Transaction hash:", signed_t.id)
let tx_blob_t = signed.signedTransaction
console.log("Signed transaction blob:", tx_blob_t)
Tip: If you don't plan to submit the TicketCreate transaction right away, you should explicitly set the instructions' maxLedgerVersionOffset to a larger number of ledgers. To create a transaction that could remain valid indefinitely, set the maxLedgerVersion to null.
{{ start_step("Prepare Ticketed Tx") }}
Select a Ticket:
{{n.next()}}. Submit Ticketed Transaction
Submit the signed transaction blob that you created in the previous step. For example:
let prelim_result_t = await api.request("submit", {"tx_blob": tx_blob_t})
console.log("Preliminary result:", prelim_result_t)
{{ start_step("Submit Ticketed Tx") }} Submit
{{ end_step() }}{{n.next()}}. Wait for Validation
Ticketed transactions go through the consensus process the same way that Sequenced transactions do.
{{ start_step("Wait Again") }}
| Latest Validated Ledger Version: | (Not connected) |
|---|---|
| Ledger Version at Time of Submission: | (Not submitted) |
Ticketed Transaction LastLedgerSequence: |
(Not prepared) |
See Also
- Concepts:
- Tutorials:
- References:
- [account_objects method][]
- [sign_for method][]
- [submit_multisigned method][]
- [TicketCreate transaction][]
- Transaction Common Fields
{% include '_snippets/rippled-api-links.md' %} {% include '_snippets/tx-type-links.md' %} {% include '_snippets/rippled_versions.md' %}
