@owney/sdk 0.7.32-beta.4 → 0.7.32-beta.5

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
@@ -1653,7 +1653,7 @@ var SnapshotHistory = class {
1653
1653
  };
1654
1654
 
1655
1655
  // src/lib/funding-ledger.ts
1656
- var SDK_VERSION = "0.7.32-beta.4";
1656
+ var SDK_VERSION = "0.7.32-beta.5";
1657
1657
  var SCOPE2 = "funding-ledger";
1658
1658
  var REQUEST_TIMEOUT_MS2 = 5e3;
1659
1659
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -1670,6 +1670,12 @@ function normalizeAppName(appName) {
1670
1670
  const lower = appName.toLowerCase();
1671
1671
  return APP_NAME_RE.test(lower) ? lower : void 0;
1672
1672
  }
1673
+ var BATCH_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1674
+ function normalizeBatchId(batchId) {
1675
+ if (typeof batchId !== "string") return void 0;
1676
+ const lower = batchId.toLowerCase();
1677
+ return BATCH_ID_RE.test(lower) ? lower : void 0;
1678
+ }
1673
1679
  function compact(obj) {
1674
1680
  const out = {};
1675
1681
  for (const [key2, value] of Object.entries(obj)) {
@@ -1805,6 +1811,7 @@ function buildReporter(config) {
1805
1811
  asset: input.asset.toLowerCase(),
1806
1812
  requestedAmountRaw: input.requestedAmountRaw,
1807
1813
  isMax: input.isMax,
1814
+ batchId: normalizeBatchId(input.batchId),
1808
1815
  sdkVersion: SDK_VERSION,
1809
1816
  app,
1810
1817
  legs: input.legs?.map((leg) => compact({ ...leg }))
@@ -1814,9 +1821,16 @@ function buildReporter(config) {
1814
1821
  debugLog(SCOPE2, `task failed: ${describeError2(err)}`);
1815
1822
  });
1816
1823
  };
1824
+ let postBody = createBody;
1817
1825
  const create = async () => {
1818
1826
  if (disabled) return false;
1819
- const res = await request2("POST", endpoint2, createBody);
1827
+ let res = await request2("POST", endpoint2, postBody);
1828
+ if (res?.status === 400 && "batchId" in postBody) {
1829
+ const { batchId: _dropped, ...withoutBatchId } = postBody;
1830
+ postBody = withoutBatchId;
1831
+ debugLog(SCOPE2, "create rejected with 400: retrying once without batchId");
1832
+ res = await request2("POST", endpoint2, postBody);
1833
+ }
1820
1834
  if (!res) return false;
1821
1835
  if (res.status === 404) {
1822
1836
  disabled = true;
@@ -2997,6 +3011,36 @@ async function ensureWalletOnChain(pub, wallet, expected, options = {}) {
2997
3011
  { expectedChainId: expected, actualChainId: after ?? actual }
2998
3012
  );
2999
3013
  }
3014
+ function isActiveChainMismatch(error) {
3015
+ const message = error instanceof Error ? error.message : String(error ?? "");
3016
+ return /must match the active chain/i.test(message) || /does not match the target chain/i.test(message);
3017
+ }
3018
+ async function signWithChainRetry(pub, wallet, expected, sign) {
3019
+ try {
3020
+ return await sign();
3021
+ } catch (error) {
3022
+ if (!isActiveChainMismatch(error)) throw error;
3023
+ try {
3024
+ await wallet.switchChain({ id: expected });
3025
+ } catch {
3026
+ }
3027
+ try {
3028
+ return await sign();
3029
+ } catch (retryError) {
3030
+ if (!isActiveChainMismatch(retryError)) throw retryError;
3031
+ const actual = await readChainId(pub);
3032
+ throw new OwneyError(
3033
+ "CHAIN_MISMATCH",
3034
+ `Your wallet would not sign for ${chainName(expected)}. Open it, switch to ${chainName(expected)}, and try again.`,
3035
+ {
3036
+ expectedChainId: expected,
3037
+ ...actual !== void 0 ? { actualChainId: actual } : {},
3038
+ cause: retryError instanceof Error ? retryError.message : String(retryError)
3039
+ }
3040
+ );
3041
+ }
3042
+ }
3043
+ }
3000
3044
 
3001
3045
  // src/lib/sponsored-deposit.ts
3002
3046
  var AUTH_WINDOW_SECONDS = 15 * 60;
@@ -3524,6 +3568,9 @@ var NAME_TO_CHAIN_ID = Object.entries(
3524
3568
  acc[name.toLowerCase()] = Number(id);
3525
3569
  return acc;
3526
3570
  }, {});
3571
+ NAME_TO_CHAIN_ID.mainnet = 1;
3572
+ NAME_TO_CHAIN_ID["ethereum mainnet"] = 1;
3573
+ NAME_TO_CHAIN_ID["arbitrum one"] = 42161;
3527
3574
  function resolveChainId(chain2) {
3528
3575
  const asNum = Number(chain2);
3529
3576
  if (Number.isFinite(asNum) && asNum > 0) return asNum;
@@ -3774,7 +3821,7 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
3774
3821
  let weightedSum = 0;
3775
3822
  let totalBalance = 0;
3776
3823
  for (const p of entry.positions ?? []) {
3777
- if (p.chainId !== chainId) continue;
3824
+ if (chainId !== void 0 && p.chainId !== chainId) continue;
3778
3825
  if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
3779
3826
  const balance = p.balance ?? 0;
3780
3827
  const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
@@ -3784,27 +3831,89 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
3784
3831
  }
3785
3832
  return totalBalance > 0 ? weightedSum / totalBalance : null;
3786
3833
  }
3787
- function mapApyHistory(raw2, chainId, tokenSymbol) {
3788
- const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => ({
3789
- date,
3790
- apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
3791
- // Provider position balances are treated as decimal amounts of the
3792
- // selected token. Carry its unit dynamically for every asset; never
3793
- // attach a token unit to an unscoped mix of assets.
3794
- ...tokenSymbol ? {
3795
- historicalBalance: {
3796
- amount: (entry.positions ?? []).filter(
3797
- (p) => p.chainId === chainId && p.tokenSymbol?.toUpperCase() === tokenSymbol.toUpperCase() && Number.isFinite(p.balance) && p.balance > 0 && Number.isFinite(p.apy_withFee ?? p.apy)
3798
- ).reduce((sum, p) => sum + p.balance, 0),
3799
- unit: tokenSymbol.toUpperCase()
3800
- }
3801
- } : {}
3802
- })).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
3834
+ function historyCoverage(raw2) {
3835
+ const chains = /* @__PURE__ */ new Map();
3836
+ const assets = /* @__PURE__ */ new Map();
3837
+ const pairs = /* @__PURE__ */ new Map();
3838
+ for (const date of Object.keys(raw2.history ?? {}).sort()) {
3839
+ void date;
3840
+ const seenChains = /* @__PURE__ */ new Set();
3841
+ const seenAssets = /* @__PURE__ */ new Set();
3842
+ const seenPairs = /* @__PURE__ */ new Map();
3843
+ for (const p of (raw2.history ?? {})[date].positions ?? []) {
3844
+ const balance = p.balance ?? 0;
3845
+ const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
3846
+ if (balance <= 0 || typeof apy !== "number") continue;
3847
+ seenChains.add(p.chainId);
3848
+ if (p.tokenSymbol) {
3849
+ const asset = p.tokenSymbol.toUpperCase();
3850
+ seenAssets.add(asset);
3851
+ seenPairs.set(`${p.chainId}:${asset}`, { chainId: p.chainId, asset });
3852
+ }
3853
+ }
3854
+ for (const c of seenChains) chains.set(c, (chains.get(c) ?? 0) + 1);
3855
+ for (const a of seenAssets) assets.set(a, (assets.get(a) ?? 0) + 1);
3856
+ for (const [key2, pair] of seenPairs) {
3857
+ pairs.set(key2, { ...pair, days: (pairs.get(key2)?.days ?? 0) + 1 });
3858
+ }
3859
+ }
3860
+ return {
3861
+ chains: [...chains].map(([chainId, days]) => ({ chainId, days })),
3862
+ assets: [...assets].map(([asset, days]) => ({ asset, days })),
3863
+ pairs: [...pairs.values()]
3864
+ };
3865
+ }
3866
+ function isEthToken(symbol2) {
3867
+ const upper = symbol2?.toUpperCase();
3868
+ return upper === "WETH" || upper === "ETH";
3869
+ }
3870
+ function holdsEthPosition(raw2) {
3871
+ return Object.values(raw2.history ?? {}).some((entry) => (entry.positions ?? []).some((p) => isEthToken(p.tokenSymbol)));
3872
+ }
3873
+ function usdPerToken(symbol2, ethUsd) {
3874
+ if (symbol2?.toUpperCase() === "USDC") return 1;
3875
+ return isEthToken(symbol2) ? ethUsd : void 0;
3876
+ }
3877
+ function dollarDay(entry, chainId, ethUsd) {
3878
+ let weightedSum = 0;
3879
+ let totalUsd = 0;
3880
+ for (const p of entry.positions ?? []) {
3881
+ if (chainId !== void 0 && p.chainId !== chainId) continue;
3882
+ const balance = p.balance ?? 0;
3883
+ const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
3884
+ if (balance <= 0 || typeof apy !== "number") continue;
3885
+ const price = usdPerToken(p.tokenSymbol, ethUsd);
3886
+ if (price === void 0) return void 0;
3887
+ weightedSum += apy * balance * price;
3888
+ totalUsd += balance * price;
3889
+ }
3890
+ return totalUsd > 0 ? { apy: weightedSum / totalUsd, usd: totalUsd } : void 0;
3891
+ }
3892
+ function mapApyHistory(raw2, chainId, tokenSymbol, ethUsd) {
3893
+ const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => {
3894
+ const dollars = tokenSymbol ? void 0 : dollarDay(entry, chainId, ethUsd);
3895
+ return {
3896
+ date,
3897
+ apy: dollars ? dollars.apy : rawPoolApyForChain(entry, chainId, tokenSymbol),
3898
+ // Provider position balances are treated as decimal amounts of the
3899
+ // selected token. Carry its unit dynamically for every asset; an
3900
+ // unscoped mix of assets is carried in dollars, or not at all.
3901
+ ...tokenSymbol ? {
3902
+ historicalBalance: {
3903
+ amount: (entry.positions ?? []).filter(
3904
+ (p) => (chainId === void 0 || p.chainId === chainId) && p.tokenSymbol?.toUpperCase() === tokenSymbol.toUpperCase() && Number.isFinite(p.balance) && p.balance > 0 && Number.isFinite(p.apy_withFee ?? p.apy)
3905
+ ).reduce((sum, p) => sum + p.balance, 0),
3906
+ unit: tokenSymbol.toUpperCase()
3907
+ }
3908
+ } : dollars ? { historicalBalance: { amount: dollars.usd, unit: "USD" } } : {}
3909
+ };
3910
+ }).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
3803
3911
  return {
3804
3912
  walletAddress: raw2.walletAddress,
3805
3913
  weightedApyAfterFee: raw2.weightedApyAfterFee ? sumTokenValues(raw2.weightedApyAfterFee) : void 0,
3806
3914
  apyByChainAndAsset: mapWeightedApyByChain(raw2.weightedApyAfterFeeByChain),
3807
- history
3915
+ history,
3916
+ coverage: historyCoverage(raw2)
3808
3917
  };
3809
3918
  }
3810
3919
  function splitOpportunity(opportunity) {
@@ -3825,6 +3934,9 @@ function mapEntries(rawEntries, chainId) {
3825
3934
  // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
3826
3935
  // the public HistoryAction union, so no consumer type change is needed.
3827
3936
  "Deposit to protocol": "Deposit",
3937
+ // Withdrawing from an async vault (Superform) is logged under its own
3938
+ // label and paid out later in a separate batch (ROUT-624).
3939
+ "Request async withdrawal": "Withdraw",
3828
3940
  Rebalance: "Rebalance"
3829
3941
  };
3830
3942
  void chainId;
@@ -3869,8 +3981,9 @@ function mapEntries(rawEntries, chainId) {
3869
3981
  ];
3870
3982
  }
3871
3983
  const mappedAction = (entry.action ? actionMap[entry.action] : void 0) ?? entry.action;
3984
+ const asyncRequest = entry.action === "Request async withdrawal";
3872
3985
  const rawAmount2 = entry?.positions?.[0]?.amount;
3873
- const hasAmount = mappedAction !== "Withdraw" && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
3986
+ const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
3874
3987
  const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
3875
3988
  entry?.positions?.[0]?.deltaAmount,
3876
3989
  tokenDecimals(entry?.positions?.[0]?.token_symbol)
