@owney/sdk 0.7.26-beta.4 → 0.7.26-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -26,9 +26,15 @@ __export(index_exports, {
26
26
  NotConnectedError: () => NotConnectedError,
27
27
  OwneyError: () => OwneyError,
28
28
  OwneySDK: () => OwneySDK,
29
+ clearWithdrawSwap: () => clearWithdrawSwap,
29
30
  createOwneySIWX: () => createOwneySIWX,
31
+ listPendingDeposits: () => listPendingDeposits,
30
32
  listPendingSwaps: () => listOrders,
31
- setOwneyDebug: () => setOwneyDebug
33
+ listWithdrawSwaps: () => listWithdrawSwaps,
34
+ saveWithdrawSwap: () => saveWithdrawSwap,
35
+ setOwneyDebug: () => setOwneyDebug,
36
+ subscribeWithdrawSwaps: () => subscribeWithdrawSwaps,
37
+ updateWithdrawSwap: () => updateWithdrawSwap
32
38
  });
33
39
  module.exports = __toCommonJS(index_exports);
34
40
 
@@ -2328,11 +2334,12 @@ function createSwapApi(baseUrl, apiKey) {
2328
2334
  baseUrl,
2329
2335
  apiKey,
2330
2336
  `/tokens/search?${new URLSearchParams({
2331
- query: params.query,
2337
+ ...params.query === void 0 ? {} : { query: params.query },
2332
2338
  // Omitted, the routing API searches every supported chain — which is
2333
2339
  // what a picker wants, since its rows already span all three.
2334
2340
  ...params.chainId === void 0 ? {} : { chainId: String(params.chainId) },
2335
- ...params.limit === void 0 ? {} : { limit: String(params.limit) }
2341
+ ...params.limit === void 0 ? {} : { limit: String(params.limit) },
2342
+ ...params.direction === void 0 ? {} : { direction: params.direction }
2336
2343
  }).toString()}`
2337
2344
  ),
