Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 0 additions & 69 deletions _code-samples/escrow/js/create-escrow.js

This file was deleted.

7 changes: 4 additions & 3 deletions _code-samples/escrow/js/package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
{
"name": "escrow-examples",
"version": "0.0.3",
"version": "2.0.0",
"license": "MIT",
"dependencies": {
"five-bells-condition": "*",
"xrpl": "^4.0.0"
}
"xrpl": "^4.4.0"
},
"type": "module"
}
89 changes: 89 additions & 0 deletions _code-samples/escrow/js/send-conditional-escrow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
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.address

// 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)

// 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())

// 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}.`)
process.exit(1)
}

// Save the sequence number so you can identify the escrow later.
const escrowSeq = response.result.tx_json.Sequence
console.log(`Escrow sequence is ${escrowSeq}.`)


// 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()
104 changes: 104 additions & 0 deletions _code-samples/escrow/js/send-timed-escrow.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import xrpl from 'xrpl'

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.address

// Set the escrow finish time -----------------------------------------------
const delay = 30 // Seconds in the future when the escrow should mature
const finishAfter = new Date() // Current time
finishAfter.setSeconds(finishAfter.getSeconds() + delay)
console.log('This escrow will finish after:', finishAfter)
// Convert finishAfter to seconds since the Ripple Epoch:
const finishAfterRippleTime = xrpl.isoTimeToRippleTime(finishAfter.toISOString())

// Send EscrowCreate transaction --------------------------------------------
const escrowCreate = {
TransactionType: 'EscrowCreate',
Account: wallet.address,
Destination: destination_address,
Amount: '123456', // drops of XRP
FinishAfter: finishAfterRippleTime
}
xrpl.validate(escrowCreate)

console.log('Signing and submitting the transaction:',
JSON.stringify(escrowCreate, null, 2))
const response = await client.submitAndWait(escrowCreate, {
wallet,
autofill: true
})
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}.`)
process.exit(1)
}

// Save the sequence number so you can identify the escrow later.
const escrowSeq = response.result.tx_json.Sequence
console.log(`Escrow sequence is ${escrowSeq}.`)

// Wait for the escrow to be finishable -------------------------------------
console.log(`Waiting ${delay} seconds for the escrow to mature...`)
await sleep(delay)

/* Sleep function that can be used with await */
function sleep (delayInSeconds) {
const delayInMs = delayInSeconds * 1000
return new Promise((resolve) => setTimeout(resolve, delayInMs))
}

// Check if escrow can be finished -------------------------------------------
let escrowReady = false
while (!escrowReady) {
// Check the close time of the latest validated ledger.
// Close times are rounded by about 10 seconds, so the exact time the escrow
// is ready to finish may vary by +/- 10 seconds.
const validatedLedger = await client.request({
command: 'ledger',
ledger_index: 'validated'
})
const ledgerCloseTime = validatedLedger.result.ledger.close_time
console.log('Latest validated ledger closed at',
xrpl.rippleTimeToISOTime(ledgerCloseTime))
if (ledgerCloseTime > finishAfterRippleTime) {
escrowReady = true
console.log('Escrow is mature.')
} else {
let timeDifference = finishAfterRippleTime - ledgerCloseTime
if (timeDifference === 0) { timeDifference = 1 }
console.log(`Waiting another ${timeDifference} second(s).`)
await sleep(timeDifference)
}
}

// Send EscrowFinish transaction --------------------------------------------
const escrowFinish = {
TransactionType: 'EscrowFinish',
Account: wallet.address,
Owner: wallet.address,
OfferSequence: escrowSeq
}
xrpl.validate(escrowFinish)

console.log('Signing and submitting the transaction:',
JSON.stringify(escrowFinish, null, 2))
const response2 = await client.submitAndWait(escrowFinish, {
wallet,
autofill: true
})
console.log(JSON.stringify(response2.result, null, 2))
if (response2.result.meta.TransactionResult === 'tesSUCCESS') {
console.log('Escrow finished successfully.')
}

client.disconnect()
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,14 @@ Response:
{% code-snippet file="/_api-examples/escrow/websocket/submit-response-escrowcreate-condition.json" language="json" /%}
{% /tab %}

{% tab label="Javascript" %}
{% code-snippet file="/_code-samples/escrow/js/create-escrow.js" language="js" from="// Prepare EscrowCreate" before="await client.disconnect" /%}
{% /tab %}

{% tab label="Python" %}
{% code-snippet file="/_code-samples/escrow/py/create_escrow.py" language="py" from="# Build escrow create" /%}
{% /tab %}

{% /tabs %}

<!-- TODO: re-add a working JS example. Removed the old one due to the sample code being refactored -->

## 4. Wait for validation

{% raw-partial file="/docs/_snippets/wait-for-validation.md" /%}
Expand Down
Loading