@@ -3896,6 +4009,7 @@ function mapEntries(rawEntries, chainId) {
3896
4009
  newApy: newApy === null ? null : String(newApy),
3897
4010
  oldApy: oldApy === null ? null : String(oldApy),
3898
4011
  ...mappedPositions.length ? { positions: mappedPositions } : {},
4012
+ ...asyncRequest ? { asyncRequest: true } : {},
3899
4013
  transactions: [
3900
4014
  {
3901
4015
  txHashes: entry.transactionHash ? [entry.transactionHash] : [],
@@ -4055,6 +4169,43 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
4055
4169
  return { walletAddress: raw2.walletAddress, chainId, assets };
4056
4170
  }
4057
4171
 
4172
+ // src/lib/eth-usd-price.ts
4173
+ var BASE_ETH_USD_FEED = "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70";
4174
+ var FEED_DECIMALS = 8;
4175
+ var PRICE_TTL_MS = 6e4;
4176
+ var AGGREGATOR_V3_ABI = [{
4177
+ type: "function",
4178
+ name: "latestRoundData",
4179
+ stateMutability: "view",
4180
+ inputs: [],
4181
+ outputs: [
4182
+ { name: "roundId", type: "uint80" },
4183
+ { name: "answer", type: "int256" },
4184
+ { name: "startedAt", type: "uint256" },
4185
+ { name: "updatedAt", type: "uint256" },
4186
+ { name: "answeredInRound", type: "uint80" }
4187
+ ]
4188
+ }];
4189
+ var prices = /* @__PURE__ */ new WeakMap();
4190
+ async function readEthUsdPrice(client, now = Date.now()) {
4191
+ const cached = prices.get(client);
4192
+ if (cached && now - cached.at < PRICE_TTL_MS) return cached.value;
4193
+ try {
4194
+ const [, answer] = await client.readContract({
4195
+ address: BASE_ETH_USD_FEED,
4196
+ abi: AGGREGATOR_V3_ABI,
4197
+ functionName: "latestRoundData"
4198
+ });
4199
+ if (answer <= 0n) return void 0;
4200
+ const value = Number(answer) / 10 ** FEED_DECIMALS;
4201
+ if (!Number.isFinite(value)) return void 0;
4202
+ prices.set(client, { value, at: now });
4203
+ return value;
4204
+ } catch {
4205
+ return void 0;
4206
+ }
4207
+ }
4208
+
4058
4209
  // src/agents/zyfai/zyfai.history-cursor.ts
4059
4210
  var InvalidHistoryCursorError = class extends Error {
4060
4211
  code = "invalid_cursor";
@@ -4253,6 +4404,9 @@ function splittingNeedsUpdate(current, desired) {
4253
4404
  }
4254
4405
 
4255
4406
  // src/agents/zyfai/pool-policy.ts
4407
+ function orgPolicyForConnect(policy, userPoolCustomization) {
4408
+ return userPoolCustomization ? { ...policy, poolPolicy: null } : policy;
4409
+ }
4256
4410
  function toZyfaiCustomizations(policy, availableByProtocol, chainsByProtocol) {
4257
4411
  const selectionByKey = /* @__PURE__ */ new Map();
4258
4412
  for (const selection of policy.selections) {
@@ -4344,6 +4498,54 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
4344
4498
  if (desiredProtocols === null) return false;
4345
4499
  return !protocolListsEqual(current.protocols, desiredProtocols);
4346
4500
  }
4501
+ function mergeScopedPoolNames(current, scoped, allAvailableNames) {
4502
+ const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
4503
+ const existing = current.autoselect ? allAvailableNames : current.pools;
4504
+ const preserved = existing.filter((name) => !managed.has(name));
4505
+ const selected = scoped.flatMap((entry) => entry.pools);
4506
+ return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
4507
+ }
4508
+ function mapAvailablePools(raw2) {
4509
+ const byChain = raw2 ?? {};
4510
+ if (typeof byChain !== "object" || byChain === null) return [];
4511
+ const result = [];
4512
+ for (const [chainIdStr, byToken] of Object.entries(byChain)) {
4513
+ const chainId = Number(chainIdStr);
4514
+ if (!Number.isFinite(chainId)) continue;
4515
+ for (const [token, entry] of Object.entries(byToken ?? {})) {
4516
+ for (const pool of entry?.pools ?? []) {
4517
+ if (!pool?.name) continue;
4518
+ result.push({
4519
+ chainId,
4520
+ token,
4521
+ name: pool.name,
4522
+ apy: pool.info?.combined_apy ?? null,
4523
+ tvlUsd: pool.info?.tvlUsd ?? null,
4524
+ link: pool.info?.link ?? null
4525
+ });
4526
+ }
4527
+ }
4528
+ }
4529
+ return result;
4530
+ }
4531
+ function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
4532
+ const wanted = asset.toUpperCase();
4533
+ const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
4534
+ const catalog = [];
4535
+ for (const protocol of protocols) {
4536
+ const pools = (poolsByProtocol.get(protocol.id) ?? []).filter(
4537
+ (p) => p.token.toUpperCase() === wanted && (allowedChains === void 0 || allowedChains.has(p.chainId))
4538
+ );
4539
+ if (pools.length === 0) continue;
4540
+ catalog.push({
4541
+ protocolId: protocol.id,
4542
+ name: protocol.name,
4543
+ logo: protocol.imageUrl ?? null,
4544
+ pools
4545
+ });
4546
+ }
4547
+ return catalog;
4548
+ }
4347
4549
 
4348
4550
  // src/lib/agent-accounts.ts
4349
4551
  var SCOPE5 = "agent-accounts";
@@ -4841,7 +5043,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4841
5043
  */
4842
5044
  async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
4843
5045
  const movements = entries.filter(
4844
- (e) => (e.action === "Withdraw" || e.action === "Top up") && e.transactions[0]?.txHashes[0]
5046
+ (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
4845
5047
  );
4846
5048
  if (movements.length === 0) return;
4847
5049
  const client = this.getPublicClient(chainId);
@@ -5072,9 +5274,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
5072
5274
  this.sdk.getUserDetails(asset),
5073
5275
  this.sdk.getAvailableProtocols(chainId)
5074
5276
  ]);
5277
+ debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
5278
+ chains: current.chains,
5279
+ protocols: current.protocols,
5280
+ strategy: current.strategy
5281
+ });
5282
+ if ((current.chains?.length ?? 0) === 0 && (current.protocols?.length ?? 0) === 0) {
5283
+ debugLog(
5284
+ "zyfai:protocol-sync",
5285
+ `${asset}: skipping untouched profile until first deposit`
5286
+ );
5287
+ return;
5288
+ }
5075
5289
  const update = buildProtocolMergeUpdate(available, current, asset);
5076
5290
  if (!update) return;
5077
5291
  await this.sdk.updateUserProfile(update);
