From 97532971182ced5b50d6c260c64de3d998ffef79 Mon Sep 17 00:00:00 2001 From: Nik Erzetic Date: Fri, 19 Jun 2026 09:49:05 +0200 Subject: [PATCH] feat: update cross-chain guides to parity with scripts --- .../typescript-viem/04-cross-chain-mint.mdx | 50 +++++-- .../typescript-viem/05-cross-chain-redeem.mdx | 124 +++++++++++------- .../smart-accounts/cross-chain-redeem.ts | 72 ++++++---- 3 files changed, 160 insertions(+), 86 deletions(-) diff --git a/docs/smart-accounts/guides/typescript-viem/04-cross-chain-mint.mdx b/docs/smart-accounts/guides/typescript-viem/04-cross-chain-mint.mdx index e31b23cd..12f11ae8 100644 --- a/docs/smart-accounts/guides/typescript-viem/04-cross-chain-mint.mdx +++ b/docs/smart-accounts/guides/typescript-viem/04-cross-chain-mint.mdx @@ -239,7 +239,7 @@ The encoded calls are dispatched by issuing an XRPL **direct mint payment** to t The XRP amount in that payment is what mints FXRP on Flare; the memo is what tells the personal account what to do with it. The FAssets executor picks the payment up off the XRPL, proves it via the [Flare Data Connector](https://dev.flare.network/fdc/attestation-types/xrp-payment), and delivers the memo to the `MasterAccountController` contract — which in turn dispatches the `UserOperation` to the personal account on Flare. -The `sendMemoFieldInstruction` helper bundles the four steps required: read the current nonce, encode the memo, submit the XRPL payment, and wait for the on-chain event that confirms execution. +The `sendMemoFieldInstruction` helper bundles the steps required: read the current nonce and the core-vault payment address, encode the memo, submit the XRPL payment, and wait for the on-chain event that confirms execution. ```typescript title="src/utils/smart-accounts.ts" export async function sendMemoFieldInstruction({ @@ -257,7 +257,13 @@ export async function sendMemoFieldInstruction({ xrplClient: Client; xrplWallet: Wallet; }) { - const nonce = await getNonce(personalAccount); + console.log(`[${label}] customInstruction:`, customInstruction, "\n"); + + const [nonce, coreVaultXrplAddress] = await Promise.all([ + getNonce(personalAccount), + getDirectMintingPaymentAddress(), + ]); + console.log(`[${label}] current nonce:`, nonce, "\n"); const memoData = encodeExecuteUserOpMemo({ customInstruction, @@ -267,8 +273,6 @@ export async function sendMemoFieldInstruction({ nonce, }); - const coreVaultXrplAddress = await getDirectMintingPaymentAddress(); - const transaction = await sendXrplPayment({ destination: coreVaultXrplAddress, amount: amountXrp, @@ -276,8 +280,14 @@ export async function sendMemoFieldInstruction({ wallet: xrplWallet, client: xrplClient, }); + console.log( + `[${label}] XRPL transaction hash:`, + transaction.result.hash, + "\n", + ); const event = await waitForUserOperationExecuted({ personalAccount, nonce }); + console.log(`[${label}] UserOperationExecuted event:`, event, "\n"); return event; } ``` @@ -313,7 +323,8 @@ export async function getNonce(personalAccount: Address): Promise { ``` The memo is built in `encodeExecuteUserOpMemo`. -It first encodes the array of `Call` structs as the calldata for `PersonalAccount.executeUserOp`, then wraps that calldata in a `PackedUserOperation` tuple matching ERC-4337's layout (with empty `initCode`, `paymasterAndData`, and `signature` for memo-bridged operations), and finally hands it to the `MemoFieldUserOpCustomInstruction` class from [`@flarenetwork/smart-accounts-encoder`](https://www.npmjs.com/package/@flarenetwork/smart-accounts-encoder). +It delegates the `PackedUserOperation` encoding to `encodePackedUserOpData` (a helper function shared with the `0xFE` hash-instruction flow), which encodes the array of `Call` structs as the calldata for `PersonalAccount.executeUserOp`, then wraps that calldata in a `PackedUserOperation` tuple matching ERC-4337's layout (with empty `initCode`, `paymasterAndData`, and `signature` for memo-bridged operations). +The `encodeExecuteUserOpMemo` function then hands the encoded operation to the `MemoFieldUserOpCustomInstruction` class from [`@flarenetwork/smart-accounts-encoder`](https://www.npmjs.com/package/@flarenetwork/smart-accounts-encoder). That class owns the 10-byte header byte layout - `0xFF` (instruction ID for memo-bridged user operations) followed by the wallet identifier byte and an 8-byte executor fee in big-endian UBA - and `.encode()` returns the header concatenated with the full `PackedUserOperation`. ```typescript title="src/utils/smart-accounts.ts" @@ -334,16 +345,12 @@ const PACKED_USER_OPERATION_TUPLE = { const ZERO_BYTES32 = ("0x" + "00".repeat(32)) as `0x${string}`; -export function encodeExecuteUserOpMemo({ +function encodePackedUserOpData({ customInstruction, - walletId, - executorFeeUBA, sender, nonce, }: { customInstruction: Call[]; - walletId: number; - executorFeeUBA: bigint; sender: Address; nonce: bigint; }): `0x${string}` { @@ -353,7 +360,7 @@ export function encodeExecuteUserOpMemo({ args: [customInstruction], }); - const packedUserOperation = encodeAbiParameters( + return encodeAbiParameters( [PACKED_USER_OPERATION_TUPLE], [ { @@ -369,7 +376,26 @@ export function encodeExecuteUserOpMemo({ }, ], ); +} +export function encodeExecuteUserOpMemo({ + customInstruction, + walletId, + executorFeeUBA, + sender, + nonce, +}: { + customInstruction: Call[]; + walletId: number; + executorFeeUBA: bigint; + sender: Address; + nonce: bigint; +}): `0x${string}` { + const packedUserOperation = encodePackedUserOpData({ + customInstruction, + sender, + nonce, + }); return new MemoFieldUserOpCustomInstruction({ walletId, executorFeeUBA, @@ -445,7 +471,7 @@ The second payment carries no mint value (`memoOnlyAmountXrp` only covers the pr :::info The split exists because the XRPL memo field is capped at roughly 1024 bytes. -A combined approve + bridge `UserOperation` encodes to about 1066 bytes — 42 bytes over the cap — so the two calls must be sent independently. +A combined approve + bridge `UserOperation` encodes to about 1098 bytes, over the cap, so the two calls must be sent independently. ::: The Sepolia block number is captured between the two instructions, so the subsequent event poll has a tight lower bound. diff --git a/docs/smart-accounts/guides/typescript-viem/05-cross-chain-redeem.mdx b/docs/smart-accounts/guides/typescript-viem/05-cross-chain-redeem.mdx index f11eca15..09668eff 100644 --- a/docs/smart-accounts/guides/typescript-viem/05-cross-chain-redeem.mdx +++ b/docs/smart-accounts/guides/typescript-viem/05-cross-chain-redeem.mdx @@ -98,22 +98,45 @@ The `getAssetManagerFXRPAddress` helper is covered in the [State Lookup guide](/ ## The compose message A LayerZero compose message is opaque calldata that the destination chain's executor passes to a contract after the OFT credit has been applied. -The redemption composer on Flare expects a tuple of `(uint256 amount, string underlyingAddress, address redeemer)`. +The redemption composer on Flare expects the `RedeemComposeMessage` struct defined by `IFAssetRedeemComposer` - a six-field tuple. +The redeemed amount itself is not part of the message; it is carried by the OFT credit that LayerZero applies before the composer runs. ```typescript title="src/cross-chain-redeem.ts" +// Mirrors `IFAssetRedeemComposer.RedeemComposeMessage`. +const redeemComposeMessageAbi = [ + { + type: "tuple", + components: [ + { name: "redeemer", type: "address" }, + { name: "redeemerUnderlyingAddress", type: "string" }, + { name: "redeemWithTag", type: "bool" }, + { name: "destinationTag", type: "uint256" }, + { name: "executor", type: "address" }, + { name: "executorFee", type: "uint256" }, + ], + }, +] as const; + function encodeComposeMessage( - amountToSend: bigint, - underlyingAddress: string, redeemer: Address, + underlyingAddress: string, ): `0x${string}` { - return encodeAbiParameters( - [{ type: "uint256" }, { type: "string" }, { type: "address" }], - [amountToSend, underlyingAddress, redeemer], - ); + return encodeAbiParameters(redeemComposeMessageAbi, [ + { + redeemer, + redeemerUnderlyingAddress: underlyingAddress, + redeemWithTag: false, + destinationTag: 0n, + executor: zeroAddress, + executorFee: 0n, + }, + ]); } ``` -The `amountToSend` parameter is the FXRP amount in base units, the `underlyingAddress` is the XRPL address to receive the XRP, and the `redeemer` is the Sepolia account credited as the redeemer on the `AssetManager`. +The `redeemer` is the Sepolia account credited as the redeemer on the `AssetManager`, and `redeemerUnderlyingAddress` is the XRPL address to receive the XRP. +This tagless flow sets `redeemWithTag` to `false` and `destinationTag` to `0`; the [Cross-Chain Redeem to Tag guide](/smart-accounts/guides/typescript-viem/cross-chain-redeem-to-tag-ts) covers the tagged variant. +The compose message leaves `executor` and `executorFee` zeroed because the script attaches no executor; the composer is deployed with a `_defaultExecutor` and uses it for the redemption, which is why the emitted `FAssetRedeemed` event reports a non-zero `executor`. ## Compose and executor options @@ -202,18 +225,20 @@ const txHash = await sepoliaWalletClient.writeContract(request); The third argument of `send` is the refund address — any unused portion of `nativeFee` is returned there. Once the Sepolia receipt is in, the LayerZero scanner link is printed so the user can follow the cross-chain delivery in real time. -## Waiting for `RedemptionRequested` Event +## Waiting for the `FAssetRedeemed` Event -A successful flow results in the `AssetManager` on Flare emitting a [`RedemptionRequested`](/fassets/reference/IAssetManagerEvents#redemptionrequested) event with the composer as the `redeemer` indexed argument. -The `waitForRedemptionOnCoston2` helper polls Flare in 25-block chunks (the Coston2 RPC caps `eth_getLogs` at 30 blocks per query) for up to 5 minutes. +Because the composer is the contract that pulls the trigger on the redemption, it emits its own `FAssetRedeemed` event once the underlying `AssetManager.redeem` call succeeds, with the redeemer (the Sepolia signer) as the indexed argument. +The `waitForFAssetRedeemedOnCoston2` helper polls Flare in 25-block chunks (the Coston2 RPC caps `eth_getLogs` at 30 blocks per query) for up to 5 minutes. ```typescript title="src/cross-chain-redeem.ts" const REDEMPTION_TIMEOUT_MS = 5 * 60 * 1000; const REDEMPTION_POLL_INTERVAL_MS = 10_000; const MAX_BLOCK_RANGE = 25n; -async function waitForRedemptionOnCoston2(fromBlock: bigint) { - const assetManagerAddress = await getAssetManagerFXRPAddress(); +async function waitForFAssetRedeemedOnCoston2( + redeemer: Address, + fromBlock: bigint, +) { const deadline = Date.now() + REDEMPTION_TIMEOUT_MS; let cursor = fromBlock; @@ -223,10 +248,10 @@ async function waitForRedemptionOnCoston2(fromBlock: bigint) { const chunkEnd = cursor + MAX_BLOCK_RANGE - 1n; const toBlock = chunkEnd > latest ? latest : chunkEnd; const logs = await publicClient.getContractEvents({ - address: assetManagerAddress, - abi: coston2.iAssetManagerAbi, - eventName: "RedemptionRequested", - args: { redeemer: CONFIG.COSTON2_COMPOSER }, + address: CONFIG.COSTON2_COMPOSER, + abi: coston2.ifAssetRedeemComposerAbi, + eventName: "FAssetRedeemed", + args: { redeemer }, fromBlock: cursor, toBlock, }); @@ -241,13 +266,13 @@ async function waitForRedemptionOnCoston2(fromBlock: bigint) { } throw new Error( - `RedemptionRequested event not observed within ${REDEMPTION_TIMEOUT_MS}ms`, + `FAssetRedeemed event not observed within ${REDEMPTION_TIMEOUT_MS}ms`, ); } ``` The inner loop advances `cursor` chunk-by-chunk through any new blocks that have appeared, then sleeps 10 seconds before re-checking the chain tip. -Filtering by `redeemer` on the indexed argument means the call only returns events tied to the composer this script is targeting. +Filtering by `redeemer` on the indexed argument means the call only returns the event tied to this redeemer (the Sepolia signer), even if multiple unrelated redemptions are in flight against the same composer. The actual XRP payment to `underlyingAddress` is handled off-chain by an FAsset agent after the redemption request is filed. That step is asynchronous and is not awaited by this script. @@ -266,9 +291,6 @@ In the example repository, certain helpers are isolated into separate files in t ```bash > pnpm run script src/layer-zero/cross-chain-redeem.ts -> @flarenetwork/flare-smart-accounts-viem@0.0.1 script ~/flare-smart-accounts-viem -> tsx --env-file=.env src/layer-zero/cross-chain-redeem.ts - Using account: 0xF5488132432118596fa13800B68df4C0fF25131d Composer configured: 0xa10569DFb38FE7Be211aCe4E4A566Cea387023b0 Connecting to FXRP OFT on Sepolia: 0x81672c5d42F3573aD95A0bdfBE824FaaC547d4E6 @@ -279,53 +301,53 @@ Amount: 10000000 FXRP base units XRP Address: rpHuw4bKSjonKRrKKVYUZYYVedg1jyPrmp Redeemer: 0xF5488132432118596fa13800B68df4C0fF25131d -Current FXRP balance: 80 +Current FXRP balance: 90 LayerZero Fee: 0.000101716112596574 ETH Sending 10 FXRP to Coston2 with auto-redeem... Target composer: 0xa10569DFb38FE7Be211aCe4E4A566Cea387023b0 -Transaction sent: 0x92f51cdc9b7ed4c9c63876340c843415ee5d5721624fadeb2549bfc539a657e7 -Confirmed in block: 10838150n +Transaction sent: 0x2fe0579171ac6e46bca2ace25eebfa7546677b00fb267917507d416bb1b38c39 +Confirmed in block: 11092668n Track your cross-chain transaction: -https://testnet.layerzeroscan.com/tx/0x92f51cdc9b7ed4c9c63876340c843415ee5d5721624fadeb2549bfc539a657e7 +https://testnet.layerzeroscan.com/tx/0x2fe0579171ac6e46bca2ace25eebfa7546677b00fb267917507d416bb1b38c39 The auto-redeem will execute once the message arrives on Coston2. XRP will be sent to: rpHuw4bKSjonKRrKKVYUZYYVedg1jyPrmp -Waiting for RedemptionRequested event on Coston2... +Waiting for FAssetRedeemed event on Coston2 composer... -RedemptionRequested event observed on Coston2: +FAssetRedeemed event observed on Coston2: { - eventName: 'RedemptionRequested', + eventName: 'FAssetRedeemed', args: { - agentVault: '0xd5dEFe2c62D48788BB3889534FBFe7Aea0602D64', - redeemer: '0xa10569DFb38FE7Be211aCe4E4A566Cea387023b0', - requestId: 29197906n, - paymentAddress: 'rpHuw4bKSjonKRrKKVYUZYYVedg1jyPrmp', - valueUBA: 10000000n, - feeUBA: 50000n, - firstUnderlyingBlock: 17306757n, - lastUnderlyingBlock: 17307376n, - lastUnderlyingTimestamp: 1778579481n, - paymentReference: '0x4642505266410002000000000000000000000000000000000000000001bd8652', - executor: '0x0000000000000000000000000000000000000000', - executorFeeNatWei: 0n + guid: '0xfc74bfbdbe1d874c972f98b171aac4a279af3940ca1090448fcac1c95e154502', + srcEid: 40161, + redeemer: '0xF5488132432118596fa13800B68df4C0fF25131d', + redeemerAccount: '0xEB947e97BD6b02C4121D2AdBAa1e07A4cA3D8D1E', + amountToRedeemUBA: 9990000n, + redeemerUnderlyingAddress: 'rpHuw4bKSjonKRrKKVYUZYYVedg1jyPrmp', + redeemWithTag: false, + destinationTag: 0n, + executor: '0x103b384064ae85577127097A7cCadfd6fb13f437', + executorFee: 0n, + redeemedAmountUBA: 9990000n, + wrappedAmount: 0n }, - address: '0xc1ca88b937d0b528842f95d5731ffb586f4fbdfa', + address: '0xa10569dfb38fe7be211ace4e4a566cea387023b0', topics: [ - '0x8cbbd73a8d1b8b02a53c4c3b0ee34b472fe3099cc19bcfb57f1aae09e8a9847e', - '0x000000000000000000000000d5defe2c62d48788bb3889534fbfe7aea0602d64', - '0x0000000000000000000000005051e8db650e9e0e2a3f03010ee5c60e79cf583e', - '0x0000000000000000000000000000000000000000000000000000000001bd8652' + '0x9e8ed1306ec6ca165a2c23ae451b161741d3da7ab41fe134775ebd94b2351f04', + '0xfc74bfbdbe1d874c972f98b171aac4a279af3940ca1090448fcac1c95e154502', + '0x0000000000000000000000000000000000000000000000000000000000009ce1', + '0x000000000000000000000000f5488132432118596fa13800b68df4c0ff25131d' ], - data: '0x00000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000989680000000000000000000000000000000000000000000000000000000000000c350000000000000000000000000000000000000000000000000000000000108148500000000000000000000000000000000000000000000000000000000010816f0000000000000000000000000000000000000000000000000000000006a02f8194642505266410002000000000000000000000000000000000000000001bd8652000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022727048757734624b536a6f6e4b52724b4b5659555a595956656467316a7950726d70000000000000000000000000000000000000000000000000000000000000', - blockNumber: 30438649n, - transactionHash: '0x9d82fe98f04fa37f729c786cab99632c781b9f3bc655cdd040a8adcfc497f736', - transactionIndex: 1, - blockHash: '0xa006cf7988226e5e57a1194e9c5a183beec2a37d999f966199f943fe044a77a2', + data: '0x000000000000000000000000eb947e97bd6b02c4121d2adbaa1e07a4ca3d8d1e0000000000000000000000000000000000000000000000000000000000986f70000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000103b384064ae85577127097a7ccadfd6fb13f43700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000986f7000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022727048757734624b536a6f6e4b52724b4b5659555a595956656467316a7950726d70000000000000000000000000000000000000000000000000000000000000', + blockNumber: 32002759n, + transactionHash: '0xfc4bbf7d8ce50667118e7ccbd9e747b9def1ec5ee246a3ff86bb16fc402ea78a', + transactionIndex: 0, + blockHash: '0x0171ee0a125ac3ba8ae50684071b238a4c8eb663b87038b60578fdfc0b4f5952', logIndex: 9, removed: false, blockTimestamp: undefined diff --git a/examples/developer-hub-javascript/smart-accounts/cross-chain-redeem.ts b/examples/developer-hub-javascript/smart-accounts/cross-chain-redeem.ts index e93c4a59..cddd416b 100644 --- a/examples/developer-hub-javascript/smart-accounts/cross-chain-redeem.ts +++ b/examples/developer-hub-javascript/smart-accounts/cross-chain-redeem.ts @@ -1,4 +1,10 @@ -import { encodeAbiParameters, formatUnits, pad, type Address } from "viem"; +import { + encodeAbiParameters, + formatUnits, + pad, + zeroAddress, + type Address, +} from "viem"; import { Options } from "@layerzerolabs/lz-v2-utilities"; import { EndpointId } from "@layerzerolabs/lz-definitions"; import { coston2 } from "@flarenetwork/flare-wagmi-periphery-package"; @@ -10,7 +16,6 @@ import { } from "./utils/client"; import { abi as fxrpOftAbi } from "./abis/FXRPOFT"; import { calculateAmountToSend } from "./utils/fassets"; -import { getAssetManagerFXRPAddress } from "./utils/flare-contract-registry"; import type { SendParam } from "./types"; const CONFIG = { @@ -29,15 +34,35 @@ const REDEMPTION_POLL_INTERVAL_MS = 10_000; // Coston2 RPC caps eth_getLogs to a 30-block range; chunk lookups to stay under it. const MAX_BLOCK_RANGE = 25n; +// Mirrors `IFAssetRedeemComposer.RedeemComposeMessage`. +const redeemComposeMessageAbi = [ + { + type: "tuple", + components: [ + { name: "redeemer", type: "address" }, + { name: "redeemerUnderlyingAddress", type: "string" }, + { name: "redeemWithTag", type: "bool" }, + { name: "destinationTag", type: "uint256" }, + { name: "executor", type: "address" }, + { name: "executorFee", type: "uint256" }, + ], + }, +] as const; + function encodeComposeMessage( - amountToSend: bigint, - underlyingAddress: string, redeemer: Address, + underlyingAddress: string, ): `0x${string}` { - return encodeAbiParameters( - [{ type: "uint256" }, { type: "string" }, { type: "address" }], - [amountToSend, underlyingAddress, redeemer], - ); + return encodeAbiParameters(redeemComposeMessageAbi, [ + { + redeemer, + redeemerUnderlyingAddress: underlyingAddress, + redeemWithTag: false, + destinationTag: 0n, + executor: zeroAddress, + executorFee: 0n, + }, + ]); } function buildComposeOptions(): `0x${string}` { @@ -130,11 +155,13 @@ async function executeSendAndRedeem( return txHash; } -async function waitForRedemptionOnCoston2(fromBlock: bigint) { - const assetManagerAddress = await getAssetManagerFXRPAddress(); +async function waitForFAssetRedeemedOnCoston2( + redeemer: Address, + fromBlock: bigint, +) { const deadline = Date.now() + REDEMPTION_TIMEOUT_MS; - console.log("\nWaiting for RedemptionRequested event on Coston2..."); + console.log("\nWaiting for FAssetRedeemed event on Coston2 composer..."); let cursor = fromBlock; while (Date.now() < deadline) { @@ -143,10 +170,10 @@ async function waitForRedemptionOnCoston2(fromBlock: bigint) { const chunkEnd = cursor + MAX_BLOCK_RANGE - 1n; const toBlock = chunkEnd > latest ? latest : chunkEnd; const logs = await publicClient.getContractEvents({ - address: assetManagerAddress, - abi: coston2.iAssetManagerAbi, - eventName: "RedemptionRequested", - args: { redeemer: CONFIG.COSTON2_COMPOSER }, + address: CONFIG.COSTON2_COMPOSER, + abi: coston2.ifAssetRedeemComposerAbi, + eventName: "FAssetRedeemed", + args: { redeemer }, fromBlock: cursor, toBlock, }); @@ -161,7 +188,7 @@ async function waitForRedemptionOnCoston2(fromBlock: bigint) { } throw new Error( - `RedemptionRequested event not observed within ${REDEMPTION_TIMEOUT_MS}ms`, + `FAssetRedeemed event not observed within ${REDEMPTION_TIMEOUT_MS}ms`, ); } @@ -194,11 +221,7 @@ async function main() { console.log("XRP Address:", CONFIG.XRP_ADDRESS); console.log("Redeemer:", signerAddress); - const composeMsg = encodeComposeMessage( - amountToSend, - CONFIG.XRP_ADDRESS, - signerAddress, - ); + const composeMsg = encodeComposeMessage(signerAddress, CONFIG.XRP_ADDRESS); const extraOptions = buildComposeOptions(); const sendParam = buildSendParam(amountToSend, composeMsg, extraOptions); @@ -222,8 +245,11 @@ async function main() { CONFIG.XRP_ADDRESS, ); - const redemptionEvent = await waitForRedemptionOnCoston2(startBlock); - console.log("\nRedemptionRequested event observed on Coston2:"); + const redemptionEvent = await waitForFAssetRedeemedOnCoston2( + signerAddress, + startBlock, + ); + console.log("\nFAssetRedeemed event observed on Coston2:"); console.log(redemptionEvent); }