2338
2345
  /**
@@ -2418,12 +2425,41 @@ function createSwapApi(baseUrl, apiKey) {
2418
2425
  // src/lib/swap/swap.rpc.ts
2419
2426
  var import_viem2 = require("viem");
2420
2427
  var DEFAULT_RPC_URLS = {
2421
- 1: ["https://cloudflare-eth.com", "https://ethereum-rpc.publicnode.com"],
2428
+ // NOT cloudflare-eth.com, which used to lead this list. It answers
2429
+ // eth_chainId happily, errors on eth_blockNumber, and — the part that
2430
+ // actually broke things — returns `result: null` for the receipt of a
2431
+ // transaction that is demonstrably mined. Null is a VALID answer meaning
2432
+ // "not found", so viem's fallback has no reason to try the next endpoint:
2433
+ // waitForTransactionReceipt simply polls until it times out, which on this
2434
+ // chain is ten minutes of a spinner (ROUT-242). An endpoint that ERRORS is
2435
+ // safe; an endpoint that lies quietly is not.
2436
+ 1: ["https://ethereum-rpc.publicnode.com", "https://eth.drpc.org"],
2422
2437
  8453: ["https://mainnet.base.org", "https://base-rpc.publicnode.com"],
2423
2438
  42161: [
2424
2439
  "https://arb1.arbitrum.io/rpc",
2425
2440
  "https://arbitrum-one-rpc.publicnode.com"
2426
- ]
2441
+ ],
2442
+ // Added with the wider swap chain set (ROUT-242, comment 15982). Every one
2443
+ // of these answered with `access-control-allow-origin: *` on 2026-09-29;
2444
+ // a chain without two verified endpoints does not belong in the list.
2445
+ 10: ["https://mainnet.optimism.io", "https://optimism-rpc.publicnode.com"],
2446
+ // polygon-rpc.com led this list until it started answering every call with
2447
+ // "API key disabled, reason: tenant disabled". It errors rather than lying,
2448
+ // so the fallback did cover it — at the cost of a failed request in front of
2449
+ // every Polygon read.
2450
+ 137: ["https://polygon-bor-rpc.publicnode.com", "https://polygon.drpc.org"],
2451
+ 56: ["https://bsc-dataseed.bnbchain.org", "https://bsc-rpc.publicnode.com"],
2452
+ 43114: [
2453
+ "https://api.avax.network/ext/bc/C/rpc",
2454
+ "https://avalanche-c-chain-rpc.publicnode.com"
2455
+ ],
2456
+ 143: ["https://rpc.monad.xyz", "https://rpc1.monad.xyz"],
2457
+ // ONE endpoint, not two: of the six the public chain registry lists for Arc,
2458
+ // this is the only one that answers a browser at all. viem ships none. It
2459
+ // was checked with a real eth_chainId call (0x13b2), not just a CORS header,
2460
+ // but a single provider is a single point of failure - add a second when one
2461
+ // exists.
2462
+ 5042: ["https://rpc.beamrpc.com"]
2427
2463
  };
2428
2464
  function swapReadTransport(chainId, overrides) {
2429
2465
  const override = overrides?.[chainId];
@@ -2436,6 +2472,157 @@ function receiptTimeoutMs(chainId) {
2436
2472
  return chainId === 1 ? 6e5 : 18e4;
2437
2473
  }
2438
2474
 
2475
+ // src/lib/swap/swap.wrap.ts
2476
+ var WRAP_SELECTOR = "0xd0e30db0";
2477
+ var FALLBACK_WRAP_GAS = 50000n;
2478
+ var APPROVE_GAS = 60000n;
2479
+ var GAS_SAFETY = 2n;
2480
+ var MIN_WALLET_GAS_PRICE = 3000000000n;
2481
+ async function wrapNative(deps, options) {
2482
+ const { chainId, wrapper, nativeSymbol, requested } = options;
2483
+ const balance = await deps.readNativeBalance();
2484
+ let wrapGas;
2485
+ try {
2486
+ wrapGas = await deps.estimateWrapGas(wrapper, requested);
2487
+ } catch (error) {
2488
+ wrapGas = FALLBACK_WRAP_GAS;
2489
+ debugLog("owney-sdk", "wrap: gas estimate failed, using the fallback", {
2490
+ fallback: FALLBACK_WRAP_GAS.toString(),
2491
+ message: error instanceof Error ? error.message : String(error)
2492
+ });
2493
+ }
2494
+ const measured = await deps.getMaxFeePerGas();
2495
+ const gasPrice = measured > MIN_WALLET_GAS_PRICE ? measured : MIN_WALLET_GAS_PRICE;
2496
+ const reserve = (wrapGas + APPROVE_GAS) * gasPrice * GAS_SAFETY;
2497
+ const spendable = balance > reserve ? balance - reserve : 0n;
2498
+ const wrapped = requested < spendable ? requested : spendable;
2499
+ debugLog("owney-sdk", "wrap: sizing", {
2500
+ balance: balance.toString(),
2501
+ requested: requested.toString(),
2502
+ measuredGasPrice: measured.toString(),
2503
+ reservedAtGasPrice: gasPrice.toString(),
2504
+ reserve: reserve.toString(),
2505
+ wrapped: wrapped.toString()
2506
+ });
2507
+ if (wrapped <= 0n) {
2508
+ throw new OwneyError(
2509
+ "SWAP_INSUFFICIENT_GAS",
2510
+ `Not enough ${nativeSymbol} to cover both the swap and its network fees. Leave a little ${nativeSymbol} for gas, or swap a smaller amount.`,
2511
+ {
2512
+ chainId,
2513
+ // Named in the details as well as the message so the app's own copy
2514
+ // can say "leave a little POL" rather than re-deriving it.
2515
+ symbol: nativeSymbol,
2516
+ balance: balance.toString(),
2517
+ requested: requested.toString(),
2518
+ reserve: reserve.toString()
2519
+ }
2520
+ );
2521
+ }
2522
+ await deps.ensureChain(chainId);
2523
+ debugLog("owney-sdk", "wrap: sending deposit()", {
2524
+ wrapper,
2525
+ value: wrapped.toString()
2526
+ });
2527
+ const txHash = await deps.sendTransaction(
2528
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
2529
+ options.onSubmitted
2530
+ );
2531
+ return { wrapped, txHash };
2532
+ }
2533
+ function requireWrapper(quote) {
2534
+ const wrapper = quote.wrappedNative;
2535
+ if (!wrapper?.address) {
2536
+ throw new OwneyError(
2537
+ "SWAP_NATIVE_UNSUPPORTED",
2538
+ `Swapping ${quote.src.symbol} from this chain to another isn't supported yet. Swap a token instead, or move to the destination chain first.`,
2539
+ { chainId: quote.src.chainId, symbol: quote.src.symbol }
2540
+ );
2541
+ }
2542
+ return { symbol: wrapper.symbol, address: wrapper.address };
2543
+ }
2544
+
2545
+ // src/lib/swap/swap.chains.ts
2546
+ var import_chains2 = require("viem/chains");
2547
+ var CHAINS = {
2548
+ 8453: import_chains2.base,
2549
+ 42161: import_chains2.arbitrum,
2550
+ 1: import_chains2.mainnet,
2551
+ 10: import_chains2.optimism,
2552
+ 137: import_chains2.polygon,
2553
+ 56: import_chains2.bsc,
2554
+ 43114: import_chains2.avalanche,
2555
+ 143: import_chains2.monad,
2556
+ 5042: import_chains2.arc
2557
+ };
2558
+ var SWAP_CHAIN_IDS = Object.keys(CHAINS).map(Number);
2559
+ function swapChain(chainId) {
2560
+ return CHAINS[chainId];
2561
+ }
2562
+
2563
+ // src/lib/swap/swap.arrival.ts
2564
+ var DEFAULT_TIMEOUT_MS = 18e4;
2565
+ var DEFAULT_POLL_MS = 4e3;
2566
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2567
+ async function awaitWithdrawalArrival(options) {
2568
+ const { arrived, lastReadError } = await awaitBalanceIncrease(options);
2569
+ if (arrived !== null) return arrived;
2570
+ throw new OwneyError(
2571
+ "WITHDRAW_ARRIVAL_TIMEOUT",
2572
+ "The withdrawal was accepted but the funds had not arrived in time to swap them. They are on their way to your wallet in the original asset.",
2573
+ {
2574
+ baseline: options.baseline.toString(),
2575
+ waitedMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,
2576
+ ...lastReadError ? { lastReadError } : {}
2577
+ }
2578
+ );
2579
+ }
2580
+ async function awaitBalanceIncrease(options) {
2581
+ const {
2582
+ readBalance,
2583
+ baseline,
2584
+ timeoutMs = DEFAULT_TIMEOUT_MS,
2585
+ pollMs = DEFAULT_POLL_MS
2586
+ } = options;
2587
+ const deadline = Date.now() + timeoutMs;
2588
+ debugLog("owney-sdk", "arrival: waiting for funds to land", {
2589
+ baseline: baseline.toString(),
2590
+ timeoutMs
2591
+ });
2592
+ let lastError;
2593
+ for (; ; ) {
2594
+ try {
2595
+ const balance = await readBalance();
2596
+ if (balance > baseline) {
2597
+ const arrived = balance - baseline;
2598
+ debugLog("owney-sdk", "arrival: funds landed", {
2599
+ arrived: arrived.toString()
2600
+ });
2601
+ return { arrived };
2602
+ }
2603
+ } catch (error) {
2604
+ lastError = error;
2605
+ debugLog("owney-sdk", "arrival: balance read failed, retrying", {
2606
+ message: error instanceof Error ? error.message : String(error)
2607
+ });
2608
+ }
2609
+ if (Date.now() >= deadline) {
2610
+ debugLog("owney-sdk", "arrival: nothing landed before the deadline", {
2611
+ baseline: baseline.toString(),
2612
+ waitedMs: timeoutMs,
2613
+ ...lastError ? {
2614
+ lastReadError: lastError instanceof Error ? lastError.message : String(lastError)
2615
+ } : {}
2616
+ });
2617
+ return lastError ? {
2618
+ arrived: null,
2619
+ lastReadError: lastError instanceof Error ? lastError.message : String(lastError)
2620
+ } : { arrived: null };
2621
+ }
2622
+ await sleep(pollMs);
2623
+ }
2624
+ }
2625
+
2439
2626
  // src/lib/permit2.ts
2440
2627
  var import_viem3 = require("viem");
2441
2628
  var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
@@ -2559,17 +2746,17 @@ var SWAP_TERMINAL_STATUSES = [
2559
2746
  var isSwapTerminal = (status) => SWAP_TERMINAL_STATUSES.includes(status);
2560
2747
 
2561
2748
  // src/lib/swap/swap.order-runner.ts
2562
- var DEFAULT_POLL_MS = 5e3;
2749
+ var DEFAULT_POLL_MS2 = 5e3;
2563
2750
  var MAX_BACKOFF_MS = 3e4;
2564
- var backoffFor = (failures, base3) => Math.min(base3 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
2565
- var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
2751
+ var backoffFor = (failures, base4) => Math.min(base4 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
2752
+ var DEFAULT_TIMEOUT_MS2 = 15 * 60 * 1e3;
2566
2753
  async function runFusionOrder(deps, options) {
2567
2754
  const {
2568
2755
  orderHash,
2569
2756
  secrets,
2570
2757
  onStage,
2571
- pollIntervalMs = DEFAULT_POLL_MS,
2572
- timeoutMs = DEFAULT_TIMEOUT_MS
2758
+ pollIntervalMs = DEFAULT_POLL_MS2,
2759
+ timeoutMs = DEFAULT_TIMEOUT_MS2
2573
2760
  } = options;
2574
2761
  const deadline = deps.now() + timeoutMs;
2575
2762
  let failures = 0;
@@ -2580,7 +2767,11 @@ async function runFusionOrder(deps, options) {
2580
2767
  throw new OwneyError(
2581
2768
  "SWAP_REQUEST_FAILED",
2582
2769
  "Timed out waiting for the swap to settle. It may still complete \u2014 check the order status before retrying.",
2583
- { orderHash }
2770
+ // Marks the one failure that means "we stopped watching a live order",
2771
+ // as opposed to a verdict or a prompt nobody answered. The executor
2772
+ // checks the wallet before believing it: resolvers do not stop filling
2773
+ // because we stopped looking (ROUT-242, comment 15980).
2774
+ { orderHash, settlementUnconfirmed: true }
2584
2775
  );
2585
2776
  }
2586
2777
  let ready;
@@ -2633,10 +2824,10 @@ async function runFusionOrder(deps, options) {
2633
2824
  }
2634
2825
 
2635
2826
  // src/lib/swap/swap.same-chain-runner.ts
2636
- var DEFAULT_POLL_MS2 = 5e3;
2827
+ var DEFAULT_POLL_MS3 = 5e3;
2637
2828
  var MAX_BACKOFF_MS2 = 3e4;
2638
- var backoffFor2 = (failures, base3) => Math.min(base3 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS2);
2639
- var DEFAULT_TIMEOUT_MS2 = 3 * 60 * 1e3;
2829
+ var backoffFor2 = (failures, base4) => Math.min(base4 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS2);
2830
+ var DEFAULT_TIMEOUT_MS3 = 3 * 60 * 1e3;
2640
2831
  function explain(status) {
2641
2832
  switch (status) {
2642
2833
  case "expired":
@@ -2659,8 +2850,8 @@ async function runSameChainOrder(deps, options) {
2659
2850
  const {
2660
2851
  orderHash,
2661
2852
  onStage,
2662
- pollIntervalMs = DEFAULT_POLL_MS2,
2663
- timeoutMs = DEFAULT_TIMEOUT_MS2
2853
+ pollIntervalMs = DEFAULT_POLL_MS3,
2854
+ timeoutMs = DEFAULT_TIMEOUT_MS3
2664
2855
  } = options;
2665
2856
  const deadline = deps.now() + timeoutMs;
2666
2857
  let failures = 0;
@@ -2758,6 +2949,35 @@ function listOrders(now = Date.now()) {
2758
2949
  }
2759
2950
 
2760
2951
  // src/lib/swap/swap.executor.ts
2952
+ var WALLET_PROMPT_TIMEOUT_MS = 3 * 60 * 1e3;
2953
+ async function awaitWalletPrompt(prompt, what) {
2954
+ let timer;
2955
+ try {
2956
+ return await Promise.race([
2957
+ prompt(),
2958
+ new Promise((_, reject) => {
2959
+ timer = setTimeout(() => {
2960
+ reject(
2961
+ new OwneyError(
2962
+ "SWAP_WALLET_PROMPT_TIMEOUT",
2963
+ // Naming the stale request matters: the wallet is still holding
2964
+ // it, which is why the next connection attempt is refused too
2965
+ // ("Connection can be declined if a previous request is still
2966
+ // active"). Dismissing it is what actually unblocks them.
2967
+ `Your wallet didn't answer the request to ${what}. Open your wallet, dismiss any request still waiting there, and try again.`,
2968
+ { prompt: what, timeoutMs: WALLET_PROMPT_TIMEOUT_MS }
2969
+ )
2970
+ );
2971
+ }, WALLET_PROMPT_TIMEOUT_MS);
2972
+ })
2973
+ ]);
2974
+ } finally {
2975
+ if (timer) clearTimeout(timer);
2976
+ }
2977
+ }
2978
+ function stoppedWatching(error) {
2979
+ return error instanceof OwneyError && error.details?.settlementUnconfirmed === true;
2980
+ }
2761
2981
  var DEFAULT_SLIPPAGE = 1;
2762
2982
  async function affordableAmount(deps, quoted) {
2763
2983
  const balance = await deps.readSourceBalance();
@@ -2780,21 +3000,39 @@ async function executeSwap(deps, options) {
2780
3000
  });
2781
3001
  const before = await deps.readTargetBalance();
2782
3002
  debugLog("owney-sdk", "swap: target balance before", before.toString());
2783
- const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
2784
- const after = await deps.readTargetBalance();
2785
- const received = after - before;
2786
- debugLog("owney-sdk", "swap: target balance after", {
2787
- after: after.toString(),
2788
- received: received.toString()
3003
+ let result;
3004
+ let railError;
3005
+ try {
3006
+ result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
3007
+ } catch (error) {
3008
+ if (!stoppedWatching(error)) throw error;
3009
+ railError = error;
3010
+ debugLog("owney-sdk", "swap: rail failed, checking whether funds landed", {
3011
+ message: error instanceof Error ? error.message : String(error)
3012
+ });
3013
+ }
3014
+ const { arrived } = await awaitBalanceIncrease({
3015
+ readBalance: () => deps.readTargetBalance(),
3016
+ baseline: before,
3017
+ ...options.arrivalTimeoutMs === void 0 ? {} : { timeoutMs: options.arrivalTimeoutMs },
3018
+ ...options.arrivalPollMs === void 0 ? {} : { pollMs: options.arrivalPollMs }
2789
3019
  });
2790
- if (received <= 0n) {
3020
+ if (arrived === null) {
3021
+ if (railError) throw railError;
2791
3022
  throw new OwneyError(
2792
3023
  "SWAP_REQUEST_FAILED",
2793
3024
  "The swap completed but no funds arrived in the wallet. Check the transaction before retrying.",
2794
- { rail: quote.rail, ...result }
3025
+ { rail: quote.rail, ...result ?? {} }
2795
3026
  );
2796
3027
  }
2797
- return { received: received.toString(), ...result };
3028
+ if (railError) {
3029
+ debugLog("owney-sdk", "swap: rail gave up but the funds are here", {
3030
+ received: arrived.toString()
3031
+ });
3032
+ const orderHash = railError.details?.orderHash;
3033
+ if (orderHash) clearOrder(orderHash);
3034
+ }
3035
+ return { received: arrived.toString(), ...result ?? {} };
2798
3036
  }
2799
3037
  async function runClassic(deps, options) {
2800
3038
  const {
@@ -2874,7 +3112,10 @@ async function runSameChainFusion(deps, options, walletAddress) {
2874
3112
  });
2875
3113
  onStage?.("signing");
2876
3114
  await deps.ensureChain(quote.src.chainId);
2877
- const signature = await deps.signTypedData(built.typedData);
3115
+ const signature = await awaitWalletPrompt(
3116
+ () => deps.signTypedData(built.typedData),
3117
+ "sign the swap"
3118
+ );
2878
3119
  debugLog("owney-sdk", "swap: signed, submitting same-chain order");
2879
3120
  await deps.api.submitOrder({
2880
3121
  // Without this the routing API hands the order to the Fusion+ relayer,
@@ -2886,6 +3127,10 @@ async function runSameChainFusion(deps, options, walletAddress) {
2886
3127
  quoteId: built.quoteId,
2887
3128
  ...built.extension ? { extension: built.extension } : {}
2888
3129
  });
3130
+ try {
3131
+ options.onOrderSubmitted?.(built.orderHash);
3132
+ } catch {
3133
+ }
2889
3134
  await runSameChainOrder(deps.sameChainRunner ?? deps.runner, {
2890
3135
  orderHash: built.orderHash,
2891
3136
  ...onStage ? { onStage } : {}
@@ -2904,7 +3149,10 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
2904
3149
  if (current >= amount) return void 0;
2905
3150
  onStage?.("approving");
2906
3151
  await deps.ensureChain(quote.src.chainId);
2907
- const permit = quote.permitSupported ? await deps.buildPermit?.(quote.spender, MAX_UINT256) ?? void 0 : void 0;
3152
+ const permit = quote.permitSupported ? await awaitWalletPrompt(
3153
+ async () => deps.buildPermit?.(quote.spender, MAX_UINT256),
3154
+ `approve ${quote.src.symbol}`
3155
+ ) ?? void 0 : void 0;
2908
3156
  if (permit) {
2909
3157
  debugLog("owney-sdk", "swap: permitting limit order protocol", {
2910
3158
  bytes: (permit.length - 2) / 2
@@ -2918,8 +3166,15 @@ async function authoriseSpend(deps, options, amount, isNativeSource) {
2918
3166
  async function runFusion(deps, options, walletAddress) {
2919
3167
  const { quote, direction, onStage } = options;
2920
3168
  const isNativeSource = quote.src.address.toLowerCase().startsWith("0xeeee");
2921
- const amount = isNativeSource ? BigInt(quote.src.amount) : await affordableAmount(deps, BigInt(quote.src.amount));
2922
- const permit = await authoriseSpend(deps, options, amount, isNativeSource);
3169
+ if (isNativeSource) {
3170
+ throw new OwneyError(
3171
+ "SWAP_NATIVE_UNSUPPORTED",
3172
+ `${quote.src.symbol} has to be wrapped before it can be swapped to another chain. Nothing has left your wallet.`,
3173
+ { chainId: quote.src.chainId, symbol: quote.src.symbol }
3174
+ );
3175
+ }
3176
+ const amount = await affordableAmount(deps, BigInt(quote.src.amount));
3177
+ const permit = await authoriseSpend(deps, options, amount, false);
2923
3178
  const { secrets, secretHashes } = mintSecrets(quote.secretsCount ?? 1);
2924
3179
  onStage?.("quoting");
2925
3180
  debugLog("owney-sdk", "swap: building fusion order", {
@@ -2954,7 +3209,10 @@ async function runFusion(deps, options, walletAddress) {
2954
3209
  debugLog("owney-sdk", "swap: awaiting signature in wallet", {
2955
3210
  signingOnChain: quote.src.chainId
2956
3211
  });
2957
- const signature = await deps.signTypedData(built.typedData);
3212
+ const signature = await awaitWalletPrompt(
3213
+ () => deps.signTypedData(built.typedData),
3214
+ "sign the swap"
3215
+ );
2958
3216
  debugLog("owney-sdk", "swap: signed, submitting to relayer");
2959
3217
  await deps.api.submitOrder({
2960
3218
  srcChainId: quote.src.chainId,
@@ -2971,6 +3229,10 @@ async function runFusion(deps, options, walletAddress) {
2971
3229
  ...built.extension ? { extension: built.extension } : {}
2972
3230
  });
2973
3231
  debugLog("owney-sdk", "swap: order submitted, polling escrows");
3232
+ try {
3233
+ options.onOrderSubmitted?.(built.orderHash);
3234
+ } catch {
3235
+ }
2974
3236
  try {
2975
3237
  await runFusionOrder(deps.runner, {
2976
3238
  orderHash: built.orderHash,
@@ -3085,54 +3347,158 @@ async function buildErc2612Permit(reads, input) {
3085
3347
  );
3086
3348
  }
3087
3349
 
3088
- // src/lib/swap/swap.arrival.ts
3089
- var DEFAULT_TIMEOUT_MS3 = 18e4;
3090
- var DEFAULT_POLL_MS3 = 4e3;
3091
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
3092
- async function awaitWithdrawalArrival(options) {
3093
- const {
3094
- readBalance,
3095
- baseline,
3096
- timeoutMs = DEFAULT_TIMEOUT_MS3,
3097
- pollMs = DEFAULT_POLL_MS3
3098
- } = options;
3099
- const deadline = Date.now() + timeoutMs;
3100
- debugLog("owney-sdk", "withdraw: waiting for funds to land", {
3101
- baseline: baseline.toString(),
3102
- timeoutMs
3103
- });
3104
- let lastError;
3105
- for (; ; ) {
3350
+ // src/lib/swap/swap.withdraw-swap.ts
3351
+ var KEY_PREFIX3 = "owney.swap.withdraw";
3352
+ var MAX_AGE_MS2 = 24 * 60 * 60 * 1e3;
3353
+ var storage3 = () => {
3354
+ if (typeof window === "undefined") return null;
3355
+ try {
3356
+ return window.localStorage;
3357
+ } catch {
3358
+ return null;
3359
+ }
3360
+ };
3361
+ var keyFor2 = (orderHash) => `${KEY_PREFIX3}.${orderHash}`;
3362
+ var listeners = /* @__PURE__ */ new Set();
3363
+ function subscribeWithdrawSwaps(listener) {
3364
+ listeners.add(listener);
3365
+ return () => {
3366
+ listeners.delete(listener);
3367
+ };
3368
+ }
3369
+ var notify = () => {
3370
+ for (const listener of listeners) {
3106
3371
  try {
3107
- const balance = await readBalance();
3108
- if (balance > baseline) {
3109
- const arrived = balance - baseline;
3110
- debugLog("owney-sdk", "withdraw: funds landed", {
3111
- arrived: arrived.toString()
3112
- });
3113
- return arrived;
3372
+ listener();
3373
+ } catch {
3374
+ }
3375
+ }
3376
+ };
3377
+ function saveWithdrawSwap(record) {
3378
+ const store = storage3();
3379
+ if (!store) return;
3380
+ try {
3381
+ store.setItem(keyFor2(record.orderHash), JSON.stringify(record));
3382
+ } catch {
3383
+ return;
3384
+ }
3385
+ notify();
3386
+ }
3387
+ function updateWithdrawSwap(orderHash, patch) {
3388
+ const store = storage3();
3389
+ if (!store) return;
3390
+ try {
3391
+ const raw = store.getItem(keyFor2(orderHash));
3392
+ if (!raw) return;
3393
+ const current = JSON.parse(raw);
3394
+ const next = { ...current, ...patch };
3395
+ if (next.status !== "swapping" && current.status === "swapping" && next.settledAt === void 0) {
3396
+ next.settledAt = Date.now();
3397
+ }
3398
+ store.setItem(keyFor2(orderHash), JSON.stringify(next));
3399
+ } catch {
3400
+ return;
3401
+ }
3402
+ notify();
3403
+ }
3404
+ function clearWithdrawSwap(orderHash) {
3405
+ const store = storage3();
3406
+ if (!store) return;
3407
+ try {
3408
+ store.removeItem(keyFor2(orderHash));
3409
+ } catch {
3410
+ return;
3411
+ }
3412
+ notify();
3413
+ }
3414
+ function listWithdrawSwaps(now = Date.now()) {
3415
+ const store = storage3();
3416
+ if (!store) return [];
3417
+ const out = [];
3418
+ try {
3419
+ const keys = [];
3420
+ for (let i = 0; i < store.length; i++) {
3421
+ const key2 = store.key(i);
3422
+ if (key2?.startsWith(`${KEY_PREFIX3}.`)) keys.push(key2);
3423
+ }
3424
+ for (const key2 of keys) {
3425
+ const raw = store.getItem(key2);
3426
+ if (!raw) continue;
3427
+ try {
3428
+ const parsed = JSON.parse(raw);
3429
+ if (now - parsed.createdAt > MAX_AGE_MS2) {
3430
+ store.removeItem(key2);
3431
+ continue;
3432
+ }
3433
+ out.push(parsed);
3434
+ } catch {
3435
+ store.removeItem(key2);
3114
3436
  }
3115
- } catch (error) {
3116
- lastError = error;
3117
- debugLog("owney-sdk", "withdraw: balance read failed, retrying", {
3118
- message: error instanceof Error ? error.message : String(error)
3119
- });
3120
3437
  }
3121
- if (Date.now() >= deadline) {
3122
- throw new OwneyError(
3123
- "WITHDRAW_ARRIVAL_TIMEOUT",
3124
- "The withdrawal was accepted but the funds had not arrived in time to swap them. They are on their way to your wallet in the original asset.",
3125
- {
3126
- baseline: baseline.toString(),
3127
- waitedMs: timeoutMs,
3128
- ...lastError ? {
3129
- lastReadError: lastError instanceof Error ? lastError.message : String(lastError)
3130
- } : {}
3438
+ } catch {
3439
+ return out;
3440
+ }
3441
+ return out.sort((a, b) => b.createdAt - a.createdAt);
3442
+ }
3443
+
3444
+ // src/lib/swap/swap.pending-deposit.ts
3445
+ var KEY_PREFIX4 = "owney.swap.pending-deposit";
3446
+ var MAX_AGE_MS3 = 24 * 60 * 60 * 1e3;
3447
+ var storage4 = () => {
3448
+ if (typeof window === "undefined") return null;
3449
+ try {
3450
+ return window.localStorage;
3451
+ } catch {
3452
+ return null;
3453
+ }
3454
+ };
3455
+ var keyFor3 = (id) => `${KEY_PREFIX4}.${id}`;
3456
+ function savePendingDeposit(entry) {
3457
+ const store = storage4();
3458
+ if (!store) return;
3459
+ try {
3460
+ store.setItem(keyFor3(entry.id), JSON.stringify(entry));
3461
+ } catch {
3462
+ return;
3463
+ }
3464
+ }
3465
+ function clearPendingDeposit(id) {
3466
+ const store = storage4();
3467
+ if (!store) return;
3468
+ try {
3469
+ store.removeItem(keyFor3(id));
3470
+ } catch {
3471
+ return;
3472
+ }
3473
+ }
3474
+ function listPendingDeposits(now = Date.now()) {
3475
+ const store = storage4();
3476
+ if (!store) return [];
3477
+ const out = [];
3478
+ try {
3479
+ const keys = [];
3480
+ for (let i = 0; i < store.length; i++) {
3481
+ const key2 = store.key(i);
3482
+ if (key2?.startsWith(`${KEY_PREFIX4}.`)) keys.push(key2);
3483
+ }
3484
+ for (const key2 of keys) {
3485
+ const raw = store.getItem(key2);
3486
+ if (!raw) continue;
3487
+ try {
3488
+ const parsed = JSON.parse(raw);
3489
+ if (now - parsed.createdAt > MAX_AGE_MS3) {
3490
+ store.removeItem(key2);
3491
+ continue;
3131
3492
  }
3132
- );
3493
+ out.push(parsed);
3494
+ } catch {
3495
+ store.removeItem(key2);
3496
+ }
3133
3497
  }
3134
- await sleep(pollMs);
3498
+ } catch {
3499
+ return out;
3135
3500
  }
3501
+ return out.sort((a, b) => b.createdAt - a.createdAt);
3136
3502
  }
3137
3503
 
3138
3504
  // src/lib/health-report.ts
@@ -3326,7 +3692,7 @@ function aggregateApyByChainAndAsset(agentApys, agentBalances) {
3326
3692
 
3327
3693
  // src/client.ts
3328
3694
  var import_viem9 = require("viem");
3329
- var import_chains2 = require("viem/chains");
3695
+ var import_chains3 = require("viem/chains");
3330
3696
 
3331
3697
  // src/lib/transfer-auth.ts
3332
3698
  var import_viem7 = require("viem");
@@ -3367,10 +3733,10 @@ function randomAuthNonce() {
3367
3733
  // src/lib/sponsor-client.ts
3368
3734
  var ROUTING_API_BASE_URL3 = "https://owney-routing-api-243946518160.europe-west4.run.app";
3369
3735
  async function postSponsorTransferAuth(input) {
3370
- const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3736
+ const base4 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3371
3737
  let res;
3372
3738
  try {
3373
- res = await fetch(`${base3}/api/v1/sponsor/erc20-transfer-auth`, {
3739
+ res = await fetch(`${base4}/api/v1/sponsor/erc20-transfer-auth`, {
3374
3740
  method: "POST",
3375
3741
  headers: {
3376
3742
  "content-type": "application/json",
@@ -3407,10 +3773,10 @@ async function postSponsorTransferAuth(input) {
3407
3773
  return parsed.data;
3408
3774
  }
3409
3775
  async function postSponsorPermit2Transfer(input) {
3410
- const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3776
+ const base4 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3411
3777
  let res;
3412
3778
  try {
3413
- res = await fetch(`${base3}/api/v1/sponsor/permit2-transfer`, {
3779
+ res = await fetch(`${base4}/api/v1/sponsor/permit2-transfer`, {
3414
3780
  method: "POST",
3415
3781
  headers: {
3416
3782
  "content-type": "application/json",
@@ -3445,11 +3811,11 @@ async function postSponsorPermit2Transfer(input) {
3445
3811
  return parsed.data;
3446
3812
  }
3447
3813
  async function getSponsorRelayerAddress(input) {
3448
- const base3 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3814
+ const base4 = input.baseUrl ?? ROUTING_API_BASE_URL3;
3449
3815
  let res;
3450
3816
  try {
3451
3817
  res = await fetch(
3452
- `${base3}/api/v1/sponsor/relayer-address?chainId=${input.chainId}`,
3818
+ `${base4}/api/v1/sponsor/relayer-address?chainId=${input.chainId}`,
3453
3819
  {
3454
3820
  headers: { "x-owney-api-key": input.apiKey }
3455
3821
  }
@@ -3734,6 +4100,7 @@ function makeSponsoredCallsCallback(deps) {
3734
4100
  }
3735
4101
 
3736
4102
  // src/client.ts
4103
+ var WALLET_CATCHUP_TIMEOUT_MS = 3e4;
3737
4104
  function encodeMultiAgentCursor(map) {
3738
4105
  return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
3739
4106
  }
@@ -3760,9 +4127,9 @@ var SPONSORED_USDC_BY_CHAIN = {
3760
4127
  1: "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
3761
4128
  };
3762
4129
  var VIEM_CHAIN2 = {
3763
- 8453: import_chains2.base,
3764
- 42161: import_chains2.arbitrum,
3765
- 1: import_chains2.mainnet
4130
+ 8453: import_chains3.base,
4131
+ 42161: import_chains3.arbitrum,
4132
+ 1: import_chains3.mainnet
3766
4133
  };
3767
4134
  var SPONSORED_WETH_BY_CHAIN = {
3768
4135
  8453: "0x4200000000000000000000000000000000000006",
@@ -4551,7 +4918,7 @@ var OwneySDK = class {
4551
4918
  async ensureSwapChain(chainId) {
4552
4919
  const provider = this.requireConnectedProvider();
4553
4920
  const state = this.requireState();
4554
- const chain = VIEM_CHAIN2[chainId];
4921
+ const chain = swapChain(chainId);
4555
4922
  if (!chain) {
4556
4923
  throw new OwneyError(
4557
4924
  "CHAIN_UNSUPPORTED",
@@ -4569,6 +4936,111 @@ var OwneySDK = class {
4569
4936
  chainId
4570
4937
  );
4571
4938
  }
4939
+ /**
4940
+ * Turn a native-source cross-chain quote into an ERC-20 one.
4941
+ *
4942
+ * Fusion+ cannot escrow native value, so the quote arrives with
4943
+ * `requiresOnchainOrder` set and the relayer would refuse the order after
4944
+ * the user signed it (ROUT-242). Wrapping first costs one transaction and
4945
+ * puts the swap back on the ERC-20 rail that already works, rather than
4946
+ * adding a second order type that would need its own escrow handling.
4947
+ *
4948
+ * Re-quoted afterwards rather than patched: the amount wrapped may be less
4949
+ * than the amount quoted (gas has to come out of the same balance), and
4950
+ * every executor dep — allowance, permit, balances — is derived from the
4951
+ * quote's source token. A quote naming ETH would have all of them reading
4952
+ * the wrong asset.
4953
+ */
4954
+ async wrapNativeSource(quote, walletAddress, onStage, direction) {
4955
+ const wrapper = requireWrapper(quote);
4956
+ const chainId = quote.src.chainId;
4957
+ const chain = swapChain(chainId);
4958
+ const provider = this.requireConnectedProvider();
4959
+ const publicClient = (0, import_viem9.createPublicClient)({
4960
+ chain,
4961
+ transport: swapReadTransport(chainId, this.zyfaiRpcUrls)
4962
+ });
4963
+ const wallet = (0, import_viem9.createWalletClient)({
4964
+ account: walletAddress,
4965
+ chain,
4966
+ transport: (0, import_viem9.custom)(provider)
4967
+ });
4968
+ onStage?.("wrapping");
4969
+ const { wrapped } = await wrapNative(
4970
+ {
4971
+ readNativeBalance: () => publicClient.getBalance({
4972
+ address: walletAddress
4973
+ }),
4974
+ estimateWrapGas: (to, value) => publicClient.estimateGas({
4975
+ account: walletAddress,
4976
+ to,
4977
+ data: WRAP_SELECTOR,
4978
+ value
4979
+ }),
4980
+ // The 1559 ceiling, not the spot price: a wallet bills against the
4981
+ // former and the two differ wildly on a quiet chain.
4982
+ getMaxFeePerGas: async () => {
4983
+ const fees = await publicClient.estimateFeesPerGas();
4984
+ return fees.maxFeePerGas ?? publicClient.getGasPrice();
4985
+ },
4986
+ sendTransaction: async (tx, onSubmitted) => {
4987
+ const hash = await wallet.sendTransaction({
4988
+ to: tx.to,
4989
+ data: tx.data,
4990
+ value: BigInt(tx.value),
4991
+ account: walletAddress,
4992
+ chain
4993
+ });
4994
+ onSubmitted?.(hash);
4995
+ const receipt = await publicClient.waitForTransactionReceipt({
4996
+ hash,
4997
+ confirmations: 1,
4998
+ timeout: receiptTimeoutMs(chainId)
4999
+ });
5000
+ if (receipt.status !== "success") {
5001
+ throw new OwneyError(
5002
+ "SWAP_REQUEST_FAILED",
5003
+ `Wrapping your ${quote.src.symbol} failed (tx ${hash}). Nothing was swapped.`,
5004
+ { hash }
5005
+ );
5006
+ }
5007
+ return hash;
5008
+ },
5009
+ ensureChain: (id) => this.ensureSwapChain(id)
5010
+ },
5011
+ {
5012
+ chainId,
5013
+ wrapper: wrapper.address,
5014
+ nativeSymbol: quote.src.symbol,
5015
+ requested: BigInt(quote.src.amount),
5016
+ onSubmitted: () => onStage?.("wrapped")
5017
+ }
5018
+ );
5019
+ debugLog("owney-sdk", "swap: wrapped native source", {
5020
+ symbol: wrapper.symbol,
5021
+ amount: wrapped.toString()
5022
+ });
5023
+ try {
5024
+ return await this.swapApi().quote({
5025
+ from: { chainId, symbol: wrapper.symbol, amount: wrapped.toString() },
5026
+ to: { chainId: quote.dst.chainId, symbol: quote.dst.symbol },
5027
+ walletAddress,
5028
+ ...direction ? { direction } : {}
5029
+ });
5030
+ } catch (error) {
5031
+ throw new OwneyError(
5032
+ "SWAP_REQUEST_FAILED",
5033
+ `Your ${quote.src.symbol} was wrapped to ${wrapper.symbol}, but the swap couldn't be priced. The funds are in your wallet as ${wrapper.symbol} \u2014 swap that instead, no need to wrap again.`,
5034
+ {
5035
+ wrappedSymbol: wrapper.symbol,
5036
+ wrappedAmount: wrapped.toString(),
5037
+ chainId,
5038
+ cause: error instanceof Error ? error.message : String(error),
5039
+ ...error instanceof OwneyError ? { causeCode: error.code } : {}
5040
+ }
5041
+ );
5042
+ }
5043
+ }
4572
5044
  /**
4573
5045
  * Binds the executor's abstract deps to this client's wallet.
4574
5046
  *
@@ -4578,8 +5050,8 @@ var OwneySDK = class {
4578
5050
  buildSwapDeps(quote) {
4579
5051
  const state = this.requireState();
4580
5052
  const provider = this.requireConnectedProvider();
4581
- const srcChain = VIEM_CHAIN2[quote.src.chainId];
4582
- const dstChain = VIEM_CHAIN2[quote.dst.chainId];
5053
+ const srcChain = swapChain(quote.src.chainId);
5054
+ const dstChain = swapChain(quote.dst.chainId);
4583
5055
  const wallet = (0, import_viem9.createWalletClient)({
4584
5056
  account: state.walletAddress,
4585
5057
  chain: srcChain,
@@ -4709,13 +5181,59 @@ var OwneySDK = class {
4709
5181
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
4710
5182
  now: () => Date.now()
4711
5183
  },
4712
- runner: {
4713
- readyForSecrets: (h) => this.swapApi().readyForSecrets(h),
4714
- submitSecret: (h, secret) => this.swapApi().submitSecret(h, secret),
4715
- orderStatus: (h) => this.swapApi().orderStatus(h),
4716
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
4717
- now: () => Date.now()
4718
- }
5184
+ runner: this.swapRunnerDeps()
5185
+ };
5186
+ }
5187
+ /**
5188
+ * Waits until the WALLET'S OWN node reports at least `amount` of `token`.
5189
+ *
5190
+ * Separate from the swap's arrival measurement on purpose: that one runs on
5191
+ * a pinned HTTP RPC, and what matters here is the view the deposit will
5192
+ * actually use. Returns whether it got there — a courtesy, not a gate, since
5193
+ * the deposit's own check is the authority and refusing to even attempt
5194
+ * would strand funds we might have been able to move.
5195
+ */
5196
+ async walletSeesBalance(chainId, token, amount) {
5197
+ const provider = this.requireConnectedProvider();
5198
+ const state = this.requireState();
5199
+ const pub = (0, import_viem9.createPublicClient)({
5200
+ chain: swapChain(chainId),
5201
+ transport: (0, import_viem9.custom)(provider)
5202
+ });
5203
+ const { arrived } = await awaitBalanceIncrease({
5204
+ readBalance: () => pub.readContract({
5205
+ address: token,
5206
+ abi: ERC20_ALLOWANCE_ABI,
5207
+ functionName: "balanceOf",
5208
+ args: [state.walletAddress]
5209
+ }),
5210
+ // `awaitBalanceIncrease` resolves on the first read STRICTLY above the
5211
+ // baseline, so one below the target means "at least the target".
5212
+ baseline: amount - 1n,
5213
+ timeoutMs: WALLET_CATCHUP_TIMEOUT_MS
5214
+ });
5215
+ return arrived !== null;
5216
+ }
5217
+ /**
5218
+ * Runs a quoted swap. A named seam rather than an inline `executeSwap` call
5219
+ * so the deposit half of `swapAndDeposit` can be exercised on its own.
5220
+ */
5221
+ runSwap(quote, options) {
5222
+ return executeSwap(this.buildSwapDeps(quote), { quote, ...options });
5223
+ }
5224
+ /**
5225
+ * The half of the swap deps that only ever talks to the routing API.
5226
+ *
5227
+ * Split out because resuming an order needs exactly this and nothing else —
5228
+ * no provider, no wallet client, no chain. See `resumePendingSwaps`.
5229
+ */
5230
+ swapRunnerDeps() {
5231
+ return {
5232
+ readyForSecrets: (h) => this.swapApi().readyForSecrets(h),
5233
+ submitSecret: (h, secret) => this.swapApi().submitSecret(h, secret),
5234
+ orderStatus: (h) => this.swapApi().orderStatus(h),
5235
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
5236
+ now: () => Date.now()
4719
5237
  };
4720
5238
  }
4721
5239
  /**
@@ -4727,6 +5245,167 @@ var OwneySDK = class {
4727
5245
  async getSwapTokens() {
4728
5246
  return this.swapApi().listTokens();
4729
5247
  }
5248
+ /**
5249
+ * Swaps that landed but were never deposited, newest first.
5250
+ *
5251
+ * The money is already in the wallet in the right asset — what is missing is
5252
+ * an ordinary deposit, which is why this needs no order and no signature to
5253
+ * describe. See `completePendingDeposit`.
5254
+ */
5255
+ listPendingDeposits() {
5256
+ return listPendingDeposits();
5257
+ }
5258
+ /**
5259
+ * Backgrounded withdrawal swaps and how they ended, newest first.
5260
+ *
5261
+ * Nothing to act on — unlike `listPendingDeposits`, which describes a job the
5262
+ * user can finish. This is a watch: the funds are in escrow and the only
5263
+ * open question is where they land. See `swap.withdraw-swap.ts`.
5264
+ */
5265
+ listWithdrawSwaps() {
5266
+ return listWithdrawSwaps();
5267
+ }
5268
+ /**
5269
+ * Retire a settled record. The user has read the outcome.
5270
+ *
5271
+ * Only they do this — a record that disappears on its own takes with it the
5272
+ * only thing telling someone where their money went.
5273
+ */
5274
+ dismissWithdrawSwap(orderHash) {
5275
+ clearWithdrawSwap(orderHash);
5276
+ }
5277
+ /**
5278
+ * Deposit a swap that already landed.
5279
+ *
5280
+ * Nothing is swapped again: the funds are in the wallet, so this is the
5281
+ * second half of `swapAndDeposit` on its own. Cleared only once the deposit
5282
+ * has actually gone through — a failure here leaves the record in place so it
5283
+ * can be offered again rather than silently dropped.
5284
+ */
5285
+ async completePendingDeposit(id) {
5286
+ const entry = listPendingDeposits().find((p) => p.id === id);
5287
+ if (!entry) {
5288
+ throw new OwneyError(
5289
+ "SWAP_REQUEST_FAILED",
5290
+ "That swap is no longer waiting to be added.",
5291
+ { id }
5292
+ );
5293
+ }
5294
+ await this.ensureSwapChain(entry.chainId);
5295
+ const deposit = await this.deposit({
5296
+ amount: entry.received,
5297
+ asset: entry.symbol,
5298
+ ...entry.agentId ? { agentId: entry.agentId } : {}
5299
+ });
5300
+ clearPendingDeposit(entry.id);
5301
+ return deposit;
5302
+ }
5303
+ /**
5304
+ * Pick up cross-chain swaps a previous session left in flight.
5305
+ *
5306
+ * A Fusion+ order is only finished when the client publishes a secret for
5307
+ * each fill, once the escrows exist — so a user who closed the tab mid-swap
5308
+ * leaves an order nobody will ever complete, and it expires and refunds
5309
+ * instead of arriving. The preimages are stored for exactly this (24h sweep,
5310
+ * see the secret store); this is the other half.
5311
+ *
5312
+ * Needs NO wallet, deliberately. The signature already happened and the funds
5313
+ * are already escrowed, so finishing is pure API work — demanding a reconnect
5314
+ * first would strand the people it exists for.
5315
+ *
5316
+ * Every order is attempted even if an earlier one throws: they are unrelated
5317
+ * escrows, and one ending badly must not abandon the next one's secrets.
5318
+ * `unfinished` is not a verdict — the order may still settle, so unless the
5319
+ * chain has said refunded or cancelled its preimages are kept.
5320
+ */
5321
+ async resumePendingSwaps(options = {}) {
5322
+ const pending = listOrders();
5323
+ if (pending.length === 0) {
5324
+ await this.resumeSameChainSwaps(options);
5325
+ return [];
5326
+ }
5327
+ const runner = this.swapRunnerDeps();
5328
+ const results = [];
5329
+ for (const order of pending) {
5330
+ try {
5331
+ await runFusionOrder(runner, {
5332
+ orderHash: order.orderHash,
5333
+ secrets: order.secrets,
5334
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
5335
+ ...options.onStage ? {
5336
+ onStage: (stage) => options.onStage(order.orderHash, stage)
5337
+ } : {}
5338
+ });
5339
+ clearOrder(order.orderHash);
5340
+ updateWithdrawSwap(order.orderHash, { status: "landed" });
5341
+ results.push({
5342
+ orderHash: order.orderHash,
5343
+ status: "completed"
5344
+ });
5345
+ } catch (error) {
5346
+ if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" || error.code === "SWAP_ORDER_CANCELLED")) {
5347
+ clearOrder(order.orderHash);
5348
+ updateWithdrawSwap(order.orderHash, { status: "refunded" });
5349
+ } else {
5350
+ updateWithdrawSwap(order.orderHash, { status: "unknown" });
5351
+ }
5352
+ results.push({
5353
+ orderHash: order.orderHash,
5354
+ status: "unfinished",
5355
+ ...error instanceof OwneyError ? { error } : {}
5356
+ });
5357
+ }
5358
+ }
5359
+ await this.resumeSameChainSwaps(options);
5360
+ return results;
5361
+ }
5362
+ /**
5363
+ * Pick up SAME-CHAIN orders a previous session left in the auction.
5364
+ *
5365
+ * They are not in the secret store and never will be: that store exists to
5366
+ * keep preimages, and a same-chain fill needs none — the resolver takes the
5367
+ * maker's tokens and delivers the taker's in one transaction. So the only
5368
+ * record of one is the withdrawal record itself, which carries the order
5369
+ * hash, and that is all a resume needs here.
5370
+ *
5371
+ * Gentler than the Fusion+ case in the way that matters. Nothing is
5372
+ * escrowed, so an order nobody ever picks up leaves the wallet exactly as it
5373
+ * was — this is catching up on news, not rescuing funds.
5374
+ *
5375
+ * Same-chain is read off the record rather than stored as a rail: a
5376
+ * withdrawal whose source and destination share a chain could not have been
5377
+ * anything else.
5378
+ */
5379
+ async resumeSameChainSwaps(options = {}) {
5380
+ const running = listWithdrawSwaps().filter(
5381
+ (record) => record.status === "swapping" && record.srcChainId === record.dstChainId
5382
+ );
5383
+ for (const record of running) {
5384
+ const runner = {
5385
+ // The chain bound in. That product keys its orders per chain, and the
5386
+ // Fusion+ endpoint answers 404 for one — which would read as an order
5387
+ // that vanished rather than one still in the auction.
5388
+ orderStatus: (h) => this.swapApi().orderStatus(h, record.srcChainId),
5389
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
5390
+ now: () => Date.now()
5391
+ };
5392
+ try {
5393
+ await runSameChainOrder(runner, {
5394
+ orderHash: record.orderHash,
5395
+ ...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs },
5396
+ ...options.onStage ? {
5397
+ onStage: (stage) => options.onStage(record.orderHash, stage)
5398
+ } : {}
5399
+ });
5400
+ updateWithdrawSwap(record.orderHash, { status: "landed" });
5401
+ } catch (error) {
5402
+ const code = error instanceof OwneyError ? error.code : void 0;
5403
+ updateWithdrawSwap(record.orderHash, {
5404
+ status: code === "SWAP_ORDER_EXPIRED" || code === "SWAP_ORDER_CANCELLED" ? "refunded" : "unknown"
5405
+ });
5406
+ }
5407
+ }
5408
+ }
4730
5409
  /**
4731
5410
  * What the wallet actually holds, across every supported chain, restricted
4732
5411
  * to tokens a swap could use.
@@ -4773,15 +5452,19 @@ var OwneySDK = class {
4773
5452
  * tokens can share a ticker, and `providers` (how many token lists carry the
4774
5453
  * address) is the only usable signal for telling them apart. Surface it.
4775
5454
  *
4776
- * Returns nothing for a blank query rather than asking for the whole list.
5455
+ * A blank query WITH a chainId lists that chain's catalogue instead of
5456
+ * searching it — what a picker wants when someone selects a chain before
5457
+ * typing anything. Blank with no chain returns nothing: that would be asking
5458
+ * for the top of every catalogue at once, which is a download, not a list.
4777
5459
  */
4778
5460
  async searchSwapTokens(params) {
4779
- const query = params.query.trim();
4780
- if (!query) return { tokens: [] };
5461
+ const query = params.query?.trim() ?? "";
5462
+ if (!query && params.chainId === void 0) return { tokens: [] };
4781
5463
  return this.swapApi().searchTokens({
4782
- query,
5464
+ ...query ? { query } : {},
4783
5465
  ...params.chainId === void 0 ? {} : { chainId: params.chainId },
4784
- ...params.limit === void 0 ? {} : { limit: params.limit }
5466
+ ...params.limit === void 0 ? {} : { limit: params.limit },
5467
+ ...params.direction === void 0 ? {} : { direction: params.direction }
4785
5468
  });
4786
5469
  }
4787
5470
  /**
@@ -4820,26 +5503,56 @@ var OwneySDK = class {
4820
5503
  async swapAndDeposit(options) {
4821
5504
  const state = this.requireState();
4822
5505
  const api = this.swapApi();
4823
- const quote = await api.quote({
5506
+ const quoted = await api.quote({
4824
5507
  from: options.from,
4825
5508
  to: options.to,
4826
5509
  walletAddress: state.walletAddress
4827
5510
  });
5511
+ const quote = quoted.requiresOnchainOrder ? await this.wrapNativeSource(
5512
+ quoted,
5513
+ state.walletAddress,
5514
+ options.onSwapProgress
5515
+ ) : quoted;
4828
5516
  await this.ensureSwapChain(quote.src.chainId);
4829
- const swap = await executeSwap(this.buildSwapDeps(quote), {
4830
- quote,
5517
+ const swap = await this.runSwap(quote, {
4831
5518
  walletAddress: state.walletAddress,
4832
5519
  ...options.slippage === void 0 ? {} : { slippage: options.slippage },
4833
5520
  ...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
4834
5521
  });
4835
5522
  options.onSwapProgress?.("depositing");
4836
- await this.ensureSwapChain(quote.dst.chainId);
4837
- const deposit = await this.deposit({
4838
- amount: swap.received,
4839
- asset: options.to.symbol,
4840
- ...options.agentId ? { agentId: options.agentId } : {}
4841
- });
4842
- return { swap, deposit };
5523
+ try {
5524
+ await this.ensureSwapChain(quote.dst.chainId);
5525
+ await this.walletSeesBalance(
5526
+ quote.dst.chainId,
5527
+ quote.dst.address,
5528
+ BigInt(swap.received)
5529
+ );
5530
+ const deposit = await this.deposit({
5531
+ amount: swap.received,
5532
+ asset: options.to.symbol,
5533
+ ...options.agentId ? { agentId: options.agentId } : {}
5534
+ });
5535
+ return { swap, deposit };
5536
+ } catch (error) {
5537
+ const pending = {
5538
+ id: `${quote.dst.chainId}-${options.to.symbol}-${Date.now()}`,
5539
+ received: swap.received,
5540
+ symbol: options.to.symbol,
5541
+ chainId: quote.dst.chainId,
5542
+ ...options.agentId ? { agentId: options.agentId } : {},
5543
+ createdAt: Date.now()
5544
+ };
5545
+ savePendingDeposit(pending);
5546
+ throw new OwneyError(
5547
+ "SWAP_DEPOSIT_PENDING",
5548
+ `The swap went through and your ${options.to.symbol} is in your wallet, but adding it to the agent didn't complete. Nothing needs swapping again.`,
5549
+ {
5550
+ ...pending,
5551
+ cause: error instanceof Error ? error.message : String(error),
5552
+ ...error instanceof OwneyError ? { causeCode: error.code } : {}
5553
+ }
5554
+ );
5555
+ }
4843
5556
  }
4844
5557
  /**
4845
5558
  * Withdraw from an agent and swap the proceeds into whatever the user wants
@@ -4928,7 +5641,14 @@ var OwneySDK = class {
4928
5641
  walletAddress: state.walletAddress,
4929
5642
  direction: "withdraw",
4930
5643
  ...options.slippage === void 0 ? {} : { slippage: options.slippage },
4931
- ...options.onSwapProgress ? { onStage: options.onSwapProgress } : {}
5644
+ ...options.onSwapProgress ? { onStage: options.onSwapProgress } : {},
5645
+ ...options.onOrderSubmitted ? {
5646
+ onOrderSubmitted: (orderHash) => options.onOrderSubmitted({
5647
+ orderHash,
5648
+ withdrawn,
5649
+ expected: quote.dst.amount
5650
+ })
5651
+ } : {}
4932
5652
  });
4933
5653
  return { withdraw, withdrawn, swap };
4934
5654
  } catch (error) {
@@ -5687,8 +6407,8 @@ var import_siwe = require("siwe");
5687
6407
  var import_sdk2 = require("@zyfai/sdk");
5688
6408
 
5689
6409
  // src/agents/zyfai/zyfai.siwx-cache.ts
5690
- var KEY_PREFIX3 = "owney.siwx.session";
5691
- var storage3 = () => {
6410
+ var KEY_PREFIX5 = "owney.siwx.session";
6411
+ var storage5 = () => {
5692
6412
  if (typeof window === "undefined") return null;
5693
6413
  try {
5694
6414
  return window.localStorage;
@@ -5696,8 +6416,8 @@ var storage3 = () => {
5696
6416
  return null;
5697
6417
  }
5698
6418
  };
5699
- var buildKey2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}`;
5700
- var legacyKeyPrefix2 = (address) => `${KEY_PREFIX3}:${address.toLowerCase()}:`;
6419
+ var buildKey2 = (address) => `${KEY_PREFIX5}:${address.toLowerCase()}`;
6420
+ var legacyKeyPrefix2 = (address) => `${KEY_PREFIX5}:${address.toLowerCase()}:`;
5701
6421
  var memorySiwxSessions = /* @__PURE__ */ new Map();
5702
6422
  var readLegacySiwxSession = (store, address) => {
5703
6423
  if (!store) return null;
@@ -5729,7 +6449,7 @@ var readLegacySiwxSession = (store, address) => {
5729
6449
  var readSiwxSession = (address, chainId) => {
5730
6450
  if (typeof window === "undefined") return null;
5731
6451
  const key2 = buildKey2(address);
5732
- const store = storage3();
6452
+ const store = storage5();
5733
6453
  let raw = null;
5734
6454
  try {
5735
6455
  raw = store?.getItem(key2) ?? null;
@@ -5759,7 +6479,7 @@ var writeSiwxSession = (address, _chainId, session) => {
5759
6479
  if (typeof window === "undefined") return;
5760
6480
  const key2 = buildKey2(address);
5761
6481
  memorySiwxSessions.set(key2, session);
5762
- const store = storage3();
6482
+ const store = storage5();
5763
6483
  try {
5764
6484
  store?.setItem(key2, JSON.stringify(session));
5765
6485
  } catch {
@@ -5768,7 +6488,7 @@ var writeSiwxSession = (address, _chainId, session) => {
5768
6488
  var clearSiwxSession = (address, _chainId) => {
5769
6489
  const key2 = buildKey2(address);
5770
6490
  memorySiwxSessions.delete(key2);
5771
- const store = storage3();
6491
+ const store = storage5();
5772
6492
  try {
5773
6493
  store?.removeItem(key2);
5774
6494
  } catch {
@@ -5901,7 +6621,13 @@ function createOwneySIWX(config) {
5901
6621
  NotConnectedError,
5902
6622
  OwneyError,
5903
6623
  OwneySDK,
6624
+ clearWithdrawSwap,
5904
6625
  createOwneySIWX,
6626
+ listPendingDeposits,
5905
6627
  listPendingSwaps,
5906
- setOwneyDebug
6628
+ listWithdrawSwaps,
6629
+ saveWithdrawSwap,
6630
+ setOwneyDebug,
6631
+ subscribeWithdrawSwaps,
6632
+ updateWithdrawSwap
5907
6633
  });