5292
+ debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
5078
5293
  } catch (error) {
5079
5294
  console.warn(
5080
5295
  "[zyfai] ensureProtocolsSynced failed (non-fatal):",
@@ -5083,10 +5298,28 @@ var ZyfaiAgent = class _ZyfaiAgent {
5083
5298
  }
5084
5299
  }
5085
5300
  /** Connect + resolve smart wallet address for read operations. */
5301
+ /**
5302
+ * Sign-in for reads: any live session of this owner will do. Zyfai's session
5303
+ * is per user and its data calls name the chain themselves, so reading
5304
+ * Arbitrum while signed in on Base needs no new sign-in. `connectAuth` pins
5305
+ * the chain, and reconnecting per chain made the whole-portfolio reads (one
5306
+ * per chain, in parallel) cancel each other's sign-in. Funding keeps
5307
+ * `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
5308
+ * so a later reconnect cannot leave the caller without an address.
5309
+ */
5310
+ async ensureReadSession(state, chainId) {
5311
+ const owner = state.walletAddress?.toLowerCase();
5312
+ if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
5313
+ if (!owner || this.connectedAddress?.toLowerCase() !== owner) await this.connectAuth(state, chainId);
5314
+ }
5315
+ /** `ensureReadSession`, then the owner it verified, read in the same turn. */
5316
+ async connectForRead(state, chainId) {
5317
+ await this.ensureReadSession(state, chainId);
5318
+ return this.getAddress();
5319
+ }
5086
5320
  async resolveSmartWallet(state, chainId) {
5087
- await this.connectAuth(state, chainId);
5088
5321
  const validChainId = isValidChainId(chainId);
5089
- const ownerAddress = this.getAddress();
5322
+ const ownerAddress = await this.connectForRead(state, validChainId);
5090
5323
  const smartWallet = await this.readSmartWallet(ownerAddress, validChainId);
5091
5324
  return { smartWallet, chainId: validChainId };
5092
5325
  }
@@ -5141,6 +5374,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5141
5374
  // --- IAgent: Account lifecycle ---
5142
5375
  async activateAgent(state, chainId) {
5143
5376
  try {
5377
+ debugLog("zyfai:activation", "starting", {
5378
+ walletAddress: state.walletAddress,
5379
+ chainId
5380
+ });
5144
5381
  await this.connectAuth(state, chainId);
5145
5382
  const validChainId = isValidChainId(chainId);
5146
5383
  await Promise.all([
@@ -5152,6 +5389,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5152
5389
  // validator, so pool-wallet users see no prompt. Non-fatal.
5153
5390
  this.ensureSessionKeyIfDeployed(validChainId)
5154
5391
  ]);
5392
+ debugLog("zyfai:activation", "completed", { chainId: validChainId });
5155
5393
  } catch (error) {
5156
5394
  throw error;
5157
5395
  }
@@ -5232,8 +5470,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
5232
5470
  * connecting, so a Zyfai hiccup must leave the user connected with their
5233
5471
  * profile unchanged, never fail activation.
5234
5472
  */
5235
- async applyPoolPolicy(policy) {
5473
+ async applyPoolPolicy(policy, opts = {}) {
5236
5474
  try {
5475
+ await this.sdk.ensureFirstDepositSetup("aggressive");
5237
5476
  const { protocols: universe } = await this.sdk.getAvailableProtocols(
5238
5477
  this.supportedChainIds[0]
5239
5478
  );
@@ -5246,7 +5485,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5246
5485
  universeIds,
5247
5486
  chainsByProtocol
5248
5487
  });
5249
- let strategy;
5488
+ let strategy = opts.strategy;
5250
5489
  const desiredProtocols = deriveProtocols(
5251
5490
  policy,
5252
5491
  universeIds,
@@ -5326,6 +5565,143 @@ var ZyfaiAgent = class _ZyfaiAgent {
5326
5565
  );
5327
5566
  }
5328
5567
  }
5568
+ /**
5569
+ * The deposit-time Pools step's catalogue: every protocol Zyfai offers this
5570
+ * user, each with the pools (name, APY, TVL, link) selectable for `asset`
5571
+ * under `strategy`. Sourced from the same two Zyfai calls `applyPoolPolicy`
5572
+ * uses, so "shown" and "selectable" are one set. A protocol whose pool
5573
+ * lookup fails is skipped rather than failing the whole catalogue.
5574
+ */
5575
+ async getPoolCatalog(params) {
5576
+ const { protocols: universe } = await this.sdk.getAvailableProtocols(
5577
+ this.supportedChainIds[0]
5578
+ );
5579
+ const poolResults = await Promise.all(
5580
+ universe.map(async (protocol) => {
5581
+ try {
5582
+ const raw2 = await this.sdk.getAvailablePools(
5583
+ protocol.id,
5584
+ params.strategy
5585
+ );
5586
+ return [protocol.id, mapAvailablePools(raw2)];
5587
+ } catch (error) {
5588
+ console.warn(
5589
+ `[zyfai] getPoolCatalog: getAvailablePools(${protocol.id}) failed, skipping (non-fatal):`,
5590
+ error instanceof Error ? error.message : String(error)
5591
+ );
5592
+ return null;
5593
+ }
5594
+ })
5595
+ );
5596
+ const poolsByProtocol = /* @__PURE__ */ new Map();
5597
+ for (const result of poolResults) {
5598
+ if (result) poolsByProtocol.set(result[0], result[1]);
5599
+ }
5600
+ return assemblePoolCatalog(universe, poolsByProtocol, params.asset);
5601
+ }
5602
+ /**
5603
+ * Persist an explicitly saved deposit-time draft at Zyfai profile level.
5604
+ * Pool choices are merged into protocol/chain records and each active asset
5605
+ * is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
5606
+ * The whole operation must succeed before the caller starts moving funds.
5607
+ */
5608
+ async setPoolSelection(selection) {
5609
+ try {
5610
+ await this.sdk.ensureFirstDepositSetup("aggressive");
5611
+ const byPair = /* @__PURE__ */ new Map();
5612
+ for (const entry of selection.selections) {
5613
+ const pair = `${entry.protocolId}:${entry.chainId}`;
5614
+ const group = byPair.get(pair) ?? [];
5615
+ group.push(entry);
5616
+ byPair.set(pair, group);
5617
+ }
5618
+ const customizations = await Promise.all(
5619
+ [...byPair.values()].map(async (scoped) => {
5620
+ const { protocolId, chainId } = scoped[0];
5621
+ const [current, rawAvailable] = await Promise.all([
5622
+ this.sdk.getSelectedPools(protocolId, chainId),
5623
+ this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
5624
+ ]);
5625
+ const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5626
+ return {
5627
+ protocolId,
5628
+ chainId,
5629
+ pools: mergeScopedPoolNames(
5630
+ {
5631
+ pools: current.pools ?? [],
5632
+ autoselect: current.autoselect
5633
+ },
5634
+ scoped,
5635
+ allAvailableNames
5636
+ ),
5637
+ // An explicit Save freezes exactly the choices the user saw.
5638
+ // This also lets an empty list disable the pair deliberately.
5639
+ autoselect: false
5640
+ };
5641
+ })
5642
+ );
5643
+ if (customizations.length > 0) {
5644
+ await this.sdk.customizeBatch(customizations);
5645
+ }
5646
+ await Promise.all(
5647
+ selection.strategies.map(async ({ asset, strategy }) => {
5648
+ const current = await this.sdk.getUserDetails(asset);
5649
+ const selectedProtocols = selection.selections.filter(
5650
+ (entry) => entry.asset === asset && entry.pools.length > 0
5651
+ ).map((entry) => entry.protocolId);
5652
+ const protocols = [
5653
+ .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
5654
+ ];
5655
+ await this.sdk.updateUserProfile({ asset, strategy, protocols });
5656
+ })
5657
+ );
5658
+ } catch (error) {
5659
+ console.warn(
5660
+ "[zyfai] setPoolSelection failed:",
5661
+ error instanceof Error ? error.message : String(error)
5662
+ );
5663
+ throw error;
5664
+ }
5665
+ }
5666
+ /**
5667
+ * Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
5668
+ * pools per protocol/chain and the strategy per asset; both are read for the
5669
+ * pairs and assets asked about. A pair still on autoselect, or one whose
5670
+ * lookup fails, is left out so the caller falls back to its default for it.
5671
+ */
5672
+ async getPoolSelection(state, chainId, params) {
5673
+ await this.connectAuth(state, chainId);
5674
+ const [pairs, strategies] = await Promise.all([
5675
+ Promise.all(
5676
+ params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
5677
+ try {
5678
+ const current = await this.sdk.getSelectedPools(
5679
+ protocolId,
5680
+ chainId2
5681
+ );
5682
+ if (current.autoselect) return null;
5683
+ return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
5684
+ } catch {
5685
+ return null;
5686
+ }
5687
+ })
5688
+ ),
5689
+ Promise.all(
5690
+ params.assets.map(async (asset) => {
5691
+ try {
5692
+ const current = await this.sdk.getUserDetails(asset);
5693
+ return current.strategy ? { asset, strategy: current.strategy } : null;
5694
+ } catch {
5695
+ return null;
5696
+ }
5697
+ })
5698
+ )
5699
+ ]);
5700
+ return {
5701
+ pairs: pairs.filter((value) => value !== null),
5702
+ strategies: strategies.filter((value) => value !== null)
5703
+ };
5704
+ }
5329
5705
  /**
5330
5706
  * True when `smartWallet` is the backend-managed pool wallet Zyfai assigned
5331
5707
  * to this EOA — the "new wallet" kind that is predeployed on the chains it
@@ -5482,11 +5858,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5482
5858
  );
5483
5859
  return;
5484
5860
  }
5485
- await this.ensureSessionKey(
5486
- ownerAddress,
5487
- chainId,
5488
- wallet.address
5489
- );
5861
+ await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
5490
5862
  } catch (error) {
5491
5863
  console.warn(
5492
5864
  "[zyfai] session-key check at activation failed (non-fatal):",
@@ -5597,11 +5969,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5597
5969
  "zyfai:onboard",
5598
5970
  "Safe already has code -> no deploy needed, checking the session key"
5599
5971
  );
5600
- await this.ensureSessionKey(
5601
- ownerAddress,
5602
- chainId,
5603
- wallet.address
5604
- );
5972
+ await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
5605
5973
  return wallet.address;
5606
5974
  }
5607
5975
  const poolFirst = await this.isPredeployedPoolWallet(
@@ -5667,6 +6035,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
5667
6035
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while preparing Zyfai deposit.", void 0, this.id);
5668
6036
  };
5669
6037
  assertCurrent();
6038
+ const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
6039
+ debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
6040
+ if (isOwneyDebug()) {
6041
+ try {
6042
+ const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
6043
+ debugLog(
6044
+ "zyfai:first-deposit",
6045
+ "profile immediately after setup",
6046
+ { asset, strategy: profile.strategy, chains: profile.chains, protocols: profile.protocols }
6047
+ );
6048
+ } catch (debugError) {
6049
+ debugLog(
6050
+ "zyfai:first-deposit",
6051
+ "post-setup profile read failed",
6052
+ { error: debugError instanceof Error ? debugError.message : String(debugError) }
6053
+ );
6054
+ }
6055
+ }
6056
+ assertCurrent();
5670
6057
  const smartWallet = await this.ensureWalletDeployed(owner, validChainId);
5671
6058
  assertCurrent();
5672
6059
  let server;
@@ -6894,7 +7281,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6894
7281
  }
6895
7282
  async refreshEarnings(state, chainId) {
6896
7283
  const generation = this.earningsGeneration;
6897
- await this.connectAuth(state, chainId);
7284
+ await this.ensureReadSession(state, chainId);
6898
7285
  const executionSdk = this.sdk;
6899
7286
  const connectionGeneration = this.connectionGeneration;
6900
7287
  const assertCurrent = () => {
@@ -6936,14 +7323,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
6936
7323
  this.earningsRefreshes.set(key2, pending2);
6937
7324
  return pending2;
6938
7325
  }
6939
- async getAccountApy(state, chainId, days, tokenSymbol) {
7326
+ async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
6940
7327
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
6941
7328
  const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
6942
- return mapApyHistory(raw2, chainId, tokenSymbol);
7329
+ const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
7330
+ const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
7331
+ return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
6943
7332
  }
6944
7333
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
6945
7334
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
6946
- const start = new Date(Date.now() - (DayFilterMapping[days] + 1) * 864e5);
7335
+ const start = new Date(
7336
+ Date.now() - (DayFilterMapping[days] + 1) * 864e5
7337
+ );
6947
7338
  const raw2 = await this.sdk.getDailyEarnings(
6948
7339
  smartWallet,
6949
7340
  start.toISOString().slice(0, 10)
@@ -7036,7 +7427,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7036
7427
  };
7037
7428
  }
7038
7429
  async getUserProfile(state, chainId) {
7039
- await this.connectAuth(state, chainId);
7430
+ await this.ensureReadSession(state, chainId);
7040
7431
  const raw2 = await this.sdk.getUserDetails();
7041
7432
  debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
7042
7433
  asset: "USDC (default \u2014 no asset passed)",
@@ -7053,6 +7444,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
7053
7444
  async ensureAutoSelectProtocols(state, chainId, asset) {
7054
7445
  await this.connectAuth(state, chainId);
7055
7446
  const current = await this.sdk.getUserDetails(asset);
7447
+ debugLog("zyfai:auto-select", `${asset}: profile before check`, {
7448
+ autoSelectProtocols: current.autoSelectProtocols,
7449
+ chains: current.chains,
7450
+ protocols: current.protocols,
7451
+ strategy: current.strategy
7452
+ });
7453
+ if ((current.chains?.length ?? 0) === 0) {
7454
+ debugLog(
7455
+ "zyfai:auto-select",
7456
+ `${asset}: skipping untouched profile until first deposit`
7457
+ );
7458
+ return false;
7459
+ }
7056
7460
  const update = buildAutoSelectUpdate(
7057
7461
  {
7058
7462
  autoSelectProtocols: current.autoSelectProtocols,
@@ -7063,6 +7467,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7063
7467
  );
7064
7468
  if (!update) return false;
7065
7469
  await this.sdk.updateUserProfile(update);
7470
+ debugLog("zyfai:auto-select", `${asset}: wrote profile update`, update);
7066
7471
  return true;
7067
7472
  }
7068
7473
  // --- IAgent: Discovery (no wallet required) ---
@@ -7281,6 +7686,14 @@ var YieldseekerAuth = class {
7281
7686
  }
7282
7687
  return this.getToken(state, chainId);
7283
7688
  }
7689
+ /** Drop a proof the provider refused, without signing a new one: a
7690
+ * promptless read cannot renew it, and must stop offering it. */
7691
+ discardToken(state, chainId, rejectedToken) {
7692
+ const key2 = this.key(state, chainId);
7693
+ if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
7694
+ if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken)
7695
+ clearYieldseekerSession(state.walletAddress, chainId);
7696
+ }
7284
7697
  isReusable(token, state, chainId) {
7285
7698
  try {
7286
7699
  const message = new import_siwe.SiweMessage(JSON.parse(atob(token)).message);
@@ -7737,18 +8150,19 @@ function dailyApy(point) {
7737
8150
  if (principal <= 0n || earned === 0n) return 0;
7738
8151
  return Number(earned) / Number(principal) * 365 * 100;
7739
8152
  }
7740
- function aggregateHistory(contexts, dayCount, now) {
8153
+ function aggregateHistory(contexts, dayCount, now, scopedAsset) {
7741
8154
  const today = new Date(now).toISOString().slice(0, 10);
7742
8155
  const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
7743
8156
  const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
7744
- const unit = assets.size === 1 ? [...assets][0] : "USD";
8157
+ const tokenUnits = scopedAsset !== void 0 && assets.size <= 1;
8158
+ const unit = tokenUnits ? scopedAsset.toUpperCase() : "USD";
7745
8159
  const byDate = /* @__PURE__ */ new Map();
7746
8160
  for (const context of contexts) {
7747
8161
  const points = context.historic?.dailyYieldSnapshots ?? [];
7748
8162
  for (const point of points) {
7749
8163
  if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
7750
8164
  const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
7751
- const amount = assets.size === 1 ? tokens : tokens * point.baseAssetPriceUsd;
8165
+ const amount = tokenUnits ? tokens : tokens * point.baseAssetPriceUsd;
7752
8166
  if (!Number.isFinite(amount) || amount < 0) {
7753
8167
  invalid("historic position", "expected a finite non-negative balance");
7754
8168
  }
@@ -7764,7 +8178,30 @@ function aggregateHistory(contexts, dayCount, now) {
7764
8178
  historicalBalance: { amount: value.amount, unit }
7765
8179
  }));
7766
8180
  }
7767
- function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
8181
+ function historyCoverage2(contexts, dayCount, now) {
8182
+ const today = new Date(now).toISOString().slice(0, 10);
8183
+ const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
8184
+ const datesByAsset = /* @__PURE__ */ new Map();
8185
+ const allDates = /* @__PURE__ */ new Set();
8186
+ for (const context of contexts) {
8187
+ for (const point of context.historic?.dailyYieldSnapshots ?? []) {
8188
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
8189
+ if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
8190
+ const asset = context.asset.toUpperCase();
8191
+ const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
8192
+ dates.add(point.date);
8193
+ datesByAsset.set(asset, dates);
8194
+ allDates.add(point.date);
8195
+ }
8196
+ }
8197
+ const assets = [...datesByAsset].map(([asset, dates]) => ({ asset, days: dates.size }));
8198
+ return {
8199
+ chains: allDates.size ? [{ chainId: 8453, days: allDates.size }] : [],
8200
+ assets,
8201
+ pairs: assets.map((entry) => ({ chainId: 8453, ...entry }))
8202
+ };
8203
+ }
8204
+ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scopedAsset) {
7768
8205
  let weighted = 0;
7769
8206
  let totalUsd = 0;
7770
8207
  const byAsset = {};
@@ -7785,7 +8222,8 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
7785
8222
  walletAddress,
7786
8223
  ...days !== "14D" || Object.keys(byAsset).length > 0 ? { weightedApyAfterFee: totalUsd > 0 ? weighted / totalUsd : 0 } : {},
7787
8224
  apyByChainAndAsset: { 8453: byAsset },
7788
- history: aggregateHistory(contexts, dayCount, now)
8225
+ history: aggregateHistory(contexts, dayCount, now, scopedAsset),
8226
+ coverage: historyCoverage2(contexts, dayCount, now)
7789
8227
  };
7790
8228
  }
7791
8229
  function actionType(value) {
@@ -10572,6 +11010,9 @@ var YieldseekerAgent = class {
10572
11010
  if (timer) clearTimeout(timer);
10573
11011
  }
10574
11012
  }
11013
+ hasReadSession(state, chainId) {
11014
+ return this.supportedChainIds.includes(chainId) && this.auth.peekToken(state, chainId) !== void 0;
11015
+ }
10575
11016
  async getBalances(state, chainId, asset) {
10576
11017
  this.assertChain(chainId);
10577
11018
  if (asset !== void 0) this.assertAsset(asset);
@@ -10710,15 +11151,17 @@ var YieldseekerAgent = class {
10710
11151
  const contexts = await this.loadPortfolio(state, chainId, { includePositions: false, ledger: true });
10711
11152
  return mapYieldseekerEarnings(await Promise.all(contexts.map((context) => this.applyEarningsHold(state, chainId, context))));
10712
11153
  }
10713
- async getAccountApy(state, chainId, days, tokenSymbol) {
11154
+ async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
10714
11155
  this.assertChain(chainId);
10715
11156
  const asset = tokenSymbol?.toUpperCase();
10716
11157
  if (asset !== void 0) this.assertAsset(asset);
11158
+ if (typeof scopeChainId === "number" && !this.supportedChainIds.includes(scopeChainId))
11159
+ return mapYieldseekerApy(state.walletAddress, [], days);
10717
11160
  const contexts = await this.loadPortfolio(state, chainId, {
10718
11161
  ...asset ? { asset } : {},
10719
11162
  historic: true
10720
11163
  });
10721
- return mapYieldseekerApy(state.walletAddress, contexts, days);
11164
+ return mapYieldseekerApy(state.walletAddress, contexts, days, Date.now(), asset);
10722
11165
  }
10723
11166
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
10724
11167
  this.assertChain(chainId);
@@ -12072,8 +12515,9 @@ var YieldseekerAgent = class {
12072
12515
  options.assertCurrent?.();
12073
12516
  return this.api.request(path, { method: options.method, body: options.body, signature: signature2 });
12074
12517
  };
12075
- const cached = options.promptless ? this.auth.peekToken(state, chainId) : void 0;
12076
- if (options.promptless && !cached)
12518
+ const promptless = options.promptless || state.promptless === true;
12519
+ const cached = promptless ? this.auth.peekToken(state, chainId) : void 0;
12520
+ if (promptless && !cached)
12077
12521
  throw new OwneyError(
12078
12522
  "AGENT_AUTH_FAILED",
12079
12523
  "No Yieldseeker sign-in is available without a prompt.",
@@ -12087,7 +12531,10 @@ var YieldseekerAgent = class {
12087
12531
  if (!(error instanceof YieldseekerApiError)) throw error;
12088
12532
  if (error.providerCode === "NO_USER") throw error;
12089
12533
  if (!error.isAuthenticationError) throw error;
12090
- if (options.promptless) throw error;
12534
+ if (promptless) {
12535
+ this.auth.discardToken(state, chainId, signature);
12536
+ throw error;
12537
+ }
12091
12538
  signature = await this.auth.refreshToken(state, chainId, signature);
12092
12539
  try {
12093
12540
  return await request2(signature);
@@ -12317,6 +12764,120 @@ var YieldseekerAgent = class {
12317
12764
  // src/client.ts
12318
12765
  init_errors();
12319
12766
 
12767
+ // src/lib/history-fanout.ts
12768
+ var SEPARATOR = "@";
12769
+ function isSupportedChainId(value) {
12770
+ return SUPPORTED_CHAIN_IDS.includes(value);
12771
+ }
12772
+ function fanoutKey(leg) {
12773
+ return leg.chainId === void 0 ? leg.agentId : `${leg.agentId}${SEPARATOR}${leg.chainId}`;
12774
+ }
12775
+ function encodeFanoutCursor(map) {
12776
+ return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
12777
+ }
12778
+ function decodeFanoutCursor(token) {
12779
+ let parsed;
12780
+ try {
12781
+ parsed = JSON.parse(Buffer.from(token, "base64").toString("utf8"));
12782
+ } catch {
12783
+ throw new InvalidHistoryCursorError(
12784
+ "History fan-out cursor is not valid base64 JSON."
12785
+ );
12786
+ }
12787
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string")) {
12788
+ throw new InvalidHistoryCursorError(
12789
+ "History fan-out cursor payload has wrong shape."
12790
+ );
12791
+ }
12792
+ return parsed;
12793
+ }
12794
+ function transactionChainId(entry) {
12795
+ let found;
12796
+ for (const tx of entry.transactions ?? []) {
12797
+ if (tx.chainId === void 0) continue;
12798
+ if (!isSupportedChainId(tx.chainId)) return void 0;
12799
+ if (found !== void 0 && found !== tx.chainId) return void 0;
12800
+ found = tx.chainId;
12801
+ }
12802
+ return found;
12803
+ }
12804
+ function mergeHistoryPages(pages) {
12805
+ const merged = [];
12806
+ const nextCursorMap = {};
12807
+ let hasMore = false;
12808
+ const identity = (e) => [
12809
+ e.agent,
12810
+ e.action,
12811
+ e.date ?? "",
12812
+ e.transactions?.[0]?.txHashes?.[0] ?? ""
12813
+ ].join("\0");
12814
+ const seen = /* @__PURE__ */ new Map();
12815
+ for (const { leg, page } of pages) {
12816
+ if (!page) continue;
12817
+ for (const e of page.data) {
12818
+ const id = identity(e);
12819
+ const prior = seen.get(id);
12820
+ if (prior) {
12821
+ prior.legs += 1;
12822
+ const own = transactionChainId(prior.entry);
12823
+ if (own === void 0) delete prior.entry.chainId;
12824
+ else prior.entry.chainId = own;
12825
+ continue;
12826
+ }
12827
+ const entry = leg.chainId === void 0 ? { ...e } : { ...e, chainId: leg.chainId };
12828
+ seen.set(id, { entry, legs: 1 });
12829
+ merged.push(entry);
12830
+ }
12831
+ if (page.hasMore && page.nextCursor) {
12832
+ nextCursorMap[fanoutKey(leg)] = page.nextCursor;
12833
+ hasMore = true;
12834
+ }
12835
+ }
12836
+ merged.sort((a, b) => {
12837
+ const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
12838
+ if (dateDiff !== 0) return dateDiff;
12839
+ if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;
12840
+ const aChain = a.chainId ?? 0;
12841
+ const bChain = b.chainId ?? 0;
12842
+ if (aChain !== bChain) return aChain - bChain;
12843
+ const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
12844
+ const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
12845
+ if (aTx !== bTx) return aTx < bTx ? -1 : 1;
12846
+ if (a.action !== b.action) return a.action < b.action ? -1 : 1;
12847
+ return 0;
12848
+ });
12849
+ return {
12850
+ data: merged,
12851
+ hasMore,
12852
+ nextCursor: hasMore ? encodeFanoutCursor(nextCursorMap) : void 0
12853
+ };
12854
+ }
12855
+
12856
+ // src/lib/daily-earnings-merge.ts
12857
+ function mergeDailyEarnings(series) {
12858
+ const byAsset = /* @__PURE__ */ new Map();
12859
+ for (const s of series) {
12860
+ for (const { asset, points } of s.assets) {
12861
+ const byDate = byAsset.get(asset) ?? /* @__PURE__ */ new Map();
12862
+ for (const point of points) {
12863
+ byDate.set(point.date, (byDate.get(point.date) ?? 0) + point.amount);
12864
+ }
12865
+ byAsset.set(asset, byDate);
12866
+ }
12867
+ }
12868
+ return {
12869
+ walletAddress: series[0]?.walletAddress ?? "",
12870
+ // Names the first source's chain. On a fanned-out read the payload spans
12871
+ // several, so this is provenance rather than scope — `assets` is the part
12872
+ // that carries the merged figures.
12873
+ chainId: series[0]?.chainId ?? 0,
12874
+ assets: [...byAsset.entries()].map(([asset, byDate]) => ({
12875
+ asset,
12876
+ points: [...byDate.entries()].map(([date, amount]) => ({ date, amount })).sort((a, b) => a.date.localeCompare(b.date))
12877
+ })).sort((a, b) => a.asset.localeCompare(b.asset))
12878
+ };
12879
+ }
12880
+
12320
12881
  // src/lib/swap/swap-api.ts
12321
12882
  init_errors();
12322
12883
  var FUSION_SECRET_SERVER_PUBLISH = 1;
@@ -12788,6 +13349,10 @@ var DEFAULT_POLL_MS2 = 5e3;
12788
13349
  var MAX_BACKOFF_MS = 3e4;
12789
13350
  var backoffFor = (failures, base7) => Math.min(base7 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
12790
13351
  var DEFAULT_TIMEOUT_MS3 = 15 * 60 * 1e3;
13352
+ var NOT_FOUND_GRACE_MS = 2 * 60 * 1e3;
13353
+ function isNotFound(error) {
13354
+ return error instanceof OwneyError && error.details?.statusCode === 404;
13355
+ }
12791
13356
  async function runFusionOrderInternal(deps, options) {
12792
13357
  const {
12793
13358
  orderHash,
@@ -12818,6 +13383,7 @@ async function runFusionOrderInternal(deps, options) {
12818
13383
  assertTime();
12819
13384
  };
12820
13385
  let failures = 0;
13386
+ let notFoundSince;
12821
13387
  const published = /* @__PURE__ */ new Set();
12822
13388
  onStage?.("swapping");
12823
13389
  for (; ; ) {
@@ -12853,7 +13419,20 @@ async function runFusionOrderInternal(deps, options) {
12853
13419
  status = state.status;
12854
13420
  partial ||= status === "partially-filled" || !!state.fills?.length;
12855
13421
  failures = 0;
12856
- } catch {
13422
+ notFoundSince = void 0;
13423
+ } catch (error) {
13424
+ if (isNotFound(error)) {
13425
+ notFoundSince ??= deps.now();
13426
+ if (deps.now() - notFoundSince >= NOT_FOUND_GRACE_MS) {
13427
+ throw new OwneyError(
13428
+ "SWAP_ORDER_NOT_FOUND",
13429
+ "The swap provider has no record of this order, so nothing was exchanged.",
13430
+ { orderHash }
13431
+ );
13432
+ }
13433
+ } else {
13434
+ notFoundSince = void 0;
13435
+ }
12857
13436
  failures += 1;
12858
13437
  await pause(backoffFor(failures, pollIntervalMs));
12859
13438
  continue;
@@ -13126,7 +13705,7 @@ async function executeSwap(deps, options) {
13126
13705
  });
13127
13706
  const before = await deps.readTargetBalance();
13128
13707
  debugLog("owney-sdk", "swap: target balance before", before.toString());
13129
- const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
13708
+ const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress).catch((error) => doubtVerdict(deps, error, before)) : await runFusion(deps, options, walletAddress);
13130
13709
  const { arrived } = await awaitBalanceIncrease({
13131
13710
  readBalance: () => deps.readTargetBalance(),
13132
13711
  baseline: before,
@@ -13145,6 +13724,17 @@ async function executeSwap(deps, options) {
13145
13724
  active = false;
13146
13725
  }
13147
13726
  }
13727
+ async function doubtVerdict(deps, error, before) {
13728
+ if (!(error instanceof OwneyError) || error.code !== "SWAP_ORDER_EXPIRED" && error.code !== "SWAP_ORDER_CANCELLED" || error.details?.outcome !== "not-submitted") throw error;
13729
+ const now = await deps.readTargetBalance().catch(() => before);
13730
+ if (now <= before) throw error;
13731
+ debugLog("owney-sdk", "swap: rail said no but the wallet received funds", { status: error.details?.status });
13732
+ throw new OwneyError(
13733
+ "SWAP_REQUEST_FAILED",
13734
+ "The swap's status says it did not fill, but funds arrived in your wallet since it started. Check your wallet before retrying.",
13735
+ { ...error.details, settlementUnconfirmed: true, outcome: "submitted-unknown" }
13736
+ );
13737
+ }
13148
13738
  async function runClassic(deps, options) {
13149
13739
  const {
13150
13740
  quote,
@@ -13169,8 +13759,8 @@ async function runClassic(deps, options) {
13169
13759
  onStage?.("quoting");
13170
13760
  debugLog("owney-sdk", "swap: fetching classic calldata");
13171
13761
  let { tx } = await deps.api.swapTx(swapTxRequest);
13172
- const isNative = BigInt(tx.value ?? "0") > 0n;
13173
- if (!isNative) {
13762
+ const isNative2 = BigInt(tx.value ?? "0") > 0n;
13763
+ if (!isNative2) {
13174
13764
  const needed = amount;
13175
13765
  const current = await deps.readAllowance(tx.to);
13176
13766
  debugLog("owney-sdk", "swap: allowance", {
@@ -13394,7 +13984,7 @@ async function runFusion(deps, options, walletAddress) {
13394
13984
  ...onStage ? { onStage } : {}
13395
13985
  });
13396
13986
  } catch (error) {
13397
- if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
13987
+ if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || error.code === "SWAP_ORDER_NOT_FOUND")) {
13398
13988
  clearOrder(built.orderHash);
13399
13989
  }
13400
13990
  throw error;
@@ -13677,6 +14267,34 @@ function verifiedFee(payout) {
13677
14267
  return gross !== void 0 && fee !== void 0 && net !== void 0 && fee > 0n && gross === rawAmount(evidence.intendedAmount) && net === rawAmount(payout.result.amount) && net + fee === gross ? fee : 0n;
13678
14268
  }
13679
14269
 
14270
+ // src/lib/swap/swap.gas-check.ts
14271
+ init_errors();
14272
+ var CLASSIC_SWAP_GAS = 300000n;
14273
+ var APPROVE_GAS2 = 60000n;
14274
+ var isNative = (address) => address.toLowerCase().startsWith("0xeeee");
14275
+ async function swapGasShortfall(deps, quote) {
14276
+ if (quote.rail !== "classic" || isNative(quote.src.address)) return null;
14277
+ const gas = CLASSIC_SWAP_GAS + APPROVE_GAS2;
14278
+ const [balance, gasPrice] = await Promise.all([
14279
+ deps.readNativeBalance(),
14280
+ deps.getMaxFeePerGas()
14281
+ ]);
14282
+ const required = gas * gasPrice;
14283
+ return balance < required ? { chainId: quote.src.chainId, balance, required } : null;
14284
+ }
14285
+ function swapGasError(shortfall, nativeSymbol) {
14286
+ return new OwneyError(
14287
+ "SWAP_INSUFFICIENT_GAS",
14288
+ `This swap needs a little ${nativeSymbol} for network fees, and your wallet has too little. Add some ${nativeSymbol}, or choose a different asset to receive.`,
14289
+ {
14290
+ chainId: shortfall.chainId,
14291
+ symbol: nativeSymbol,
14292
+ balance: shortfall.balance.toString(),
14293
+ required: shortfall.required.toString()
14294
+ }
14295
+ );
14296
+ }
14297
+
13680
14298
  // src/lib/swap/swap.permit.ts
13681
14299
  var import_viem20 = require("viem");
13682
14300
  var PERMIT_ABI = (0, import_viem20.parseAbi)([
@@ -14750,7 +15368,9 @@ async function execute(i, key2, plan) {
14750
15368
  if (balance < total)
14751
15369
  throw new OwneyError(
14752
15370
  "DEPOSIT_INSUFFICIENT_BALANCE",
14753
- "Insufficient token balance for this deposit."
15371
+ "Insufficient token balance for this deposit.",
15372
+ // What was seen: a swap's deposit retries once at a small shortfall (ROUT-618).
15373
+ { token: i.token, chainId: i.chainId, balance: balance.toString(), amount: total.toString() }
14754
15374
  );
14755
15375
  if (allowance < total && !supportsSponsoredErc2612(i.chainId, i.token))
14756
15376
  throw new OwneyError(
@@ -14785,15 +15405,20 @@ async function execute(i, key2, plan) {
14785
15405
  tokenName,
14786
15406
  tokenVersion
14787
15407
  };
14788
- const signature2 = await i.wallet.signTypedData({
14789
- account: i.owner,
14790
- ...erc2612TypedData({
14791
- chainId: i.chainId,
14792
- token: i.token,
14793
- owner: i.owner,
14794
- permit: unsignedPermit
15408
+ const signature2 = await signWithChainRetry(
15409
+ i.walletChain ?? i.pub,
15410
+ i.wallet,
15411
+ i.chainId,
15412
+ () => i.wallet.signTypedData({
15413
+ account: i.owner,
15414
+ ...erc2612TypedData({
15415
+ chainId: i.chainId,
15416
+ token: i.token,
15417
+ owner: i.owner,
15418
+ permit: unsignedPermit
15419
+ })
14795
15420
  })
14796
- });
15421
+ );
14797
15422
  erc2612Permit = { ...unsignedPermit, signature: signature2 };
14798
15423
  }
14799
15424
  const spender = await getSponsorRelayerAddress({
@@ -14810,10 +15435,15 @@ async function execute(i, key2, plan) {
14810
15435
  deadline: (now + 900n).toString(),
14811
15436
  ...erc2612Permit ? { erc2612Permit } : {}
14812
15437
  };
14813
- const signature = await i.wallet.signTypedData({
14814
- account: i.owner,
14815
- ...batchTypedData(unsigned, spender)
14816
- });
15438
+ const signature = await signWithChainRetry(
15439
+ i.walletChain ?? i.pub,
15440
+ i.wallet,
15441
+ i.chainId,
15442
+ () => i.wallet.signTypedData({
15443
+ account: i.owner,
15444
+ ...batchTypedData(unsigned, spender)
15445
+ })
15446
+ );
14817
15447
  i.onApproved?.();
14818
15448
  return send({ ...unsigned, signature });
14819
15449
  }
@@ -14842,6 +15472,7 @@ function makeSponsoredTokenCallback(deps) {
14842
15472
  chainId,
14843
15473
  transfers,
14844
15474
  pub,
15475
+ walletChain,
14845
15476
  wallet,
14846
15477
  onApproved: deps.onApproved,
14847
15478
  // Rest arguments keep the callbacks' arity: the flag appears only when set.
@@ -15116,6 +15747,19 @@ function makeSponsoredCallsCallback(deps) {
15116
15747
  var WALLET_CATCHUP_TIMEOUT_MS = 3e4;
15117
15748
  var PERMIT2_ALLOWANCE_VERIFY_ATTEMPTS = 6;
15118
15749
  var PERMIT2_ALLOWANCE_VERIFY_DELAY_MS = 250;
15750
+ function shortfallBalance(error, asked) {
15751
+ if (!(error instanceof OwneyError)) return void 0;
15752
+ if (error.code !== "DEPOSIT_INSUFFICIENT_BALANCE") return void 0;
15753
+ const seen = error.details?.balance;
15754
+ if (typeof seen !== "string") return void 0;
15755
+ const balance = BigInt(seen);
15756
+ if (balance <= 0n || balance >= asked) return void 0;
15757
+ return (asked - balance) * 100n <= asked ? balance : void 0;
15758
+ }
15759
+ function agentRunsOn(agent, chainId) {
15760
+ const chains = agent.supportedChainIds;
15761
+ return !chains || chains.includes(chainId);
15762
+ }
15119
15763
  function encodeMultiAgentCursor(map) {
15120
15764
  return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
15121
15765
  }
@@ -15209,6 +15853,7 @@ var OwneySDK = class {
15209
15853
  zyfaiRpcUrls;
15210
15854
  yieldseekerApiBaseUrl;
15211
15855
  yieldseekerSiweOrigin;
15856
+ userPoolCustomization = false;
15212
15857
  routingApiBaseUrl;
15213
15858
  referralSource;
15214
15859
  ledger;
@@ -15259,6 +15904,7 @@ var OwneySDK = class {
15259
15904
  this.routingApiBaseUrl = config.routingApiBaseUrl;
15260
15905
  this.paymasterServiceUrl = config.paymasterServiceUrl;
15261
15906
  this.referralSource = config.referralSource;
15907
+ this.userPoolCustomization = config.userPoolCustomization ?? false;
15262
15908
  this.ledger = createFundingLedger({
15263
15909
  apiKey: config.apiKey,
15264
15910
  baseUrl: config.routingApiBaseUrl,
@@ -15719,6 +16365,31 @@ var OwneySDK = class {
15719
16365
  }
15720
16366
  return active;
15721
16367
  }
16368
+ /**
16369
+ * Agents that do not run on the connection chain but can be read on their
16370
+ * own from a saved sign-in: Yieldseeker, Base-only, while the wallet sits on
16371
+ * Arbitrum or Ethereum. The whole-portfolio reads (ROUT-479) add them, under
16372
+ * a promptless state; with no saved sign-in they are left out, as before.
16373
+ */
16374
+ offChainPortfolioAgents(state) {
16375
+ const connectionChain = state.chainId;
16376
+ if (connectionChain === null) return [];
16377
+ const active = this.getActiveAgents();
16378
+ const promptless = { ...state, promptless: true };
16379
+ return [...this.agents.values()].flatMap((agent) => {
16380
+ if (active.has(agent.id) || agentRunsOn(agent, connectionChain) || !agent.hasReadSession) return [];
16381
+ const chainIds = agent.supportedChainIds.filter((id) => agent.hasReadSession(promptless, id));
16382
+ return chainIds.length ? [{ agent, state: promptless, chainIds }] : [];
16383
+ });
16384
+ }
16385
+ /** Every agent a whole-portfolio read covers: the active ones on the
16386
+ * connection chain, then the off-chain ones on their own chain. */
16387
+ portfolioReads(state, chainId) {
16388
+ return [
16389
+ ...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
16390
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
16391
+ ];
16392
+ }
15722
16393
  /**
15723
16394
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
15724
16395
  * throws — it degrades to null — so this cannot break activation.
@@ -15755,7 +16426,8 @@ var OwneySDK = class {
15755
16426
  try {
15756
16427
  const policy = await this.getOrgAgentConfig();
15757
16428
  if (!policy) return;
15758
- await agent.applyOrgPolicy(state, chainId, policy);
16429
+ const effective = orgPolicyForConnect(policy, this.userPoolCustomization);
16430
+ await agent.applyOrgPolicy(state, chainId, effective);
15759
16431
  } catch (error) {
15760
16432
  console.warn(
15761
16433
  `[owney-sdk] applyOrgPolicy(${agent.id}) failed (non-fatal):`,
@@ -16074,15 +16746,16 @@ var OwneySDK = class {
16074
16746
  return { agentResults: {} };
16075
16747
  }
16076
16748
  const state = this.requireState();
16077
- const chainId = this.requireChainId();
16749
+ const chainId = options.chainId ?? this.requireChainId();
16750
+ const activatedChain = state.chainId;
16078
16751
  let checkpointFailure;
16079
16752
  let checkpointFailedEvidence = [];
16080
16753
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
16081
16754
  try {
16082
- if (this.state !== state || state.chainId !== chainId) throw new Error("Wallet changed before deposit submission.");
16755
+ if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
16083
16756
  const submitting = evidence.map((leg) => ({ ...leg, depositSubmission: "started" }));
16084
16757
  await options.onBeforeSubmission(submitting);
16085
- if (this.state !== state || state.chainId !== chainId) throw new Error("Wallet changed before deposit submission.");
16758
+ if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
16086
16759
  submitting.forEach((leg) => notifyFunding(onProgress, leg));
16087
16760
  } catch (cause) {
16088
16761
  checkpointFailedEvidence = evidence;
@@ -16124,7 +16797,8 @@ var OwneySDK = class {
16124
16797
  chainId,
16125
16798
  token: ledgerToken?.address ?? "",
16126
16799
  asset: asset.toLowerCase(),
16127
- requestedAmountRaw: amount
16800
+ requestedAmountRaw: amount,
16801
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
16128
16802
  });
16129
16803
  } catch {
16130
16804
  }
@@ -16150,7 +16824,7 @@ var OwneySDK = class {
16150
16824
  const wallet = await (agent.getFundingWallet ? agent.getFundingWallet(state, chainId, asset) : agent.getUserProfile(state, chainId).then((profile) => profile.smartWallet)).catch(() => void 0);
16151
16825
  return { agent, wallet };
16152
16826
  }));
16153
- if (this.state !== state || this.state.chainId !== chainId)
16827
+ if (this.state !== state || this.state.chainId !== activatedChain)
16154
16828
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while recovering the deposit.");
16155
16829
  const usedAgents = /* @__PURE__ */ new Set();
16156
16830
  const legs = pending2.transfers.map((transfer) => {
@@ -16190,6 +16864,7 @@ var OwneySDK = class {
16190
16864
  );
16191
16865
  }
16192
16866
  const agent = this.getAgent(agentId);
16867
+ this.validateChainSupport(agent, chainId);
16193
16868
  this.validateAssetSupport(agent, chainId, asset);
16194
16869
  await this.validateMinDepositAmount(agent, state, chainId, asset, amount);
16195
16870
  return ledgerDone(await this.depositWithFallback(
@@ -16208,6 +16883,7 @@ var OwneySDK = class {
16208
16883
  ));
16209
16884
  }
16210
16885
  const totalAmount = BigInt(amount);
16886
+ this.validateChainHasAgents(chainId);
16211
16887
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
16212
16888
  excludeDisabled: true
16213
16889
  });
@@ -16564,6 +17240,41 @@ var OwneySDK = class {
16564
17240
  return false;
16565
17241
  }
16566
17242
  }
17243
+ /**
17244
+ * Guard an explicitly requested chain against one agent's own list.
17245
+ *
17246
+ * Only reachable when the caller passes `chainId` — the activated chain has
17247
+ * already been checked by `activateAgent`. Kept separate from
17248
+ * `validateAssetSupport` so "this agent is not on Ethereum" does not arrive
17249
+ * worded as "this agent does not support USDC".
17250
+ */
17251
+ validateChainSupport(agent, chainId) {
17252
+ if (!agent.supportedChainIds.includes(chainId)) {
17253
+ throw new AgentChainIncompatibleError(
17254
+ [{ agentId: agent.id, supportedChainIds: agent.supportedChainIds }],
17255
+ chainId
17256
+ );
17257
+ }
17258
+ }
17259
+ /**
17260
+ * Guard an explicitly requested chain before a fan-out.
17261
+ *
17262
+ * Without this the split simply produces no agents, and the caller is told
17263
+ * their amount "cannot activate every eligible agent" against a combined
17264
+ * minimum of 0 — an error about the amount when the chain is at fault.
17265
+ */
17266
+ validateChainHasAgents(chainId) {
17267
+ const compatible = [...this.agents.values()].some(
17268
+ (agent) => agent.supportedChainIds.includes(chainId)
17269
+ );
17270
+ if (!compatible) {
17271
+ throw new OwneyError(
17272
+ "CHAIN_NO_COMPATIBLE_AGENTS",
17273
+ `No agents support chain ${chainId}.`,
17274
+ { chainId }
17275
+ );
17276
+ }
17277
+ }
16567
17278
  validateAssetSupport(agent, chainId, asset) {
16568
17279
  const chainAssets = agent.supportedAssets.find(
16569
17280
  (sa) => sa.chainId === chainId
@@ -17299,6 +18010,19 @@ var OwneySDK = class {
17299
18010
  chain: dstChain,
17300
18011
  transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
17301
18012
  });
18013
+ const walletPublic = (0, import_viem25.createPublicClient)({
18014
+ chain: srcChain,
18015
+ transport: (0, import_viem25.custom)(provider)
18016
+ });
18017
+ const signOnSource = (payload) => signWithChainRetry(
18018
+ walletPublic,
18019
+ wallet,
18020
+ quote.src.chainId,
18021
+ () => wallet.signTypedData({
18022
+ account: state.walletAddress,
18023
+ ...payload
18024
+ })
18025
+ );
17302
18026
  return {
17303
18027
  api: this.swapApi(),
17304
18028
  // Native-aware, like readSourceBalance below. Native ETH is never a
@@ -17349,10 +18073,7 @@ var OwneySDK = class {
17349
18073
  },
17350
18074
  signTypedData: (typedData) => {
17351
18075
  assertWallet();
17352
- return wallet.signTypedData({
17353
- account: state.walletAddress,
17354
- ...typedData
17355
- });
18076
+ return signOnSource(typedData);
17356
18077
  },
17357
18078
  // Chain-bound like every other read here: the wallet provider's chain is
17358
18079
  // not ours to rely on mid-swap.
@@ -17421,10 +18142,7 @@ var OwneySDK = class {
17421
18142
  chainId: quote.src.chainId,
17422
18143
  signTypedData: (payload) => {
17423
18144
  assertWallet();
17424
- return wallet.signTypedData({
17425
- account: state.walletAddress,
17426
- ...payload
17427
- });
18145
+ return signOnSource(payload);
17428
18146
  }
17429
18147
  }
17430
18148
  ),
@@ -17451,13 +18169,27 @@ var OwneySDK = class {
17451
18169
  * would strand funds we might have been able to move.
17452
18170
  */
17453
18171
  /** ERC20 balance of the connected wallet, read through the wallet's own node. */
18172
+ /**
18173
+ * A read client pinned to `chainId`, over HTTP rather than the wallet.
18174
+ *
18175
+ * The swap rail has read this way from the start, and the reason is written
18176
+ * out at `buildSwapDeps`: a provider-backed client reads from whatever chain
18177
+ * the WALLET is on, which after a cross-chain swap is the source chain, not
18178
+ * the one the funds landed on. The deposit's own reads did not, so a Permit2
18179
+ * check for WETH on Arbitrum went to Base — where that address is not a
18180
+ * contract at all, so viem got "0x" back and threw "The contract function
18181
+ * 'allowance' returned no data".
18182
+ */
18183
+ chainReader(chainId) {
18184
+ return (0, import_viem25.createPublicClient)({
18185
+ chain: swapChain(chainId),
18186
+ transport: swapReadTransport(chainId, this.zyfaiRpcUrls)
18187
+ });
18188
+ }
17454
18189
  async readTokenBalance(chainId, token) {
17455
18190
  const state = this.requireState();
17456
18191
  return readErc20Balance(
17457
- (0, import_viem25.createPublicClient)({
17458
- chain: swapChain(chainId),
17459
- transport: (0, import_viem25.custom)(this.requireConnectedProvider())
17460
- }),
18192
+ this.chainReader(chainId),
17461
18193
  token,
17462
18194
  state.walletAddress
17463
18195
  );
@@ -17466,10 +18198,7 @@ var OwneySDK = class {
17466
18198
  async readTokenPermit2Allowance(chainId, token) {
17467
18199
  const state = this.requireState();
17468
18200
  return readPermit2Allowance(
17469
- (0, import_viem25.createPublicClient)({
17470
- chain: swapChain(chainId),
17471
- transport: (0, import_viem25.custom)(this.requireConnectedProvider())
17472
- }),
18201
+ this.chainReader(chainId),
17473
18202
  token,
17474
18203
  state.walletAddress
17475
18204
  );
@@ -17498,6 +18227,34 @@ var OwneySDK = class {
17498
18227
  const balance = await this.readTokenBalance(chainId, token);
17499
18228
  return (balance < received ? balance : received).toString();
17500
18229
  }
18230
+ /**
18231
+ * Deposit a swap's output, retrying once at the balance the deposit saw.
18232
+ *
18233
+ * `settleSwapDepositAmount` approves and THEN reads, but the read and the
18234
+ * deposit's own pre-check can disagree: the approval is confirmed through
18235
+ * the wallet's node, the read goes to a pinned RPC, and gas paid in WETH
18236
+ * (MetaMask offers this to a wallet with no ETH) can land after either.
18237
+ * ROUT-618 failed that way with the settle step in place.
18238
+ *
18239
+ * The pre-check reports the balance it saw, and that is the authority, so
18240
+ * a shortfall is retried once at that figure. Only a small one: a node that
18241
+ * has not caught up can read near zero, and depositing that would leave the
18242
+ * rest of the swap stranded behind a "success".
18243
+ */
18244
+ async depositSwapOutput(options) {
18245
+ const attempt = (amount) => this.deposit({ ...options, amount });
18246
+ try {
18247
+ return {
18248
+ deposit: await attempt(options.amount),
18249
+ deposited: options.amount
18250
+ };
18251
+ } catch (error) {
18252
+ const balance = shortfallBalance(error, BigInt(options.amount));
18253
+ if (balance === void 0) throw error;
18254
+ const deposited = balance.toString();
18255
+ return { deposit: await attempt(deposited), deposited };
18256
+ }
18257
+ }
17501
18258
  async walletSeesBalance(chainId, token, amount) {
17502
18259
  const provider = this.requireConnectedProvider();
17503
18260
  const state = this.requireState();
@@ -17523,9 +18280,39 @@ var OwneySDK = class {
17523
18280
  * Runs a quoted swap. A named seam rather than an inline `executeSwap` call
17524
18281
  * so the deposit half of `swapAndDeposit` can be exercised on its own.
17525
18282
  */
17526
- runSwap(quote, options, onTransactionHash) {
18283
+ async runSwap(quote, options, onTransactionHash) {
18284
+ await this.checkSwapGas(quote);
17527
18285
  return executeSwap(this.buildSwapDeps(quote, options.assertCurrent, onTransactionHash), { quote, ...options });
17528
18286
  }
18287
+ /**
18288
+ * Throws SWAP_INSUFFICIENT_GAS when the wallet cannot pay for this swap.
18289
+ *
18290
+ * Only the classic rail is ever refused: it is the one where the user sends
18291
+ * the transactions. Call it on a preview quote to warn BEFORE a withdrawal
18292
+ * moves anything — `withdrawAndSwap` repeats it on its own quote, but by
18293
+ * then the funds have already left the agent (ROUT-622).
18294
+ */
18295
+ async checkSwapGas(quote) {
18296
+ const state = this.requireState();
18297
+ const chain2 = swapChain(quote.src.chainId);
18298
+ if (!chain2) return;
18299
+ const pub = (0, import_viem25.createPublicClient)({
18300
+ chain: chain2,
18301
+ transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
18302
+ });
18303
+ const shortfall = await swapGasShortfall(
18304
+ {
18305
+ readNativeBalance: () => pub.getBalance({ address: state.walletAddress }),
18306
+ // The 1559 ceiling, as the wrap reserve reads it.
18307
+ getMaxFeePerGas: async () => {
18308
+ const fees = await pub.estimateFeesPerGas();
18309
+ return fees.maxFeePerGas ?? pub.getGasPrice();
18310
+ }
18311
+ },
18312
+ quote
18313
+ );
18314
+ if (shortfall) throw swapGasError(shortfall, chain2.nativeCurrency.symbol);
18315
+ }
17529
18316
  /**
17530
18317
  * The half of the swap deps that only ever talks to the routing API.
17531
18318
  *
@@ -17597,12 +18384,20 @@ var OwneySDK = class {
17597
18384
  );
17598
18385
  }
17599
18386
  await this.ensureSwapChain(entry.chainId);
17600
- const deposit = await this.deposit({
17601
- amount: entry.received,
18387
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
18388
+ const amount = token ? await this.settleSwapDepositAmount(
18389
+ entry.chainId,
18390
+ token,
18391
+ entry.symbol,
18392
+ BigInt(entry.received)
18393
+ ) : entry.received;
18394
+ const { deposit } = await this.depositSwapOutput({
18395
+ amount,
17602
18396
  asset: entry.symbol,
17603
18397
  ...entry.agentId ? { agentId: entry.agentId } : {},
17604
18398
  // The swap's own funding-ledger operation; older records have none.
17605
- ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {}
18399
+ ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
18400
+ ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
17606
18401
  });
17607
18402
  clearPendingDeposit(entry.id);
17608
18403
  return deposit;
@@ -17661,13 +18456,15 @@ var OwneySDK = class {
17661
18456
  chainId: deposit.chainId,
17662
18457
  createdAt: Date.now(),
17663
18458
  ...typeof deposit.agentId === "string" ? { agentId: deposit.agentId } : {},
17664
- ...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {}
18459
+ ...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {},
18460
+ ...typeof deposit.batchId === "string" ? { batchId: deposit.batchId } : {}
17665
18461
  });
17666
18462
  clearOrder(order.orderHash);
17667
18463
  updateWithdrawSwap(order.orderHash, { status: "landed" });
17668
18464
  return { orderHash: order.orderHash, status: "completed" };
17669
18465
  } catch (error) {
17670
- if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
18466
+ if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || // The provider never accepted it: nothing was escrowed.
18467
+ error.code === "SWAP_ORDER_NOT_FOUND")) {
17671
18468
  clearOrder(order.orderHash);
17672
18469
  updateWithdrawSwap(order.orderHash, { status: "refunded" });
17673
18470
  } else {
@@ -17840,7 +18637,8 @@ var OwneySDK = class {
17840
18637
  owner: state.walletAddress,
17841
18638
  chainId: options.to.chainId,
17842
18639
  token: SupportedAssets.find((value) => value.chainId === options.to.chainId && value.symbol === options.to.symbol)?.address ?? "",
17843
- asset: options.to.symbol.toLowerCase()
18640
+ asset: options.to.symbol.toLowerCase(),
18641
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17844
18642
  });
17845
18643
  const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
17846
18644
  try {
@@ -17878,7 +18676,8 @@ var OwneySDK = class {
17878
18676
  symbol: options.to.symbol,
17879
18677
  chainId: quote.dst.chainId,
17880
18678
  ...options.agentId ? { agentId: options.agentId } : {},
17881
- ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
18679
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
18680
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17882
18681
  },
17883
18682
  ...secretHandoff ? { secretHandoff } : {},
17884
18683
  ...ledgerOp ? { onOrderSubmitted: (orderHash) => {
@@ -17921,7 +18720,7 @@ var OwneySDK = class {
17921
18720
  options.assertCurrent?.();
17922
18721
  await options.onBeforeDeposit?.();
17923
18722
  options.assertCurrent?.();
17924
- const deposit = await this.deposit({
18723
+ const { deposit, deposited } = await this.depositSwapOutput({
17925
18724
  amount,
17926
18725
  asset: options.to.symbol,
17927
18726
  ...options.agentId ? { agentId: options.agentId } : {},
@@ -17931,7 +18730,7 @@ var OwneySDK = class {
17931
18730
  ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
17932
18731
  });
17933
18732
  if (backgroundDepositId) clearPendingDeposit(backgroundDepositId);
17934
- return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited: amount });
18733
+ return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited });
17935
18734
  } catch (error) {
17936
18735
  const pending2 = {
17937
18736
  // Keyed by the order when there is one, so it replaces any record a
@@ -17943,7 +18742,11 @@ var OwneySDK = class {
17943
18742
  ...options.agentId ? { agentId: options.agentId } : {},
17944
18743
  createdAt: Date.now()
17945
18744
  };
17946
- savePendingDeposit(ledgerOp ? { ...pending2, operationId: ledgerOp.operationId } : pending2);
18745
+ savePendingDeposit({
18746
+ ...pending2,
18747
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
18748
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
18749
+ });
17947
18750
  throw new OwneyError(
17948
18751
  "SWAP_DEPOSIT_PENDING",
17949
18752
  `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.`,
@@ -17993,7 +18796,8 @@ var OwneySDK = class {
17993
18796
  token: asset.address,
17994
18797
  asset: asset.symbol.toLowerCase(),
17995
18798
  isMax: recovery.requested === void 0,
17996
- ...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested }
18799
+ ...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested },
18800
+ ...record2.batchId === void 0 ? {} : { batchId: record2.batchId }
17997
18801
  });
17998
18802
  } catch {
17999
18803
  }
@@ -18148,6 +18952,7 @@ var OwneySDK = class {
18148
18952
  let ledgerInput;
18149
18953
  ledgerOp = this.openSwapLedger(() => {
18150
18954
  const requestedRaw = saved ? saved.recovery.requested : options.amount === void 0 ? void 0 : (0, import_viem25.parseUnits)(options.amount, asset.decimals).toString();
18955
+ const batchId = saved?.batchId ?? options.batchId;
18151
18956
  return ledgerInput = {
18152
18957
  operationId: saved?.operationId ?? options.operationId,
18153
18958
  kind: "withdraw_swap",
@@ -18156,7 +18961,8 @@ var OwneySDK = class {
18156
18961
  token: asset.address,
18157
18962
  asset: asset.symbol.toLowerCase(),
18158
18963
  isMax: requestedRaw === void 0,
18159
- ...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw }
18964
+ ...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw },
18965
+ ...batchId === void 0 ? {} : { batchId }
18160
18966
  };
18161
18967
  });
18162
18968
  const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
@@ -18201,7 +19007,8 @@ var OwneySDK = class {
18201
19007
  agentId: options.agentId,
18202
19008
  evidence: {}
18203
19009
  },
18204
- ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
19010
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
19011
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
18205
19012
  };
18206
19013
  if (ledgerOp && !record2.operationId) record2.operationId = ledgerOp.operationId;
18207
19014
  hadDurableRecord = saveWithdrawSwap(record2);
@@ -18317,6 +19124,8 @@ var OwneySDK = class {
18317
19124
  () => new OwneyError("SWAP_WALLET_PROMPT_TIMEOUT", "The wallet did not confirm its chain. No swap was submitted.", { outcome: "not-submitted" })
18318
19125
  );
18319
19126
  assertCurrent();
19127
+ await this.checkSwapGas(quote);
19128
+ assertCurrent();
18320
19129
  const swap = await executeSwap(this.buildSwapDeps(quote, assertCurrent, (hash2) => {
18321
19130
  record2.txHash = hash2;
18322
19131
  saveWithdrawSwap(record2);
@@ -18446,7 +19255,7 @@ var OwneySDK = class {
18446
19255
  { phase: "prepare", rejectedBeforeSubmission: true }
18447
19256
  );
18448
19257
  const state = this.requireState();
18449
- const chainId = this.requireChainId();
19258
+ const chainId = options.chainId ?? this.requireChainId();
18450
19259
  const submissionKey = `${state.walletAddress.toLowerCase()}:${chainId}:${options.asset.toUpperCase()}`;
18451
19260
  if (this.withdrawalSubmissions.has(submissionKey))
18452
19261
  throw new OwneyError(
@@ -18468,7 +19277,8 @@ var OwneySDK = class {
18468
19277
  token: ledgerToken?.address ?? "",
18469
19278
  asset: options.asset.toLowerCase(),
18470
19279
  isMax: options.amount === void 0,
18471
- ...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {}
19280
+ ...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {},
19281
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
18472
19282
  });
18473
19283
  } catch {
18474
19284
  }
@@ -18793,6 +19603,7 @@ var OwneySDK = class {
18793
19603
  }
18794
19604
  async withdrawFromAgents(options, state, chainId, attempted, ledgerLeg, reservation, plannedLegs, settleLedger, serverLegs = /* @__PURE__ */ new Map()) {
18795
19605
  const { asset, amount, agentId, onAgentResult } = options;
19606
+ const activatedChain = state.chainId;
18796
19607
  const notifyAgentResult = (id, result) => {
18797
19608
  try {
18798
19609
  if (result.evidence) notifyFunding(options.onProgress, result.evidence);
@@ -18853,7 +19664,7 @@ var OwneySDK = class {
18853
19664
  const plannedTask = serverLegs.get(agent.id);
18854
19665
  const serverTask = plannedTask ? await plannedTask.answer : void 0;
18855
19666
  if (serverTask) await settleLedger?.(3e3);
18856
- if (this.state !== state || this.state.chainId !== chainId)
19667
+ if (this.state !== state || this.state.chainId !== activatedChain)
18857
19668
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed before withdrawal submission.");
18858
19669
  attempted.add(agent.id);
18859
19670
  let evidence = {
@@ -18938,6 +19749,7 @@ var OwneySDK = class {
18938
19749
  }
18939
19750
  if (agentId) {
18940
19751
  const agent = this.getAgent(agentId);
19752
+ this.validateChainSupport(agent, chainId);
18941
19753
  this.validateAssetSupport(agent, chainId, asset);
18942
19754
  const result = await withFailureReporting(
18943
19755
  this.apiKey,
@@ -19161,7 +19973,7 @@ var OwneySDK = class {
19161
19973
  const verified = await entry.agent.getWithdrawableBalance(state, chainId, token, minimumAmount);
19162
19974
  if (typeof verified !== "bigint" || verified < 0n)
19163
19975
  throw new OwneyError("WITHDRAW_BALANCE_UNAVAILABLE", "Invalid withdrawal balance proof.", {}, entry.agent.id);
19164
- if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== chainId)
19976
+ if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== activatedChain)
19165
19977
  throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
19166
19978
  entry.balance = verified;
19167
19979
  const unavailableIndex = unavailableAgents.indexOf(entry.agent);
@@ -19176,7 +19988,7 @@ var OwneySDK = class {
19176
19988
  };
19177
19989
  }
19178
19990
  }));
19179
- if (this.state !== state || this.state.chainId !== chainId)
19991
+ if (this.state !== state || this.state.chainId !== activatedChain)
19180
19992
  throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
19181
19993
  const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
19182
19994
  const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
@@ -19357,6 +20169,76 @@ var OwneySDK = class {
19357
20169
  * @param agentId - Optional. Agent to query. Omit for aggregated balances.
19358
20170
  * @returns {AgentBalance} for a single agent, or {OwneyBalances} with totalBalance and per-agent breakdown
19359
20171
  */
20172
+ /**
20173
+ * Withdraw every position the wallet holds, across chains and assets.
20174
+ *
20175
+ * `withdraw()` drains one asset on one chain, so this is N of those. It
20176
+ * deliberately does not stop at the first failure: the funds in the other
20177
+ * positions are just as withdrawable, and someone who asked for everything
20178
+ * is better served by three of four than by none. Each leg reports its own
20179
+ * outcome so the caller can name the ones that did not arrive; only a total
20180
+ * failure throws.
20181
+ *
20182
+ * @returns {OwneyWithdrawAllResult} one leg per position attempted.
20183
+ */
20184
+ async withdrawAll() {
20185
+ this.requireState();
20186
+ const balances = await this.readBalances(void 0, false);
20187
+ const positions = /* @__PURE__ */ new Map();
20188
+ for (const agentBalance of Object.values(balances.agentBalances ?? {})) {
20189
+ for (const token of agentBalance.tokens ?? []) {
20190
+ if (!(Number(token.amount) > 0)) continue;
20191
+ const key2 = `${token.chainId}:${token.asset}`;
20192
+ const seen = positions.get(key2);
20193
+ if (seen) {
20194
+ seen.amount = String(Number(seen.amount) + Number(token.amount));
20195
+ continue;
20196
+ }
20197
+ positions.set(key2, {
20198
+ chainId: token.chainId,
20199
+ asset: token.asset,
20200
+ amount: token.amount
20201
+ });
20202
+ }
20203
+ }
20204
+ if (positions.size === 0) {
20205
+ throw new OwneyError(
20206
+ "WITHDRAW_NOTHING_TO_WITHDRAW",
20207
+ "There is nothing to withdraw."
20208
+ );
20209
+ }
20210
+ const legs = [];
20211
+ for (const position2 of positions.values()) {
20212
+ try {
20213
+ const result = await this.withdraw({
20214
+ asset: position2.asset,
20215
+ chainId: position2.chainId
20216
+ });
20217
+ legs.push({ ...position2, result });
20218
+ } catch (err) {
20219
+ console.error(
20220
+ `withdrawAll failed for ${position2.asset} on ${position2.chainId}:`,
20221
+ err
20222
+ );
20223
+ legs.push({
20224
+ ...position2,
20225
+ error: err instanceof Error ? err.message : String(err)
20226
+ });
20227
+ }
20228
+ }
20229
+ if (legs.every((leg) => leg.error !== void 0)) {
20230
+ throw new OwneyError(
20231
+ "WITHDRAW_ALL_FAILED",
20232
+ "Failed to withdraw from every position.",
20233
+ {
20234
+ legErrors: Object.fromEntries(
20235
+ legs.map((leg) => [`${leg.asset}:${leg.chainId}`, leg.error])
20236
+ )
20237
+ }
20238
+ );
20239
+ }
20240
+ return { legs };
20241
+ }
19360
20242
  async getBalances(agentId, options) {
19361
20243
  if (agentId) {
19362
20244
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
@@ -19374,7 +20256,11 @@ var OwneySDK = class {
19374
20256
  balanceComposition: agent.balanceComposition ?? "tokens-include-positions"
19375
20257
  };
19376
20258
  }
19377
- const { balances, failures } = await this.readAggregatedBalances(options);
20259
+ const portfolio = options?.chainId === void 0 && options?.asset === void 0;
20260
+ return this.readBalances(options, portfolio);
20261
+ }
20262
+ async readBalances(options, portfolio) {
20263
+ const { balances, failures } = await this.readAggregatedBalances(options, portfolio);
19378
20264
  if (Object.keys(balances.agentBalances).length === 0) {
19379
20265
  throw new OwneyError(
19380
20266
  "BALANCE_ALL_FAILED",
@@ -19385,21 +20271,27 @@ var OwneySDK = class {
19385
20271
  return balances;
19386
20272
  }
19387
20273
  /** Preserve failure objects for withdrawal recovery without changing public balance results. */
19388
- async readAggregatedBalances(options) {
20274
+ async readAggregatedBalances(options, portfolio = false) {
19389
20275
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19390
20276
  const asset = options?.asset;
19391
- const readBalance = (agent) => this.readAgent(
19392
- agent,
20277
+ const readBalance = (read2) => read2.state === state ? this.readAgent(
20278
+ read2.agent,
19393
20279
  "balances",
19394
- () => asset ? agent.getBalances(state, chainId, asset) : agent.getBalances(state, chainId),
20280
+ () => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
19395
20281
  asset ? { asset } : null
20282
+ ) : this.readAgent(
20283
+ read2.agent,
20284
+ "balances",
20285
+ () => read2.agent.getBalances(read2.state, read2.chainId),
20286
+ { chainId: read2.chainId }
19396
20287
  );
19397
20288
  let totalBalance = 0;
19398
20289
  const results = {};
19399
- const entries = [...this.getActiveAgents().entries()];
20290
+ const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
19400
20291
  const balanceResults = await Promise.allSettled(
19401
- entries.map(async ([id, agent]) => {
19402
- const b = await readBalance(agent);
20292
+ entries.map(async ([id, read2]) => {
20293
+ const { agent } = read2;
20294
+ const b = await readBalance(read2);
19403
20295
  return [
19404
20296
  id,
19405
20297
  {
@@ -19456,10 +20348,14 @@ var OwneySDK = class {
19456
20348
  () => agent.getEarnings(state, chainId)
19457
20349
  );
19458
20350
  }
19459
- const entries = [...this.getActiveAgents().entries()];
19460
20351
  return this.aggregateEarnings(
19461
- entries,
19462
- (agent) => this.readAgent(agent, "earnings", () => agent.getEarnings(state, chainId))
20352
+ this.portfolioReads(state, chainId),
20353
+ (read2) => this.readAgent(
20354
+ read2.agent,
20355
+ "earnings",
20356
+ () => read2.agent.getEarnings(read2.state, read2.chainId),
20357
+ read2.state === state ? null : { chainId: read2.chainId }
20358
+ )
19463
20359
  );
19464
20360
  }
19465
20361
  /**
@@ -19469,23 +20365,24 @@ var OwneySDK = class {
19469
20365
  async refreshEarnings(agentId) {
19470
20366
  const state = this.requireState();
19471
20367
  const chainId = this.requireChainId();
19472
- const refreshAgent = (agent) => this.readAgent(
20368
+ const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
19473
20369
  agent,
19474
20370
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
19475
- () => agent.refreshEarnings?.(state, chainId) ?? agent.getEarnings(state, chainId)
20371
+ () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
20372
+ readState === state ? null : { chainId: readChain }
19476
20373
  );
19477
- if (agentId) return refreshAgent(this.getAgent(agentId));
19478
- return this.aggregateEarnings([...this.getActiveAgents().entries()], refreshAgent);
20374
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
20375
+ return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
19479
20376
  }
19480
20377
  async aggregateEarnings(entries, read2) {
19481
- const settled2 = await Promise.allSettled(entries.map(([, agent]) => read2(agent)));
20378
+ const settled2 = await Promise.allSettled(entries.map(read2));
19482
20379
  const agentEarnings = {};
19483
20380
  const agentErrors = {};
19484
20381
  const agentRetryAt = {};
19485
20382
  const failures = [];
19486
20383
  let totalEarnings = 0;
19487
20384
  for (let i = 0; i < settled2.length; i++) {
19488
- const [id] = entries[i];
20385
+ const { id } = entries[i];
19489
20386
  const result = settled2[i];
19490
20387
  if (result.status === "fulfilled") {
19491
20388
  agentEarnings[id] = result.value;
@@ -19532,9 +20429,46 @@ var OwneySDK = class {
19532
20429
  async getDailyEarnings({
19533
20430
  agentId,
19534
20431
  days,
19535
- tokenSymbol
20432
+ tokenSymbol,
20433
+ chainIds
19536
20434
  }) {
19537
20435
  const state = this.requireState();
20436
+ if (chainIds?.length) {
20437
+ const agents = (agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()]).filter((agent) => agent.getDailyEarnings);
20438
+ const legs = [];
20439
+ for (const agent of agents) {
20440
+ for (const legChainId of chainIds) {
20441
+ if (agentRunsOn(agent, legChainId))
20442
+ legs.push({ agent, legChainId, legState: state });
20443
+ }
20444
+ }
20445
+ if (!agentId) {
20446
+ for (const extra of this.offChainPortfolioAgents(state)) {
20447
+ if (!extra.agent.getDailyEarnings) continue;
20448
+ for (const legChainId of chainIds) {
20449
+ if (extra.chainIds.includes(legChainId))
20450
+ legs.push({ agent: extra.agent, legChainId, legState: extra.state });
20451
+ }
20452
+ }
20453
+ }
20454
+ const settled3 = await Promise.allSettled(
20455
+ legs.map(
20456
+ ({ agent, legChainId, legState }) => this.readAgent(
20457
+ agent,
20458
+ "dailyEarnings",
20459
+ () => agent.getDailyEarnings(legState, legChainId, days, tokenSymbol),
20460
+ // The leg's chain must be in the key: the read key otherwise names
20461
+ // only the CONNECTION chain, so every leg shared the first leg's
20462
+ // request and the sum counted that chain once per leg. (ROUT-561)
20463
+ { days, tokenSymbol, chainId: legChainId }
20464
+ )
20465
+ )
20466
+ );
20467
+ const series2 = settled3.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
20468
+ const failure = settled3.find((result) => result.status === "rejected");
20469
+ if (!series2.length && failure?.status === "rejected") throw failure.reason;
20470
+ return mergeDailyEarnings(series2);
20471
+ }
19538
20472
  const chainId = this.requireChainId();
19539
20473
  if (agentId) {
19540
20474
  const agent = this.getAgent(agentId);
@@ -19576,46 +20510,113 @@ var OwneySDK = class {
19576
20510
  assets: aggregateDailyEarnings(series, tokenSymbol)
19577
20511
  };
19578
20512
  }
20513
+ /**
20514
+ * The deposit-time pool catalogue (ROUT-569): every protocol with its
20515
+ * selectable pools (name, APY, TVL, link) for `asset` under `strategy`.
20516
+ * Defaults to the zyfai agent, the only one with pool customization today.
20517
+ */
20518
+ async getPoolCatalog(params) {
20519
+ await this.ensureAgentsInitialized();
20520
+ const agent = this.getAgent(params.agentId ?? "zyfai");
20521
+ if (!agent.getPoolCatalog) {
20522
+ throw new OwneyError(
20523
+ "POOL_CATALOG_UNSUPPORTED",
20524
+ `Agent ${agent.id} does not support pool customization`
20525
+ );
20526
+ }
20527
+ return agent.getPoolCatalog({
20528
+ asset: params.asset,
20529
+ strategy: params.strategy
20530
+ });
20531
+ }
20532
+ /**
20533
+ * Apply a user's deposit-time pool selection to their account (ROUT-569).
20534
+ * The request carries explicit pool choices plus the resulting strategy for
20535
+ * each asset reviewed in the deposit flow.
20536
+ */
20537
+ async setPoolSelection(params) {
20538
+ await this.ensureAgentsInitialized();
20539
+ const agent = this.getAgent(params.agentId ?? "zyfai");
20540
+ if (!agent.setPoolSelection) {
20541
+ throw new OwneyError(
20542
+ "POOL_SELECTION_UNSUPPORTED",
20543
+ `Agent ${agent.id} does not support pool customization`
20544
+ );
20545
+ }
20546
+ await agent.setPoolSelection(params.selection);
20547
+ }
20548
+ /**
20549
+ * The pool selection saved on the user's account (ROUT-650), so the Pools
20550
+ * step can show what applies now rather than the defaults. `pairs` and
20551
+ * `assets` say which protocol/chain lists and strategies to read.
20552
+ */
20553
+ async getPoolSelection(params) {
20554
+ const state = this.requireState();
20555
+ const chainId = this.requireChainId();
20556
+ await this.ensureAgentsInitialized();
20557
+ const agent = this.getAgent(params.agentId ?? "zyfai");
20558
+ if (!agent.getPoolSelection) {
20559
+ throw new OwneyError(
20560
+ "POOL_SELECTION_UNSUPPORTED",
20561
+ `Agent ${agent.id} does not support pool customization`
20562
+ );
20563
+ }
20564
+ return agent.getPoolSelection(state, chainId, {
20565
+ pairs: params.pairs,
20566
+ assets: params.assets
20567
+ });
20568
+ }
19579
20569
  async getAccountApy({
19580
20570
  agentId,
19581
20571
  days,
19582
- tokenSymbol
20572
+ tokenSymbol,
20573
+ chainId: scope
19583
20574
  }) {
19584
20575
  const state = this.requireState();
19585
20576
  const chainId = this.requireChainId();
20577
+ const scopeChainId = scope === "all" ? null : scope;
19586
20578
  if (agentId) {
19587
20579
  const agent = this.getAgent(agentId);
19588
20580
  return this.readAgent(
19589
20581
  agent,
19590
20582
  "accountApy",
19591
- () => agent.getAccountApy(state, chainId, days, tokenSymbol),
19592
- { days, tokenSymbol }
20583
+ () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
20584
+ { days, tokenSymbol, scopeChainId }
19593
20585
  );
19594
20586
  }
19595
- const activeAgents = this.getActiveAgents();
19596
- const entries = [...activeAgents.entries()];
19597
- const [apyResults, balanceResults] = await Promise.all([
19598
- Promise.all(
19599
- entries.map(async ([id, agent]) => {
19600
- const apy = await this.readAgent(
20587
+ const entries = scopeChainId === void 0 ? [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })) : this.portfolioReads(state, chainId).filter((read2) => read2.state === state || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
20588
+ const reads = await Promise.all(
20589
+ entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
20590
+ const offChain = readState !== state;
20591
+ const pair = Promise.all([
20592
+ this.readAgent(
19601
20593
  agent,
19602
20594
  "accountApy",
19603
- () => agent.getAccountApy(state, chainId, days, tokenSymbol),
19604
- { days, tokenSymbol }
19605
- );
19606
- return [id, apy];
19607
- })
19608
- ),
19609
- Promise.all(
19610
- entries.map(async ([id, agent]) => {
19611
- const b = await this.readAgent(agent, "balances", () => agent.getBalances(state, chainId));
19612
- return [
19613
- id,
19614
- balanceForApyScope(b, chainId, tokenSymbol)
19615
- ];
19616
- })
19617
- )
19618
- ]);
20595
+ () => agent.getAccountApy(
20596
+ readState,
20597
+ readChain,
20598
+ days,
20599
+ tokenSymbol,
20600
+ scopeChainId
20601
+ ),
20602
+ offChain ? { days, tokenSymbol, scopeChainId, chainId: readChain } : { days, tokenSymbol, scopeChainId }
20603
+ ),
20604
+ this.readAgent(
20605
+ agent,
20606
+ "balances",
20607
+ () => agent.getBalances(readState, readChain),
20608
+ offChain ? { chainId: readChain } : null
20609
+ ).then((b) => balanceForApyScope(b, readChain, tokenSymbol))
20610
+ ]);
20611
+ if (!offChain) return [id, ...await pair];
20612
+ return pair.then(([apy, balance]) => [id, apy, balance], (error) => {
20613
+ console.error(`[owney-sdk] APY fetch failed for agent "${id}" on chain ${readChain}:`, error);
20614
+ return null;
20615
+ });
20616
+ })
20617
+ );
20618
+ const apyResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[1]]] : []);
20619
+ const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
19619
20620
  const results = {};
19620
20621
  for (const [id, apy] of apyResults) {
19621
20622
  results[id] = apy;
@@ -19666,8 +20667,57 @@ var OwneySDK = class {
19666
20667
  * @returns {OwneyAgentHistory} `data` (up to `limit` entries), `hasMore`, `nextCursor`.
19667
20668
  */
19668
20669
  async getHistory(options) {
20670
+ const { agentId, filters, chainIds } = options ?? {};
20671
+ if (chainIds?.length) {
20672
+ const state2 = this.requireState();
20673
+ const agents = agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()];
20674
+ const cursorMap2 = filters?.cursor ? decodeFanoutCursor(filters.cursor) : void 0;
20675
+ const legs = [];
20676
+ for (const agent of agents) {
20677
+ for (const legChainId of chainIds) {
20678
+ if (agentRunsOn(agent, legChainId))
20679
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
20680
+ }
20681
+ }
20682
+ if (!agentId) {
20683
+ for (const extra of this.offChainPortfolioAgents(state2)) {
20684
+ for (const legChainId of chainIds) {
20685
+ if (extra.chainIds.includes(legChainId))
20686
+ legs.push({ agentId: extra.agent.id, chainId: legChainId, legState: extra.state });
20687
+ }
20688
+ }
20689
+ }
20690
+ const agentErrors2 = {};
20691
+ let firstFailure;
20692
+ const pages = await Promise.all(
20693
+ legs.map(async (leg) => {
20694
+ const legCursor = cursorMap2?.[fanoutKey(leg)];
20695
+ if (cursorMap2 && legCursor === void 0) {
20696
+ return { leg, page: null };
20697
+ }
20698
+ const legFilters = { ...filters, cursor: legCursor };
20699
+ const agent = this.getAgent(leg.agentId);
20700
+ try {
20701
+ const page = await this.readAgent(
20702
+ agent,
20703
+ "history",
20704
+ () => agent.getHistory(leg.legState, leg.chainId, legFilters),
20705
+ // Keyed per leg for the same reason as getDailyEarnings' fan-out.
20706
+ { ...legFilters, chainId: leg.chainId }
20707
+ );
20708
+ return { leg, page };
20709
+ } catch (error) {
20710
+ firstFailure ??= error;
20711
+ agentErrors2[leg.agentId] = error instanceof Error ? error.message : String(error);
20712
+ return { leg, page: null };
20713
+ }
20714
+ })
20715
+ );
20716
+ if (firstFailure !== void 0 && pages.every(({ page }) => page === null)) throw firstFailure;
20717
+ const merged2 = mergeHistoryPages(pages);
20718
+ return Object.keys(agentErrors2).length ? { ...merged2, agentErrors: agentErrors2 } : merged2;
20719
+ }
19669
20720
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19670
- const { agentId, filters } = options ?? {};
19671
20721
  if (agentId) {
19672
20722
  const agent = this.getAgent(agentId);
19673
20723
  const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);