This tutorial demonstrates how to send an escrow that can be released when a specific crypto-condition is fulfilled. Essentially, a crypto-condition is like a random password that unlocks the escrow to be sent to its indicated destination. You can use this as part of an app that reveals the fulfillment only when specific actions take place.
This tutorial shows how to escrow XRP. If the TokenEscrow amendment is enabled, you can also escrow tokens.
By following this tutorial, you should learn how to:
- Convert a timestamp into the XRP Ledger's native format.
- Create a crypto-condition and fulfillment in the format needed for the XRP Ledger.
- Create and finish an escrow.
To complete this tutorial, you should:
- Have a basic understanding of the XRP Ledger.
- Have an XRP Ledger client library, such as xrpl.js, installed.
You can find the complete source code for this tutorial's examples in the code samples section of this website's repository.
From the code sample folder, use npm to install dependencies:
npm iTo get started, import the client library and instantiate an API client. For this tutorial, you also need one account, which you can get from the faucet. You also need the address of another account to send the escrow to. You can fund a second account using the faucet, or use the address of an existing account like the faucet.
import xrpl from 'xrpl'
import { PreimageSha256 } from 'five-bells-condition'
import { randomBytes } from 'crypto'
const client = new xrpl.Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
console.log('Funding new wallet from faucet...')
const { wallet } = await client.fundWallet()
// const destination_address = 'rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe' // Testnet faucet
// Alternative: Get another account to send the escrow to. Use this if you get
// a tecDIR_FULL error trying to create escrows to the Testnet faucet.
const destination_address = (await client.fundWallet()).wallet.addressConditional escrows require a fulfillment and its corresponding condition in the format of a PREIMAGE-SHA-256 crypto-condition, represented as hexadecimal. To calculate these in the correct format, use a crypto-conditions library. Generally, you want to generate the fulfillment using at least 32 random bytes from a cryptographically secure source of randomness.
// Create the crypto-condition for release ----------------------------------
const preimage = randomBytes(32)
const fulfillment = new PreimageSha256()
fulfillment.setPreimage(preimage)
const fulfillmentHex = fulfillment.serializeBinary().toString('hex').toUpperCase()
const conditionHex = fulfillment.getConditionBinary().toString('hex').toUpperCase()
console.log('Condition:', conditionHex)
console.log('Fulfillment:', fulfillmentHex)Conditional escrows also need an expiration time, so that the escrow can be canceled if the correct fulfillment isn't provided by the scheduled time. This timestamp must be formatted as seconds since the Ripple Epoch. The sample code calculates an expiration time 30 seconds after the current time.
// Set the escrow expiration ------------------------------------------------
const cancelDelay = 300 // Seconds in the future when the escrow should expire
const cancelAfter = new Date() // Current time
cancelAfter.setSeconds(cancelAfter.getSeconds() + cancelDelay)
console.log('This escrow will expire after:', cancelAfter)
// Convert cancelAfter to seconds since the Ripple Epoch:
const cancelAfterRippleTime = xrpl.isoTimeToRippleTime(cancelAfter.toISOString())To send the escrow, construct an EscrowCreate transaction and then submit it to the network. The fields of this transaction define the properties of the escrow. The sample code uses hard-coded values to send 0.123456 XRP back to the Testnet faucet:
// Send EscrowCreate transaction --------------------------------------------
const escrowCreate = {
TransactionType: 'EscrowCreate',
Account: wallet.address,
Destination: destination_address,
Amount: '123456', // drops of XRP
Condition: conditionHex,
CancelAfter: cancelAfterRippleTime
}
xrpl.validate(escrowCreate)
console.log('Signing and submitting the transaction:',
JSON.stringify(escrowCreate, null, 2))
const response = await client.submitAndWait(escrowCreate, {
wallet,
autofill: true // Note: fee is higher based on condition size in bytes
})
// Check result of submitting -----------------------------------------------
console.log(JSON.stringify(response.result, null, 2))
const escrowCreateResultCode = response.result.meta.TransactionResult
if (escrowCreateResultCode === 'tesSUCCESS') {
console.log('Escrow created successfully.')
} else {
console.error(`EscrowCreate failed with code ${escrowCreateResultCode}.`)
client.disconnect()
process.exit(1)
}Anyone with the correct fulfillment can immediately finish a conditional escrow (unless it's a timed conditinal escrow with a FinishAfter time). To do this, construct an EscrowFinish transaction, using the sequence number that you recorded when you created the escrow, and the matching condition and fulfillment for the escrow, then submit it to the network.
Fee field manually.// Send EscrowFinish transaction --------------------------------------------
const escrowFinish = {
TransactionType: 'EscrowFinish',
Account: wallet.address,
Owner: wallet.address,
OfferSequence: escrowSeq,
Condition: conditionHex,
Fulfillment: fulfillmentHex
}
xrpl.validate(escrowFinish)
console.log('Signing and submitting the transaction:',
JSON.stringify(escrowFinish, null, 2))
const response2 = await client.submitAndWait(escrowFinish, {
wallet,
autofill: true // Note: fee is higher based on fulfillment size in bytes
})
console.log(JSON.stringify(response2.result, null, 2))
if (response2.result.meta.TransactionResult === 'tesSUCCESS') {
console.log('Escrow finished successfully.')
} else {
console.log(`Failed with result code ${response2.result.meta.TransactionResult}`)
}
client.disconnect()