Skip to content
Open
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
30 changes: 29 additions & 1 deletion e2e-tests/host_functions_test/runTest.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
const xrpl = require("xrpl")

async function test(testContext) {
const { deploy, sourceWallet, finish, finishEscrow } = testContext
const { deploy, submit, sourceWallet, finish, finishEscrow, expectResult } =
testContext

// Mint an NFT with distinctive fields so the WASM contract can assert typed getters.
const nftMint = {
TransactionType: "NFTokenMint",
Account: sourceWallet.address,
NFTokenTaxon: 12345,
TransferFee: 1000,
URI: xrpl.convertStringToHex("https://example.com/nft-metadata.json"),
Flags:
xrpl.NFTokenMintFlags.tfBurnable |
xrpl.NFTokenMintFlags.tfOnlyXRP |
xrpl.NFTokenMintFlags.tfTransferable,
}
const mintResponse = await submit(nftMint, sourceWallet)
expectResult(mintResponse, "tesSUCCESS", "NFTokenMint")
const nftId = mintResponse.result.meta.nftoken_id

// This escrow should always succeed. If it fails, something in rippled
// is broken.
const { sequence } = await deploy(sourceWallet, sourceWallet, finish)
await finishEscrow(testContext, sourceWallet, {
Owner: sourceWallet.address,
OfferSequence: sequence,
Memos: [
{
Memo: {
MemoType: xrpl.convertStringToHex("nft_id"),
MemoData: nftId,
},
},
],
})
}

Expand Down
178 changes: 153 additions & 25 deletions e2e-tests/host_functions_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,21 @@ use xrpl_common_stdlib::host::trace::{
use xrpl_common_stdlib::sfield;
use xrpl_common_stdlib::types::account_id::AccountID;
use xrpl_common_stdlib::types::amount::Amount;
use xrpl_common_stdlib::types::blob::StandardBlob;
use xrpl_common_stdlib::types::currency::Currency;
use xrpl_common_stdlib::types::iou_number::IOUNumber;
use xrpl_common_stdlib::types::mpt_id::MptId;
use xrpl_common_stdlib::types::nft::{NFT_ID_SIZE, NFToken, flags as nftoken_flags};
use xrpl_escrow_stdlib::current_tx::escrow_finish::EscrowFinish;

/// Values `runTest.js` puts on the minted NFToken so this contract can check the typed getters
/// against a real host, not just that they return *something*.
const EXPECTED_NFT_TAXON: u32 = 12345;
const EXPECTED_NFT_TRANSFER_FEE: u16 = 1000;
const EXPECTED_NFT_FLAGS: u16 =
nftoken_flags::BURNABLE | nftoken_flags::ONLY_XRP | nftoken_flags::TRANSFERABLE;
const EXPECTED_NFT_URI: &[u8] = b"https://example.com/nft-metadata.json";

#[unsafe(no_mangle)]
pub extern "C" fn escrow_finish() -> i32 {
trace("=== HOST FUNCTIONS TEST ===");
Expand Down Expand Up @@ -665,31 +675,10 @@ fn test_utility_functions() -> i32 {
trace_hex("Input data:", test_data);
trace_hex("SHA512 half hash:", &hash_output);

// Test 6.2: nft_uri() - NFT data retrieval
let escrow_finish = EscrowFinish;
let account_id = escrow_finish.get_account().unwrap();
let nft_id = [0u8; 32]; // Dummy NFT ID for testing
let mut nft_buffer = [0u8; 256];
let nft_result = unsafe {
host::nft_uri(
account_id.0.as_ptr(),
account_id.0.len(),
nft_id.as_ptr(),
nft_id.len(),
nft_buffer.as_mut_ptr(),
nft_buffer.len(),
)
};

if nft_result <= 0 {
trace_num(
"INFO: nft_uri failed (expected - no such NFT):",
nft_result as i64,
);
// This is expected - test account likely doesn't own the dummy NFT
} else {
trace_num("NFT data length:", nft_result as i64);
trace_hex("NFT data:", &nft_buffer[..nft_result as usize]);
// Test 6.2: NFToken field access via the typed stdlib API
match test_nft_fields() {
0 => (),
err => return err,
}

// Test 6.3: trace() - Debug logging with data
Expand Down Expand Up @@ -720,6 +709,145 @@ fn test_utility_functions() -> i32 {
0
}

/// Trace every NFToken field the stdlib exposes, using the NFT minted by `runTest.js`
/// (ID passed as EscrowFinish `Memos[0].MemoData`).
///
/// Error range: -621 to -632.
fn test_nft_fields() -> i32 {
trace("--- NFT fields (typed NFToken API) ---");

let escrow_finish = EscrowFinish;
let memo = match escrow_finish
Comment thread
TimothyBanks marked this conversation as resolved.
Resolved
.path()
.field(sfield::Memos)
.index(0)
.field(sfield::MemoData)
.get::<StandardBlob>()
{
host::Result::Ok(blob) => blob,
host::Result::Err(e) => {
trace_num("ERROR: reading NFT ID memo:", e.code() as i64);
return -621;
}
};

if memo.len() < NFT_ID_SIZE {
trace_num("ERROR: NFT ID memo too short:", memo.len() as i64);
return -621;
}

let mut nft_id_bytes = [0u8; NFT_ID_SIZE];
nft_id_bytes.copy_from_slice(&memo.as_slice()[..NFT_ID_SIZE]);
let nft = NFToken::new(nft_id_bytes);
trace_hex("NFT ID:", nft.as_bytes());

let flags = match nft.flags() {
host::Result::Ok(flags) => flags,
host::Result::Err(e) => {
trace_num("ERROR: nft.flags():", e.code() as i64);
return -622;
}
};
trace_num("NFT Flags:", flags.as_u16() as i64);
if flags.is_burnable() {
trace_num(" - BURNABLE:", 1);
}
if flags.is_only_xrp() {
trace_num(" - ONLY_XRP:", 1);
}
if flags.is_trust_line() {
trace_num(" - TRUST_LINE:", 1);
}
if flags.is_transferable() {
trace_num(" - TRANSFERABLE:", 1);
}

let transfer_fee = match nft.transfer_fee() {
host::Result::Ok(fee) => fee,
host::Result::Err(e) => {
trace_num("ERROR: nft.transfer_fee():", e.code() as i64);
return -623;
}
};
trace_num("NFT Transfer Fee:", transfer_fee as i64);

let issuer = match nft.issuer() {
host::Result::Ok(issuer) => issuer,
host::Result::Err(e) => {
trace_num("ERROR: nft.issuer():", e.code() as i64);
return -624;
}
};
trace_acct_buf("NFT Issuer:", &issuer.0);

let taxon = match nft.taxon() {
host::Result::Ok(taxon) => taxon,
host::Result::Err(e) => {
trace_num("ERROR: nft.taxon():", e.code() as i64);
return -625;
}
};
trace_num("NFT Taxon:", taxon as i64);

let token_sequence = match nft.token_sequence() {
host::Result::Ok(seq) => seq,
host::Result::Err(e) => {
trace_num("ERROR: nft.token_sequence():", e.code() as i64);
return -626;
}
};
trace_num("NFT Token Sequence:", token_sequence as i64);

let owner = escrow_finish.get_account().unwrap();
let uri = match nft.uri(&owner) {
host::Result::Ok(uri) => uri,
host::Result::Err(e) => {
trace_num("ERROR: nft.uri():", e.code() as i64);
return -627;
}
};
let uri_end = uri
.data
.iter()
.rposition(|&b| b != 0)
.map(|i| i + 1)
.unwrap_or(0);
trace_hex("NFT URI:", &uri.data[..uri_end]);

// Native coverage runs against empty/mock host stubs, which do not reproduce the minted
// token. Value checks are only meaningful against rippled.
if cfg!(target_arch = "wasm32") {
if flags.as_u16() != EXPECTED_NFT_FLAGS {
Comment thread
TimothyBanks marked this conversation as resolved.
Resolved
trace_num("ERROR: NFT flags mismatch, got:", flags.as_u16() as i64);
return -628;
}
if transfer_fee != EXPECTED_NFT_TRANSFER_FEE {
trace_num(
"ERROR: NFT transfer fee mismatch, got:",
transfer_fee as i64,
);
return -629;
}
if issuer.0 != owner.0 {
trace("ERROR: NFT issuer does not match EscrowFinish Account");
return -630;
}
if taxon != EXPECTED_NFT_TAXON {
trace_num("ERROR: NFT taxon mismatch, got:", taxon as i64);
return -631;
}
// Compare the trimmed slice (bounded by `uri_end`, never a fixed index) so a
// shorter-than-expected buffer fails the length check instead of trapping.
if &uri.data[..uri_end] != EXPECTED_NFT_URI {
trace_num("ERROR: NFT URI mismatch, got len:", uri_end as i64);
return -632;
}
}

trace("SUCCESS: NFT fields");
0
}

/// Test Category 7: Data Update Functions (1 function)
/// Tests the function for modifying the current ledger entry
fn test_data_update_functions() -> i32 {
Expand Down
79 changes: 21 additions & 58 deletions examples/smart-escrows/atomic_swap/atomic_swap1/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,15 @@
#[cfg(not(target_arch = "wasm32"))]
extern crate std;

use xrpl_common_stdlib::fields::locator::Locator;
use xrpl_common_stdlib::ctx::SmartFeatureContext;
use xrpl_common_stdlib::current_tx::traits::TransactionCommonFields;
use xrpl_common_stdlib::host::chain::parent_ledger_time;
use xrpl_common_stdlib::host::trace::{trace_hex, trace_num};
use xrpl_common_stdlib::host::tx_inner;
use xrpl_common_stdlib::host::{Error, Result, Result::Err, Result::Ok};
use xrpl_common_stdlib::host::{Result::Err, Result::Ok};
use xrpl_common_stdlib::ledger_entry_ids::XRPL_LEDGER_ENTRY_ID_SIZE;
use xrpl_common_stdlib::objects::cache_le;
use xrpl_common_stdlib::objects::traits::EscrowFields;
use xrpl_common_stdlib::sfield;
use xrpl_common_stdlib::types::contract_data::XRPL_CONTRACT_DATA_SIZE;
use xrpl_common_stdlib::types::contract_data::{
ContractData, XRPL_CONTRACT_DATA_SIZE as TX_CONTRACT_DATA_SIZE,
};
use xrpl_common_stdlib::types::contract_data::{ContractData, XRPL_CONTRACT_DATA_SIZE};
use xrpl_escrow_stdlib::EscrowFinishContext;
use xrpl_escrow_stdlib::ledger_objects::current_escrow::CurrentEscrow;
use xrpl_escrow_stdlib::ledger_objects::escrow::Escrow;
Expand Down Expand Up @@ -52,40 +48,6 @@ fn is_valid_atomic_swap2_wasm(wasm_bytes: &[u8]) -> bool {
}
*/

/// Extracts the first memo from the transaction.
///
/// This function uses a Locator to navigate the transaction structure:
/// - Memos[0].MemoData contains the counterpart escrow ledger entry ID
/// - Returns the memo data as a byte array and its length
/// - Used to get the 32-byte ledger entry ID of the counterpart escrow
#[unsafe(no_mangle)]
pub fn get_first_memo() -> Result<Option<(ContractData, usize)>> {
let mut data: ContractData = ContractData {
data: [0u8; TX_CONTRACT_DATA_SIZE],
len: 0,
};
let mut locator = Locator::new();
locator.pack(sfield::Memos);
locator.pack(0);
locator.pack(sfield::MemoData);
let result_code = unsafe {
tx_inner(
locator.as_ptr(),
locator.num_packed_bytes(),
data.data.as_mut_ptr(),
data.data.len(),
)
};

match result_code {
result_code if result_code > 0 => Ok(Some((data, result_code as usize))),
// Zero length is a present-but-empty memo (protocol-valid input); treat it the
// same as an absent field and let the caller decide.
0 => Ok(None),
result_code => Err(Error::from_code(result_code)),
}
}

/// Phase 1: Initialization - validate counterpart escrow and set timing deadline.
///
/// This function:
Expand All @@ -95,30 +57,30 @@ pub fn get_first_memo() -> Result<Option<(ContractData, usize)>> {
/// 4. Retrieves CancelAfter as the swap deadline
/// 5. Stores the counterpart ledger entry ID + deadline in the data field
/// 6. Returns 0 to wait for Phase 2
fn phase1_initialize(current_escrow: &CurrentEscrow) -> i32 {
fn phase1_initialize(tx: &impl TransactionCommonFields, current_escrow: &CurrentEscrow) -> i32 {
trace_num("Phase 1: Initialization", 0);

// Extract the counterpart escrow ledger entry ID from transaction memo
let (memo, memo_len) = match get_first_memo() {
Ok(v) => match v {
Some(v) => v,
None => {
trace_num(
"No memo provided - atomic swap requires counterpart reference",
0,
);
return VALIDATION_FAILED;
}
},
let memo: ContractData = match tx.first_memo_data().get_optional::<ContractData>() {
// Zero length is a present-but-empty memo (protocol-valid input); treat it the
// same as an absent field.
Ok(Some(v)) if v.len > 0 => v,
Ok(_) => {
trace_num(
"No memo provided - atomic swap requires counterpart reference",
0,
);
return VALIDATION_FAILED;
}
Err(e) => {
trace_num("Error getting first memo:", e.code() as i64);
return e.code();
}
};

// Validate memo contains a full 32-byte ledger entry ID
if memo_len != XRPL_LEDGER_ENTRY_ID_SIZE {
trace_num("Memo too short, expected 32 bytes, got:", memo_len as i64);
if memo.len != XRPL_LEDGER_ENTRY_ID_SIZE {
trace_num("Memo too short, expected 32 bytes, got:", memo.len as i64);
return VALIDATION_FAILED;
}

Expand Down Expand Up @@ -336,6 +298,7 @@ fn phase2_complete(current_data: &xrpl_common_stdlib::types::contract_data::Cont
/// 4. Returns 1 (success) if within deadline, 0 (failure) if expired
#[smart_escrow]
fn atomic_swap1_finish(ctx: EscrowFinishContext) -> i32 {
let tx = ctx.tx();
let current_escrow = ctx.escrow();

// Get the current data field - this stores the atomic swap state
Expand All @@ -346,7 +309,7 @@ fn atomic_swap1_finish(ctx: EscrowFinishContext) -> i32 {
// If the data field doesn't exist, this is Phase 1
if e.code() == xrpl_common_stdlib::host::error_codes::FIELD_NOT_FOUND {
trace_num("No data field found - this is Phase 1", 0);
return phase1_initialize(current_escrow);
return phase1_initialize(tx, current_escrow);
}
trace_num("Error getting current escrow data:", e.code() as i64);
return e.code();
Expand All @@ -359,7 +322,7 @@ fn atomic_swap1_finish(ctx: EscrowFinishContext) -> i32 {
// Phase 1: data.len == 0 (no state stored yet)
// Phase 2: data.len >= 36 (contains counterpart ledger entry ID + timing data)
if current_data.len == 0 {
phase1_initialize(current_escrow)
phase1_initialize(tx, current_escrow)
} else {
phase2_complete(&current_data)
}
Expand Down
Loading
Loading