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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -452,6 +452,35 @@ function debugLog(scope, message, data) {
452
452
  // src/lib/routing-api.ts
453
453
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
454
454
  var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
455
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
456
+ const query2 = new URLSearchParams({
457
+ walletAddress: input.walletAddress,
458
+ agentId: input.agentId,
459
+ chainId: String(input.chainId),
460
+ asset: input.asset.toUpperCase(),
461
+ from: input.from,
462
+ to: input.to
463
+ });
464
+ try {
465
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
466
+ headers: {
467
+ Accept: "application/json",
468
+ "x-owney-api-key": apiKey
469
+ }
470
+ });
471
+ if (!response.ok) return [];
472
+ const body = await response.json();
473
+ if (!body.success || !Array.isArray(body.data)) return [];
474
+ return body.data.filter(
475
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
476
+ );
477
+ } catch (error) {
478
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
479
+ error: error instanceof Error ? error.message : String(error)
480
+ });
481
+ return [];
482
+ }
483
+ }
455
484
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
456
485
  const url = `${baseUrl}/api/v1/agent/org-config`;
457
486
  try {
@@ -982,7 +1011,7 @@ var SnapshotHistory = class {
982
1011
  };
983
1012
 
984
1013
  // src/lib/funding-ledger.ts
985
- var SDK_VERSION = "0.7.32-beta.4";
1014
+ var SDK_VERSION = "0.7.32-beta.6";
986
1015
  var SCOPE2 = "funding-ledger";
987
1016
  var REQUEST_TIMEOUT_MS2 = 5e3;
988
1017
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -999,6 +1028,12 @@ function normalizeAppName(appName) {
999
1028
  const lower = appName.toLowerCase();
1000
1029
  return APP_NAME_RE.test(lower) ? lower : void 0;
1001
1030
  }
1031
+ 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}$/;
1032
+ function normalizeBatchId(batchId) {
1033
+ if (typeof batchId !== "string") return void 0;
1034
+ const lower = batchId.toLowerCase();
1035
+ return BATCH_ID_RE.test(lower) ? lower : void 0;
1036
+ }
1002
1037
  function compact(obj) {
1003
1038
  const out = {};
1004
1039
  for (const [key2, value] of Object.entries(obj)) {
@@ -1134,6 +1169,7 @@ function buildReporter(config) {
1134
1169
  asset: input.asset.toLowerCase(),
1135
1170
  requestedAmountRaw: input.requestedAmountRaw,
1136
1171
  isMax: input.isMax,
1172
+ batchId: normalizeBatchId(input.batchId),
1137
1173
  sdkVersion: SDK_VERSION,
1138
1174
  app,
1139
1175
  legs: input.legs?.map((leg) => compact({ ...leg }))
@@ -1143,9 +1179,16 @@ function buildReporter(config) {
1143
1179
  debugLog(SCOPE2, `task failed: ${describeError2(err)}`);
1144
1180
  });
1145
1181
  };
1182
+ let postBody = createBody;
1146
1183
  const create = async () => {
1147
1184
  if (disabled) return false;
1148
- const res = await request2("POST", endpoint2, createBody);
1185
+ let res = await request2("POST", endpoint2, postBody);
1186
+ if (res?.status === 400 && "batchId" in postBody) {
1187
+ const { batchId: _dropped, ...withoutBatchId } = postBody;
1188
+ postBody = withoutBatchId;
1189
+ debugLog(SCOPE2, "create rejected with 400: retrying once without batchId");
1190
+ res = await request2("POST", endpoint2, postBody);
1191
+ }
1149
1192
  if (!res) return false;
1150
1193
  if (res.status === 404) {
1151
1194
  disabled = true;
@@ -2278,7 +2321,7 @@ var CHAIN_NAMES = {
2278
2321
  function chainName(chainId) {
2279
2322
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2280
2323
  }
2281
- var SETTLE_TIMEOUT_MS = 8e3;
2324
+ var SETTLE_TIMEOUT_MS = 15e3;
2282
2325
  var POLL_INTERVAL_MS = 200;
2283
2326
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2284
2327
  async function readChainId(pub) {
@@ -2321,6 +2364,36 @@ async function ensureWalletOnChain(pub, wallet, expected, options = {}) {
2321
2364
  { expectedChainId: expected, actualChainId: after ?? actual }
2322
2365
  );
2323
2366
  }
2367
+ function isActiveChainMismatch(error) {
2368
+ const message = error instanceof Error ? error.message : String(error ?? "");
2369
+ return /must match the active chain/i.test(message) || /does not match the target chain/i.test(message);
2370
+ }
2371
+ async function signWithChainRetry(pub, wallet, expected, sign) {
2372
+ try {
2373
+ return await sign();
2374
+ } catch (error) {
2375
+ if (!isActiveChainMismatch(error)) throw error;
2376
+ try {
2377
+ await wallet.switchChain({ id: expected });
2378
+ } catch {
2379
+ }
2380
+ try {
2381
+ return await sign();
2382
+ } catch (retryError) {
2383
+ if (!isActiveChainMismatch(retryError)) throw retryError;
2384
+ const actual = await readChainId(pub);
2385
+ throw new OwneyError(
2386
+ "CHAIN_MISMATCH",
2387
+ `Your wallet would not sign for ${chainName(expected)}. Open it, switch to ${chainName(expected)}, and try again.`,
2388
+ {
2389
+ expectedChainId: expected,
2390
+ ...actual !== void 0 ? { actualChainId: actual } : {},
2391
+ cause: retryError instanceof Error ? retryError.message : String(retryError)
2392
+ }
2393
+ );
2394
+ }
2395
+ }
2396
+ }
2324
2397
 
2325
2398
  // src/lib/sponsored-deposit.ts
2326
2399
  var AUTH_WINDOW_SECONDS = 15 * 60;
@@ -2843,6 +2916,9 @@ var NAME_TO_CHAIN_ID = Object.entries(
2843
2916
  acc[name.toLowerCase()] = Number(id);
2844
2917
  return acc;
2845
2918
  }, {});
2919
+ NAME_TO_CHAIN_ID.mainnet = 1;
2920
+ NAME_TO_CHAIN_ID["ethereum mainnet"] = 1;
2921
+ NAME_TO_CHAIN_ID["arbitrum one"] = 42161;
2846
2922
  function resolveChainId(chain2) {
2847
2923
  const asNum = Number(chain2);
2848
2924
  if (Number.isFinite(asNum) && asNum > 0) return asNum;
@@ -3093,7 +3169,7 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
3093
3169
  let weightedSum = 0;
3094
3170
  let totalBalance = 0;
3095
3171
  for (const p of entry.positions ?? []) {
3096
- if (p.chainId !== chainId) continue;
3172
+ if (chainId !== void 0 && p.chainId !== chainId) continue;
3097
3173
  if (tokenSymbol && p.tokenSymbol?.toUpperCase() !== tokenSymbol.toUpperCase()) continue;
3098
3174
  const balance = p.balance ?? 0;
3099
3175
  const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
@@ -3103,27 +3179,89 @@ function rawPoolApyForChain(entry, chainId, tokenSymbol) {
3103
3179
  }
3104
3180
  return totalBalance > 0 ? weightedSum / totalBalance : null;
3105
3181
  }
3106
- function mapApyHistory(raw2, chainId, tokenSymbol) {
3107
- const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => ({
3108
- date,
3109
- apy: rawPoolApyForChain(entry, chainId, tokenSymbol),
3110
- // Provider position balances are treated as decimal amounts of the
3111
- // selected token. Carry its unit dynamically for every asset; never
3112
- // attach a token unit to an unscoped mix of assets.
3113
- ...tokenSymbol ? {
3114
- historicalBalance: {
3115
- amount: (entry.positions ?? []).filter(
3116
- (p) => p.chainId === chainId && p.tokenSymbol?.toUpperCase() === tokenSymbol.toUpperCase() && Number.isFinite(p.balance) && p.balance > 0 && Number.isFinite(p.apy_withFee ?? p.apy)
3117
- ).reduce((sum, p) => sum + p.balance, 0),
3118
- unit: tokenSymbol.toUpperCase()
3119
- }
3120
- } : {}
3121
- })).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
3182
+ function historyCoverage(raw2) {
3183
+ const chains = /* @__PURE__ */ new Map();
3184
+ const assets = /* @__PURE__ */ new Map();
3185
+ const pairs = /* @__PURE__ */ new Map();
3186
+ for (const date of Object.keys(raw2.history ?? {}).sort()) {
3187
+ void date;
3188
+ const seenChains = /* @__PURE__ */ new Set();
3189
+ const seenAssets = /* @__PURE__ */ new Set();
3190
+ const seenPairs = /* @__PURE__ */ new Map();
3191
+ for (const p of (raw2.history ?? {})[date].positions ?? []) {
3192
+ const balance = p.balance ?? 0;
3193
+ const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
3194
+ if (balance <= 0 || typeof apy !== "number") continue;
3195
+ seenChains.add(p.chainId);
3196
+ if (p.tokenSymbol) {
3197
+ const asset = p.tokenSymbol.toUpperCase();
3198
+ seenAssets.add(asset);
3199
+ seenPairs.set(`${p.chainId}:${asset}`, { chainId: p.chainId, asset });
3200
+ }
3201
+ }
3202
+ for (const c of seenChains) chains.set(c, (chains.get(c) ?? 0) + 1);
3203
+ for (const a of seenAssets) assets.set(a, (assets.get(a) ?? 0) + 1);
3204
+ for (const [key2, pair] of seenPairs) {
3205
+ pairs.set(key2, { ...pair, days: (pairs.get(key2)?.days ?? 0) + 1 });
3206
+ }
3207
+ }
3208
+ return {
3209
+ chains: [...chains].map(([chainId, days]) => ({ chainId, days })),
3210
+ assets: [...assets].map(([asset, days]) => ({ asset, days })),
3211
+ pairs: [...pairs.values()]
3212
+ };
3213
+ }
3214
+ function isEthToken(symbol2) {
3215
+ const upper = symbol2?.toUpperCase();
3216
+ return upper === "WETH" || upper === "ETH";
3217
+ }
3218
+ function holdsEthPosition(raw2) {
3219
+ return Object.values(raw2.history ?? {}).some((entry) => (entry.positions ?? []).some((p) => isEthToken(p.tokenSymbol)));
3220
+ }
3221
+ function usdPerToken(symbol2, ethUsd) {
3222
+ if (symbol2?.toUpperCase() === "USDC") return 1;
3223
+ return isEthToken(symbol2) ? ethUsd : void 0;
3224
+ }
3225
+ function dollarDay(entry, chainId, ethUsd) {
3226
+ let weightedSum = 0;
3227
+ let totalUsd = 0;
3228
+ for (const p of entry.positions ?? []) {
3229
+ if (chainId !== void 0 && p.chainId !== chainId) continue;
3230
+ const balance = p.balance ?? 0;
3231
+ const apy = netApy(p.apy_withFee, p.apy, "apy_withFee");
3232
+ if (balance <= 0 || typeof apy !== "number") continue;
3233
+ const price = usdPerToken(p.tokenSymbol, ethUsd);
3234
+ if (price === void 0) return void 0;
3235
+ weightedSum += apy * balance * price;
3236
+ totalUsd += balance * price;
3237
+ }
3238
+ return totalUsd > 0 ? { apy: weightedSum / totalUsd, usd: totalUsd } : void 0;
3239
+ }
3240
+ function mapApyHistory(raw2, chainId, tokenSymbol, ethUsd) {
3241
+ const history = Object.entries(raw2.history ?? {}).map(([date, entry]) => {
3242
+ const dollars = tokenSymbol ? void 0 : dollarDay(entry, chainId, ethUsd);
3243
+ return {
3244
+ date,
3245
+ apy: dollars ? dollars.apy : rawPoolApyForChain(entry, chainId, tokenSymbol),
3246
+ // Provider position balances are treated as decimal amounts of the
3247
+ // selected token. Carry its unit dynamically for every asset; an
3248
+ // unscoped mix of assets is carried in dollars, or not at all.
3249
+ ...tokenSymbol ? {
3250
+ historicalBalance: {
3251
+ amount: (entry.positions ?? []).filter(
3252
+ (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)
3253
+ ).reduce((sum, p) => sum + p.balance, 0),
3254
+ unit: tokenSymbol.toUpperCase()
3255
+ }
3256
+ } : dollars ? { historicalBalance: { amount: dollars.usd, unit: "USD" } } : {}
3257
+ };
3258
+ }).filter((p) => p.apy !== null).sort((a, b) => a.date.localeCompare(b.date));
3122
3259
  return {
3123
3260
  walletAddress: raw2.walletAddress,
3124
3261
  weightedApyAfterFee: raw2.weightedApyAfterFee ? sumTokenValues(raw2.weightedApyAfterFee) : void 0,
3125
3262
  apyByChainAndAsset: mapWeightedApyByChain(raw2.weightedApyAfterFeeByChain),
3126
- history
3263
+ history,
3264
+ coverage: historyCoverage(raw2)
3127
3265
  };
3128
3266
  }
3129
3267
  function splitOpportunity(opportunity) {
@@ -3144,6 +3282,9 @@ function mapEntries(rawEntries, chainId) {
3144
3282
  // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
3145
3283
  // the public HistoryAction union, so no consumer type change is needed.
3146
3284
  "Deposit to protocol": "Deposit",
3285
+ // Withdrawing from an async vault (Superform) is logged under its own
3286
+ // label and paid out later in a separate batch (ROUT-624).
3287
+ "Request async withdrawal": "Withdraw",
3147
3288
  Rebalance: "Rebalance"
3148
3289
  };
3149
3290
  void chainId;
@@ -3188,8 +3329,9 @@ function mapEntries(rawEntries, chainId) {
3188
3329
  ];
3189
3330
  }
3190
3331
  const mappedAction = (entry.action ? actionMap[entry.action] : void 0) ?? entry.action;
3332
+ const asyncRequest = entry.action === "Request async withdrawal";
3191
3333
  const rawAmount2 = entry?.positions?.[0]?.amount;
3192
- const hasAmount = mappedAction !== "Withdraw" && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
3334
+ const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
3193
3335
  const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
3194
3336
  entry?.positions?.[0]?.deltaAmount,
3195
3337
  tokenDecimals(entry?.positions?.[0]?.token_symbol)
@@ -3215,6 +3357,7 @@ function mapEntries(rawEntries, chainId) {
3215
3357
  newApy: newApy === null ? null : String(newApy),
3216
3358
  oldApy: oldApy === null ? null : String(oldApy),
3217
3359
  ...mappedPositions.length ? { positions: mappedPositions } : {},
3360
+ ...asyncRequest ? { asyncRequest: true } : {},
3218
3361
  transactions: [
3219
3362
  {
3220
3363
  txHashes: entry.transactionHash ? [entry.transactionHash] : [],
@@ -3374,6 +3517,43 @@ function mapDailyEarnings(raw2, chainId, tokenSymbol) {
3374
3517
  return { walletAddress: raw2.walletAddress, chainId, assets };
3375
3518
  }
3376
3519
 
3520
+ // src/lib/eth-usd-price.ts
3521
+ var BASE_ETH_USD_FEED = "0x71041dddad3595F9CEd3DcCFBe3D1F4b0a16Bb70";
3522
+ var FEED_DECIMALS = 8;
3523
+ var PRICE_TTL_MS = 6e4;
3524
+ var AGGREGATOR_V3_ABI = [{
3525
+ type: "function",
3526
+ name: "latestRoundData",
3527
+ stateMutability: "view",
3528
+ inputs: [],
3529
+ outputs: [
3530
+ { name: "roundId", type: "uint80" },
3531
+ { name: "answer", type: "int256" },
3532
+ { name: "startedAt", type: "uint256" },
3533
+ { name: "updatedAt", type: "uint256" },
3534
+ { name: "answeredInRound", type: "uint80" }
3535
+ ]
3536
+ }];
3537
+ var prices = /* @__PURE__ */ new WeakMap();
3538
+ async function readEthUsdPrice(client, now = Date.now()) {
3539
+ const cached = prices.get(client);
3540
+ if (cached && now - cached.at < PRICE_TTL_MS) return cached.value;
3541
+ try {
3542
+ const [, answer] = await client.readContract({
3543
+ address: BASE_ETH_USD_FEED,
3544
+ abi: AGGREGATOR_V3_ABI,
3545
+ functionName: "latestRoundData"
3546
+ });
3547
+ if (answer <= 0n) return void 0;
3548
+ const value = Number(answer) / 10 ** FEED_DECIMALS;
3549
+ if (!Number.isFinite(value)) return void 0;
3550
+ prices.set(client, { value, at: now });
3551
+ return value;
3552
+ } catch {
3553
+ return void 0;
3554
+ }
3555
+ }
3556
+
3377
3557
  // src/agents/zyfai/zyfai.history-cursor.ts
3378
3558
  var InvalidHistoryCursorError = class extends Error {
3379
3559
  code = "invalid_cursor";
@@ -3569,6 +3749,9 @@ function splittingNeedsUpdate(current, desired) {
3569
3749
  }
3570
3750
 
3571
3751
  // src/agents/zyfai/pool-policy.ts
3752
+ function orgPolicyForConnect(policy, userPoolCustomization) {
3753
+ return userPoolCustomization ? { ...policy, poolPolicy: null } : policy;
3754
+ }
3572
3755
  function toZyfaiCustomizations(policy, availableByProtocol, chainsByProtocol) {
3573
3756
  const selectionByKey = /* @__PURE__ */ new Map();
3574
3757
  for (const selection of policy.selections) {
@@ -3660,6 +3843,54 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
3660
3843
  if (desiredProtocols === null) return false;
3661
3844
  return !protocolListsEqual(current.protocols, desiredProtocols);
3662
3845
  }
3846
+ function mergeScopedPoolNames(current, scoped, allAvailableNames) {
3847
+ const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
3848
+ const existing = current.autoselect ? allAvailableNames : current.pools;
3849
+ const preserved = existing.filter((name) => !managed.has(name));
3850
+ const selected = scoped.flatMap((entry) => entry.pools);
3851
+ return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
3852
+ }
3853
+ function mapAvailablePools(raw2) {
3854
+ const byChain = raw2 ?? {};
3855
+ if (typeof byChain !== "object" || byChain === null) return [];
3856
+ const result = [];
3857
+ for (const [chainIdStr, byToken] of Object.entries(byChain)) {
3858
+ const chainId = Number(chainIdStr);
3859
+ if (!Number.isFinite(chainId)) continue;
3860
+ for (const [token, entry] of Object.entries(byToken ?? {})) {
3861
+ for (const pool of entry?.pools ?? []) {
3862
+ if (!pool?.name) continue;
3863
+ result.push({
3864
+ chainId,
3865
+ token,
3866
+ name: pool.name,
3867
+ apy: pool.info?.combined_apy ?? null,
3868
+ tvlUsd: pool.info?.tvlUsd ?? null,
3869
+ link: pool.info?.link ?? null
3870
+ });
3871
+ }
3872
+ }
3873
+ }
3874
+ return result;
3875
+ }
3876
+ function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
3877
+ const wanted = asset.toUpperCase();
3878
+ const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
3879
+ const catalog = [];
3880
+ for (const protocol of protocols) {
3881
+ const pools = (poolsByProtocol.get(protocol.id) ?? []).filter(
3882
+ (p) => p.token.toUpperCase() === wanted && (allowedChains === void 0 || allowedChains.has(p.chainId))
3883
+ );
3884
+ if (pools.length === 0) continue;
3885
+ catalog.push({
3886
+ protocolId: protocol.id,
3887
+ name: protocol.name,
3888
+ logo: protocol.imageUrl ?? null,
3889
+ pools
3890
+ });
3891
+ }
3892
+ return catalog;
3893
+ }
3663
3894
 
3664
3895
  // src/lib/agent-accounts.ts
3665
3896
  var SCOPE5 = "agent-accounts";
@@ -4159,7 +4390,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4159
4390
  */
4160
4391
  async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
4161
4392
  const movements = entries.filter(
4162
- (e) => (e.action === "Withdraw" || e.action === "Top up") && e.transactions[0]?.txHashes[0]
4393
+ (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
4163
4394
  );
4164
4395
  if (movements.length === 0) return;
4165
4396
  const client = this.getPublicClient(chainId);
@@ -4230,11 +4461,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
4230
4461
  if (typeof window === "undefined") return;
4231
4462
  const internals = sdk;
4232
4463
  const original = internals.authenticateUser.bind(internals);
4233
- internals.authenticateUser = async () => {
4464
+ let inFlight2 = null;
4465
+ const authenticate = async () => {
4234
4466
  if (internals.authenticatedUserId !== null) return;
4235
4467
  const address = internals.walletClient?.account?.address;
4236
- const chainId = internals.currentChainId;
4237
- if (address && chainId) {
4468
+ const chainId = internals.currentChainId ?? 0;
4469
+ if (address) {
4238
4470
  const cached = readSession(address, chainId);
4239
4471
  if (cached) {
4240
4472
  internals.httpClient.setAuthToken(cached.token);
@@ -4246,9 +4478,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
4246
4478
  }
4247
4479
  await original();
4248
4480
  const newAddress = internals.walletClient?.account?.address;
4249
- const newChainId = internals.currentChainId;
4481
+ const newChainId = internals.currentChainId ?? 0;
4250
4482
  const newToken = internals.httpClient.authToken;
4251
- if (newAddress && newChainId && newToken) {
4483
+ if (newAddress && newToken) {
4252
4484
  writeSession(newAddress, newChainId, {
4253
4485
  token: newToken,
4254
4486
  userId: internals.authenticatedUserId,
@@ -4257,6 +4489,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
4257
4489
  });
4258
4490
  }
4259
4491
  };
4492
+ internals.authenticateUser = () => {
4493
+ const address = internals.walletClient?.account?.address?.toLowerCase();
4494
+ if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
4495
+ const promise = authenticate().finally(() => {
4496
+ if (inFlight2?.promise === promise) inFlight2 = null;
4497
+ });
4498
+ inFlight2 = { address, promise };
4499
+ return promise;
4500
+ };
4260
4501
  }
4261
4502
  // --- Private helpers ---
4262
4503
  getAddress() {
@@ -4390,9 +4631,22 @@ var ZyfaiAgent = class _ZyfaiAgent {
4390
4631
  this.sdk.getUserDetails(asset),
4391
4632
  this.sdk.getAvailableProtocols(chainId)
4392
4633
  ]);
4634
+ debugLog("zyfai:protocol-sync", `${asset}: profile before sync`, {
4635
+ chains: current.chains,
4636
+ protocols: current.protocols,
4637
+ strategy: current.strategy
4638
+ });
4639
+ if ((current.chains?.length ?? 0) === 0 && (current.protocols?.length ?? 0) === 0) {
4640
+ debugLog(
4641
+ "zyfai:protocol-sync",
4642
+ `${asset}: skipping untouched profile until first deposit`
4643
+ );
4644
+ return;
4645
+ }
4393
4646
  const update = buildProtocolMergeUpdate(available, current, asset);
4394
4647
  if (!update) return;
4395
4648
  await this.sdk.updateUserProfile(update);
4649
+ debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
4396
4650
  } catch (error) {
4397
4651
  console.warn(
4398
4652
  "[zyfai] ensureProtocolsSynced failed (non-fatal):",
@@ -4401,10 +4655,28 @@ var ZyfaiAgent = class _ZyfaiAgent {
4401
4655
  }
4402
4656
  }
4403
4657
  /** Connect + resolve smart wallet address for read operations. */
4658
+ /**
4659
+ * Sign-in for reads: any live session of this owner will do. Zyfai's session
4660
+ * is per user and its data calls name the chain themselves, so reading
4661
+ * Arbitrum while signed in on Base needs no new sign-in. `connectAuth` pins
4662
+ * the chain, and reconnecting per chain made the whole-portfolio reads (one
4663
+ * per chain, in parallel) cancel each other's sign-in. Funding keeps
4664
+ * `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
4665
+ * so a later reconnect cannot leave the caller without an address.
4666
+ */
4667
+ async ensureReadSession(state, chainId) {
4668
+ const owner = state.walletAddress?.toLowerCase();
4669
+ if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
4670
+ if (!owner || this.connectedAddress?.toLowerCase() !== owner) await this.connectAuth(state, chainId);
4671
+ }
4672
+ /** `ensureReadSession`, then the owner it verified, read in the same turn. */
4673
+ async connectForRead(state, chainId) {
4674
+ await this.ensureReadSession(state, chainId);
4675
+ return this.getAddress();
4676
+ }
4404
4677
  async resolveSmartWallet(state, chainId) {
4405
- await this.connectAuth(state, chainId);
4406
4678
  const validChainId = isValidChainId(chainId);
4407
- const ownerAddress = this.getAddress();
4679
+ const ownerAddress = await this.connectForRead(state, validChainId);
4408
4680
  const smartWallet = await this.readSmartWallet(ownerAddress, validChainId);
4409
4681
  return { smartWallet, chainId: validChainId };
4410
4682
  }
@@ -4458,8 +4730,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
4458
4730
  }
4459
4731
  // --- IAgent: Account lifecycle ---
4460
4732
  async activateAgent(state, chainId) {
4733
+ const startedAt = Date.now();
4461
4734
  try {
4735
+ debugLog("zyfai:activation", "starting", {
4736
+ walletAddress: state.walletAddress,
4737
+ chainId
4738
+ });
4462
4739
  await this.connectAuth(state, chainId);
4740
+ debugLog("zyfai:activation", "signed in", {
4741
+ ms: Date.now() - startedAt
4742
+ });
4463
4743
  const validChainId = isValidChainId(chainId);
4464
4744
  await Promise.all([
4465
4745
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -4470,6 +4750,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
4470
4750
  // validator, so pool-wallet users see no prompt. Non-fatal.
4471
4751
  this.ensureSessionKeyIfDeployed(validChainId)
4472
4752
  ]);
4753
+ debugLog("zyfai:activation", "completed", {
4754
+ chainId: validChainId,
4755
+ ms: Date.now() - startedAt
4756
+ });
4473
4757
  } catch (error) {
4474
4758
  throw error;
4475
4759
  }
@@ -4550,8 +4834,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
4550
4834
  * connecting, so a Zyfai hiccup must leave the user connected with their
4551
4835
  * profile unchanged, never fail activation.
4552
4836
  */
4553
- async applyPoolPolicy(policy) {
4837
+ async applyPoolPolicy(policy, opts = {}) {
4554
4838
  try {
4839
+ await this.sdk.ensureFirstDepositSetup("aggressive");
4555
4840
  const { protocols: universe } = await this.sdk.getAvailableProtocols(
4556
4841
  this.supportedChainIds[0]
4557
4842
  );
@@ -4564,7 +4849,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4564
4849
  universeIds,
4565
4850
  chainsByProtocol
4566
4851
  });
4567
- let strategy;
4852
+ let strategy = opts.strategy;
4568
4853
  const desiredProtocols = deriveProtocols(
4569
4854
  policy,
4570
4855
  universeIds,
@@ -4644,6 +4929,143 @@ var ZyfaiAgent = class _ZyfaiAgent {
4644
4929
  );
4645
4930
  }
4646
4931
  }
4932
+ /**
4933
+ * The deposit-time Pools step's catalogue: every protocol Zyfai offers this
4934
+ * user, each with the pools (name, APY, TVL, link) selectable for `asset`
4935
+ * under `strategy`. Sourced from the same two Zyfai calls `applyPoolPolicy`
4936
+ * uses, so "shown" and "selectable" are one set. A protocol whose pool
4937
+ * lookup fails is skipped rather than failing the whole catalogue.
4938
+ */
4939
+ async getPoolCatalog(params) {
4940
+ const { protocols: universe } = await this.sdk.getAvailableProtocols(
4941
+ this.supportedChainIds[0]
4942
+ );
4943
+ const poolResults = await Promise.all(
4944
+ universe.map(async (protocol) => {
4945
+ try {
4946
+ const raw2 = await this.sdk.getAvailablePools(
4947
+ protocol.id,
4948
+ params.strategy
4949
+ );
4950
+ return [protocol.id, mapAvailablePools(raw2)];
4951
+ } catch (error) {
4952
+ console.warn(
4953
+ `[zyfai] getPoolCatalog: getAvailablePools(${protocol.id}) failed, skipping (non-fatal):`,
4954
+ error instanceof Error ? error.message : String(error)
4955
+ );
4956
+ return null;
4957
+ }
4958
+ })
4959
+ );
4960
+ const poolsByProtocol = /* @__PURE__ */ new Map();
4961
+ for (const result of poolResults) {
4962
+ if (result) poolsByProtocol.set(result[0], result[1]);
4963
+ }
4964
+ return assemblePoolCatalog(universe, poolsByProtocol, params.asset);
4965
+ }
4966
+ /**
4967
+ * Persist an explicitly saved deposit-time draft at Zyfai profile level.
4968
+ * Pool choices are merged into protocol/chain records and each active asset
4969
+ * is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
4970
+ * The whole operation must succeed before the caller starts moving funds.
4971
+ */
4972
+ async setPoolSelection(selection) {
4973
+ try {
4974
+ await this.sdk.ensureFirstDepositSetup("aggressive");
4975
+ const byPair = /* @__PURE__ */ new Map();
4976
+ for (const entry of selection.selections) {
4977
+ const pair = `${entry.protocolId}:${entry.chainId}`;
4978
+ const group = byPair.get(pair) ?? [];
4979
+ group.push(entry);
4980
+ byPair.set(pair, group);
4981
+ }
4982
+ const customizations = await Promise.all(
4983
+ [...byPair.values()].map(async (scoped) => {
4984
+ const { protocolId, chainId } = scoped[0];
4985
+ const [current, rawAvailable] = await Promise.all([
4986
+ this.sdk.getSelectedPools(protocolId, chainId),
4987
+ this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
4988
+ ]);
4989
+ const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
4990
+ return {
4991
+ protocolId,
4992
+ chainId,
4993
+ pools: mergeScopedPoolNames(
4994
+ {
4995
+ pools: current.pools ?? [],
4996
+ autoselect: current.autoselect
4997
+ },
4998
+ scoped,
4999
+ allAvailableNames
5000
+ ),
5001
+ // An explicit Save freezes exactly the choices the user saw.
5002
+ // This also lets an empty list disable the pair deliberately.
5003
+ autoselect: false
5004
+ };
5005
+ })
5006
+ );
5007
+ if (customizations.length > 0) {
5008
+ await this.sdk.customizeBatch(customizations);
5009
+ }
5010
+ await Promise.all(
5011
+ selection.strategies.map(async ({ asset, strategy }) => {
5012
+ const current = await this.sdk.getUserDetails(asset);
5013
+ const selectedProtocols = selection.selections.filter(
5014
+ (entry) => entry.asset === asset && entry.pools.length > 0
5015
+ ).map((entry) => entry.protocolId);
5016
+ const protocols = [
5017
+ .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
5018
+ ];
5019
+ await this.sdk.updateUserProfile({ asset, strategy, protocols });
5020
+ })
5021
+ );
5022
+ } catch (error) {
5023
+ console.warn(
5024
+ "[zyfai] setPoolSelection failed:",
5025
+ error instanceof Error ? error.message : String(error)
5026
+ );
5027
+ throw error;
5028
+ }
5029
+ }
5030
+ /**
5031
+ * Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
5032
+ * pools per protocol/chain and the strategy per asset; both are read for the
5033
+ * pairs and assets asked about. A pair still on autoselect, or one whose
5034
+ * lookup fails, is left out so the caller falls back to its default for it.
5035
+ */
5036
+ async getPoolSelection(state, chainId, params) {
5037
+ await this.connectAuth(state, chainId);
5038
+ const [pairs, strategies] = await Promise.all([
5039
+ Promise.all(
5040
+ params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
5041
+ try {
5042
+ const current = await this.sdk.getSelectedPools(
5043
+ protocolId,
5044
+ chainId2
5045
+ );
5046
+ if (current.autoselect) return null;
5047
+ return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
5048
+ } catch {
5049
+ return null;
5050
+ }
5051
+ })
5052
+ ),
5053
+ Promise.all(
5054
+ params.assets.map(async (asset) => {
5055
+ try {
5056
+ const current = await this.sdk.getUserDetails(asset);
5057
+ return current.strategy ? { asset, strategy: current.strategy } : null;
5058
+ } catch {
5059
+ return null;
5060
+ }
5061
+ })
5062
+ )
5063
+ ]);
5064
+ return {
5065
+ pairs: pairs.filter((value) => value !== null),
5066
+ strategies: strategies.filter((value) => value !== null)
5067
+ };
5068
+ }
4647
5069
  /**
4648
5070
  * True when `smartWallet` is the backend-managed pool wallet Zyfai assigned
4649
5071
  * to this EOA — the "new wallet" kind that is predeployed on the chains it
@@ -4800,11 +5222,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4800
5222
  );
4801
5223
  return;
4802
5224
  }
4803
- await this.ensureSessionKey(
4804
- ownerAddress,
4805
- chainId,
4806
- wallet.address
4807
- );
5225
+ await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
4808
5226
  } catch (error) {
4809
5227
  console.warn(
4810
5228
  "[zyfai] session-key check at activation failed (non-fatal):",
@@ -4915,11 +5333,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4915
5333
  "zyfai:onboard",
4916
5334
  "Safe already has code -> no deploy needed, checking the session key"
4917
5335
  );
4918
- await this.ensureSessionKey(
4919
- ownerAddress,
4920
- chainId,
4921
- wallet.address
4922
- );
5336
+ await this.ensureSessionKey(ownerAddress, chainId, wallet.address);
4923
5337
  return wallet.address;
4924
5338
  }
4925
5339
  const poolFirst = await this.isPredeployedPoolWallet(
@@ -4985,6 +5399,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
4985
5399
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while preparing Zyfai deposit.", void 0, this.id);
4986
5400
  };
4987
5401
  assertCurrent();
5402
+ const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
5403
+ debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
5404
+ if (isOwneyDebug()) {
5405
+ try {
5406
+ const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
5407
+ debugLog(
5408
+ "zyfai:first-deposit",
5409
+ "profile immediately after setup",
5410
+ { asset, strategy: profile.strategy, chains: profile.chains, protocols: profile.protocols }
5411
+ );
5412
+ } catch (debugError) {
5413
+ debugLog(
5414
+ "zyfai:first-deposit",
5415
+ "post-setup profile read failed",
5416
+ { error: debugError instanceof Error ? debugError.message : String(debugError) }
5417
+ );
5418
+ }
5419
+ }
5420
+ assertCurrent();
4988
5421
  const smartWallet = await this.ensureWalletDeployed(owner, validChainId);
4989
5422
  assertCurrent();
4990
5423
  let server;
@@ -6016,6 +6449,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6016
6449
  const generation = this.earningsGeneration;
6017
6450
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
6018
6451
  const raw2 = await this.sdk.getPortfolio(this.getAddress());
6452
+ debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
6019
6453
  const balance = mapBalances(raw2, validChainId, smartWallet);
6020
6454
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
6021
6455
  for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
@@ -6212,7 +6646,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6212
6646
  }
6213
6647
  async refreshEarnings(state, chainId) {
6214
6648
  const generation = this.earningsGeneration;
6215
- await this.connectAuth(state, chainId);
6649
+ await this.ensureReadSession(state, chainId);
6216
6650
  const executionSdk = this.sdk;
6217
6651
  const connectionGeneration = this.connectionGeneration;
6218
6652
  const assertCurrent = () => {
@@ -6254,14 +6688,18 @@ var ZyfaiAgent = class _ZyfaiAgent {
6254
6688
  this.earningsRefreshes.set(key2, pending);
6255
6689
  return pending;
6256
6690
  }
6257
- async getAccountApy(state, chainId, days, tokenSymbol) {
6691
+ async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
6258
6692
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
6259
6693
  const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
6260
- return mapApyHistory(raw2, chainId, tokenSymbol);
6694
+ const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
6695
+ const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
6696
+ return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
6261
6697
  }
6262
6698
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
6263
6699
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
6264
- const start = new Date(Date.now() - (DayFilterMapping[days] + 1) * 864e5);
6700
+ const start = new Date(
6701
+ Date.now() - (DayFilterMapping[days] + 1) * 864e5
6702
+ );
6265
6703
  const raw2 = await this.sdk.getDailyEarnings(
6266
6704
  smartWallet,
6267
6705
  start.toISOString().slice(0, 10)
@@ -6354,7 +6792,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6354
6792
  };
6355
6793
  }
6356
6794
  async getUserProfile(state, chainId) {
6357
- await this.connectAuth(state, chainId);
6795
+ await this.ensureReadSession(state, chainId);
6358
6796
  const raw2 = await this.sdk.getUserDetails();
6359
6797
  debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
6360
6798
  asset: "USDC (default \u2014 no asset passed)",
@@ -6371,6 +6809,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
6371
6809
  async ensureAutoSelectProtocols(state, chainId, asset) {
6372
6810
  await this.connectAuth(state, chainId);
6373
6811
  const current = await this.sdk.getUserDetails(asset);
6812
+ debugLog("zyfai:auto-select", `${asset}: profile before check`, {
6813
+ autoSelectProtocols: current.autoSelectProtocols,
6814
+ chains: current.chains,
6815
+ protocols: current.protocols,
6816
+ strategy: current.strategy
6817
+ });
6818
+ if ((current.chains?.length ?? 0) === 0) {
6819
+ debugLog(
6820
+ "zyfai:auto-select",
6821
+ `${asset}: skipping untouched profile until first deposit`
6822
+ );
6823
+ return false;
6824
+ }
6374
6825
  const update = buildAutoSelectUpdate(
6375
6826
  {
6376
6827
  autoSelectProtocols: current.autoSelectProtocols,
@@ -6381,6 +6832,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6381
6832
  );
6382
6833
  if (!update) return false;
6383
6834
  await this.sdk.updateUserProfile(update);
6835
+ debugLog("zyfai:auto-select", `${asset}: wrote profile update`, update);
6384
6836
  return true;
6385
6837
  }
6386
6838
  // --- IAgent: Discovery (no wallet required) ---
@@ -6412,6 +6864,27 @@ import {
6412
6864
  } from "viem";
6413
6865
  import { base as base4 } from "viem/chains";
6414
6866
 
6867
+ // src/lib/wallet-rejection.ts
6868
+ var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
6869
+ function isWalletRejection(error) {
6870
+ let current = error;
6871
+ const seen = /* @__PURE__ */ new Set();
6872
+ while (current && typeof current === "object" && !seen.has(current)) {
6873
+ seen.add(current);
6874
+ const candidate = current;
6875
+ if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
6876
+ const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
6877
+ if (REJECTION_MESSAGE.test(message)) return true;
6878
+ const details = candidate.details;
6879
+ if (details && typeof details === "object") {
6880
+ const cause = details.cause;
6881
+ if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
6882
+ }
6883
+ current = candidate.cause;
6884
+ }
6885
+ return false;
6886
+ }
6887
+
6415
6888
  // src/agents/yieldseeker/yieldseeker.auth.ts
6416
6889
  import { SiweMessage, generateNonce } from "siwe";
6417
6890
  import {
@@ -6615,6 +7088,14 @@ var YieldseekerAuth = class {
6615
7088
  }
6616
7089
  return this.getToken(state, chainId);
6617
7090
  }
7091
+ /** Drop a proof the provider refused, without signing a new one: a
7092
+ * promptless read cannot renew it, and must stop offering it. */
7093
+ discardToken(state, chainId, rejectedToken) {
7094
+ const key2 = this.key(state, chainId);
7095
+ if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
7096
+ if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken)
7097
+ clearYieldseekerSession(state.walletAddress, chainId);
7098
+ }
6618
7099
  isReusable(token, state, chainId) {
6619
7100
  try {
6620
7101
  const message = new SiweMessage(JSON.parse(atob(token)).message);
@@ -7070,18 +7551,19 @@ function dailyApy(point) {
7070
7551
  if (principal <= 0n || earned === 0n) return 0;
7071
7552
  return Number(earned) / Number(principal) * 365 * 100;
7072
7553
  }
7073
- function aggregateHistory(contexts, dayCount, now) {
7554
+ function aggregateHistory(contexts, dayCount, now, scopedAsset) {
7074
7555
  const today = new Date(now).toISOString().slice(0, 10);
7075
7556
  const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
7076
7557
  const assets = new Set(contexts.map((context) => context.asset.toUpperCase()));
7077
- const unit = assets.size === 1 ? [...assets][0] : "USD";
7558
+ const tokenUnits = scopedAsset !== void 0 && assets.size <= 1;
7559
+ const unit = tokenUnits ? scopedAsset.toUpperCase() : "USD";
7078
7560
  const byDate = /* @__PURE__ */ new Map();
7079
7561
  for (const context of contexts) {
7080
7562
  const points = context.historic?.dailyYieldSnapshots ?? [];
7081
7563
  for (const point of points) {
7082
7564
  if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || !Number.isFinite(Date.parse(point.date)) || point.date < cutoff || point.date > today) continue;
7083
7565
  const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
7084
- const amount = assets.size === 1 ? tokens : tokens * point.baseAssetPriceUsd;
7566
+ const amount = tokenUnits ? tokens : tokens * point.baseAssetPriceUsd;
7085
7567
  if (!Number.isFinite(amount) || amount < 0) {
7086
7568
  invalid("historic position", "expected a finite non-negative balance");
7087
7569
  }
@@ -7097,7 +7579,30 @@ function aggregateHistory(contexts, dayCount, now) {
7097
7579
  historicalBalance: { amount: value.amount, unit }
7098
7580
  }));
7099
7581
  }
7100
- function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
7582
+ function historyCoverage2(contexts, dayCount, now) {
7583
+ const today = new Date(now).toISOString().slice(0, 10);
7584
+ const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
7585
+ const datesByAsset = /* @__PURE__ */ new Map();
7586
+ const allDates = /* @__PURE__ */ new Set();
7587
+ for (const context of contexts) {
7588
+ for (const point of context.historic?.dailyYieldSnapshots ?? []) {
7589
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
7590
+ if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
7591
+ const asset = context.asset.toUpperCase();
7592
+ const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
7593
+ dates.add(point.date);
7594
+ datesByAsset.set(asset, dates);
7595
+ allDates.add(point.date);
7596
+ }
7597
+ }
7598
+ const assets = [...datesByAsset].map(([asset, dates]) => ({ asset, days: dates.size }));
7599
+ return {
7600
+ chains: allDates.size ? [{ chainId: 8453, days: allDates.size }] : [],
7601
+ assets,
7602
+ pairs: assets.map((entry) => ({ chainId: 8453, ...entry }))
7603
+ };
7604
+ }
7605
+ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scopedAsset) {
7101
7606
  let weighted = 0;
7102
7607
  let totalUsd = 0;
7103
7608
  const byAsset = {};
@@ -7118,7 +7623,8 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now()) {
7118
7623
  walletAddress,
7119
7624
  ...days !== "14D" || Object.keys(byAsset).length > 0 ? { weightedApyAfterFee: totalUsd > 0 ? weighted / totalUsd : 0 } : {},
7120
7625
  apyByChainAndAsset: { 8453: byAsset },
7121
- history: aggregateHistory(contexts, dayCount, now)
7626
+ history: aggregateHistory(contexts, dayCount, now, scopedAsset),
7627
+ coverage: historyCoverage2(contexts, dayCount, now)
7122
7628
  };
7123
7629
  }
7124
7630
  function actionType(value) {
@@ -7425,11 +7931,13 @@ function mapYieldseekerProfile(address, contexts) {
7425
7931
  protocols: [...protocols]
7426
7932
  };
7427
7933
  }
7428
- function mapYieldseekerAgentApy(stats) {
7934
+ function mapYieldseekerAgentApy(stats, days) {
7429
7935
  const perAsset = {};
7430
7936
  const all = [];
7431
7937
  for (const entry of stats) {
7432
- const expected = percent(entry.stats.expectedApy7d);
7938
+ const expected = percent(
7939
+ days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
7940
+ );
7433
7941
  if (!Number.isFinite(expected)) continue;
7434
7942
  perAsset[entry.asset] = expected;
7435
7943
  all.push(expected);
@@ -7608,6 +8116,15 @@ function sponsorError(message, safeToFallback, details = {}) {
7608
8116
  "yieldseeker"
7609
8117
  );
7610
8118
  }
8119
+ function cannotSignRawHash(error) {
8120
+ for (let current = error, depth = 0; current && depth < 5; depth++) {
8121
+ const code = current.code;
8122
+ if (code === -32602 || code === -32601 || code === 4200) return true;
8123
+ if (code === 4001) return false;
8124
+ current = current.cause;
8125
+ }
8126
+ return false;
8127
+ }
7611
8128
  function assertIntentFresh(expiresAt) {
7612
8129
  if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
7613
8130
  throw sponsorError(
@@ -7969,7 +8486,18 @@ async function submitEoa(input) {
7969
8486
  transport: custom3(input.state.provider)
7970
8487
  });
7971
8488
  input.assertCurrent?.();
7972
- const signature = await wallet.signMessage({ message: { raw: userOpHash } });
8489
+ let signature;
8490
+ try {
8491
+ signature = await wallet.signMessage({ message: { raw: userOpHash } });
8492
+ } catch (error) {
8493
+ if (cannotSignRawHash(error))
8494
+ throw sponsorError(
8495
+ "This wallet cannot sign the gas-free withdrawal.",
8496
+ true,
8497
+ { failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
8498
+ );
8499
+ throw error;
8500
+ }
7973
8501
  operation = { ...operation, signature };
7974
8502
  await assertOwnerSession(input.state, input.owner);
7975
8503
  assertIntentFresh(input.expiresAt);
@@ -8241,11 +8769,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
8241
8769
  var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
8242
8770
  var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
8243
8771
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
8772
+ var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
8773
+ var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
8774
+ var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
8775
+ var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
8244
8776
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
8245
8777
  var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
8246
8778
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
8247
8779
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
8248
8780
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
8781
+ function apyAsPercent(fraction) {
8782
+ if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
8783
+ return Number((fraction * 100).toPrecision(12));
8784
+ }
8785
+ function isActiveMemory(memory) {
8786
+ return !!memory && memory.isActive !== false && memory.isDeleted !== true;
8787
+ }
8788
+ function vaultOptionsKey(asset, includeUnavailable) {
8789
+ return `${asset}:${includeUnavailable ? "all" : "usable"}`;
8790
+ }
8791
+ function isManagedVaultList(memory) {
8792
+ return memory.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
8793
+ }
8794
+ function isLegacyPoolSelectionMemory(memory) {
8795
+ if (isManagedVaultList(memory) || typeof memory.content !== "string") return false;
8796
+ const content = memory.content.trim();
8797
+ return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
8798
+ }
8799
+ function uniqueAddresses(addresses) {
8800
+ const seen = /* @__PURE__ */ new Set();
8801
+ return addresses.filter((address) => {
8802
+ const key2 = address.toLowerCase();
8803
+ if (seen.has(key2)) return false;
8804
+ seen.add(key2);
8805
+ return true;
8806
+ });
8807
+ }
8808
+ function sameVaults(actual, expected) {
8809
+ const want = new Set(expected.map((address) => address.toLowerCase()));
8810
+ const got = new Set(actual.map((address) => address.toLowerCase()));
8811
+ return got.size === want.size && [...want].every((address) => got.has(address));
8812
+ }
8249
8813
  function isYieldseekerWalletCodeMissing(error) {
8250
8814
  for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
8251
8815
  const { name, message } = current;
@@ -8255,6 +8819,8 @@ function isYieldseekerWalletCodeMissing(error) {
8255
8819
  return false;
8256
8820
  }
8257
8821
  var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
8822
+ var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
8823
+ var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
8258
8824
  var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
8259
8825
  var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
8260
8826
  var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
@@ -8274,6 +8840,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
8274
8840
  var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
8275
8841
  var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
8276
8842
  var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
8843
+ var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
8277
8844
  var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
8278
8845
  var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
8279
8846
  function generateYieldseekerUsername() {
@@ -8366,9 +8933,31 @@ var YieldseekerAgent = class {
8366
8933
  walletContexts = /* @__PURE__ */ new Map();
8367
8934
  agentAccountReads = /* @__PURE__ */ new Map();
8368
8935
  reportedAccounts = /* @__PURE__ */ new Set();
8369
- // Slots whose verified agent is missing even from a re-read list, until the
8370
- // list cache window ends. Stops a re-read on every portfolio poll.
8936
+ // Slots whose verified agent is missing even from a re-read list (and could
8937
+ // not be reopened), with the error the lookup failed with, until the list
8938
+ // cache window ends. Stops a re-read and a reactivate on every portfolio poll.
8371
8939
  missingSlots = /* @__PURE__ */ new Map();
8940
+ // A remembered rate limit rethrown with the time left on its marker
8941
+ // (throwIfSlotMissing), mapped to the remembered error it copies, so
8942
+ // isMarkedSlotFailure still recognises it.
8943
+ rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
8944
+ // Slots whose verified agent Yieldseeker will never reopen (a reactivate
8945
+ // answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
8946
+ // slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
8947
+ // it is kept for the session, like unavailableSlots: reads and deposits get
8948
+ // it with no request until disconnect, or until a lookup selects an agent
8949
+ // for the slot.
8950
+ closedSlots = /* @__PURE__ */ new Map();
8951
+ // In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
8952
+ // shared by concurrent lookups of one slot.
8953
+ pendingReopens = /* @__PURE__ */ new Map();
8954
+ // Slots Yieldseeker will not give an agent this session (a reactivate answered
8955
+ // an active-agent limit), keyed by slotKey, with the provider's limit code.
8956
+ // Never expires: it answers without a request until disconnect.
8957
+ unavailableSlots = /* @__PURE__ */ new Map();
8958
+ // In-flight reactivates keyed by slotKey + agentId, shared by every caller
8959
+ // (a read-time reopen, deposits): one request however many ask.
8960
+ pendingReactivates = /* @__PURE__ */ new Map();
8372
8961
  // In-flight cache-bypassing list reads, shared by concurrent callers.
8373
8962
  freshListReads = /* @__PURE__ */ new Map();
8374
8963
  // Every contextKey computed this session; asset-only calls fall back to them.
@@ -8421,6 +9010,7 @@ var YieldseekerAgent = class {
8421
9010
  ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
8422
9011
  /** slotKey -> the last successful ledger rows and when they arrived. */
8423
9012
  lastLedgerRows = /* @__PURE__ */ new Map();
9013
+ /** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
8424
9014
  vaultOptions = /* @__PURE__ */ new Map();
8425
9015
  pendingVaultOptions = /* @__PURE__ */ new Map();
8426
9016
  assetApyStats = /* @__PURE__ */ new Map();
@@ -8478,36 +9068,57 @@ var YieldseekerAgent = class {
8478
9068
  return { ...await pending };
8479
9069
  }
8480
9070
  /**
8481
- * Deposits go only to a wallet whose identity is verified on chain (factory
8482
- * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
8483
- * the provider API returned is not trusted on its own. V1 wallets still
8484
- * accept deposits: only identity is required, not the V2 implementation.
8485
- * A failed read fails closed (reason UNAVAILABLE): an unverified wallet never
8486
- * receives funds. Session changes keep their own NOT_CONNECTED error.
9071
+ * Deposits go only to an agent Yieldseeker still has open. The session caches
9072
+ * the selected agent, so a tab left open can hold one Yieldseeker has since
9073
+ * closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
9074
+ * bypassing the cached wallet contexts, and:
9075
+ * - open, same wallet address: returns the context to deposit with;
9076
+ * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9077
+ * continues only when it is now open with the same address. Only the
9078
+ * verified record's agent is reopened: any other closed agent (a
9079
+ * superseded-wallet match, or a named agent with no verified record, also
9080
+ * when the accounts could not be read) refuses without a request;
9081
+ * - anything else refuses with nothing sent, before any progress event,
9082
+ * signature or callback. Every refusal carries `notSubmitted` and
9083
+ * `safeToFallback: false`, so no paid fallback runs.
9084
+ * A slot recorded unavailable (the active-agent limit) refuses at once with
9085
+ * no request. The reactivate goes through reactivateSlot, which shares one
9086
+ * request per slot and remembers a failure for the list-cache window, so
9087
+ * repeated deposits do not repeat it. A failed wallet read fails closed
9088
+ * (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
9089
+ * gate. A reactivate that fails keeps its error code
9090
+ * (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
9091
+ * failure). At the limit the slot is also recorded unavailable for the
9092
+ * session (see isSlotUnavailable). Session changes keep their own
9093
+ * NOT_CONNECTED error.
8487
9094
  */
8488
- async assertDepositWalletVerified(state, chainId, asset, context) {
9095
+ async assertAgentOpen(state, chainId, asset, context) {
8489
9096
  const generation = this.readGeneration;
9097
+ const agentId = context.agent.agentId;
8490
9098
  const agentWallet = context.wallet.walletAddress;
8491
- const deployedAt = this.recentDeployments.get(agentWallet.toLowerCase());
8492
- const justDeployed = deployedAt !== void 0 && Date.now() - deployedAt < YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS;
8493
- let status;
8494
- for (let attempt = 0; ; attempt++) {
9099
+ const refusal = { notSubmitted: true, safeToFallback: false };
9100
+ const slot = this.slotKey(state, chainId, asset);
9101
+ const unavailable = this.unavailableSlots.get(slot);
9102
+ if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
9103
+ const readWallet = async () => {
9104
+ let fresh2;
8495
9105
  try {
8496
- status = await this.readWalletStatus(state, chainId, asset, context, true);
8497
- break;
9106
+ const answer = await this.walletRequest(
9107
+ state,
9108
+ chainId,
9109
+ this.agentPath(context, "wallet")
9110
+ );
9111
+ if (!answer?.agentWallet || !isAddress4(answer.agentWallet.walletAddress)) {
9112
+ throw this.invalidResponse("agent wallet");
9113
+ }
9114
+ fresh2 = answer.agentWallet;
8498
9115
  } catch (error) {
8499
9116
  this.assertSession(generation, chainId, asset);
8500
- if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
8501
- await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
8502
- this.assertSession(generation, chainId, asset);
8503
- continue;
8504
- }
8505
9117
  throw new OwneyError(
8506
9118
  "YIELDSEEKER_WALLET_UNVERIFIED",
8507
- "Could not verify the Yieldseeker Agent Wallet on chain. Nothing was sent. Please retry.",
9119
+ "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
8508
9120
  {
8509
- notSubmitted: true,
8510
- safeToFallback: false,
9121
+ ...refusal,
8511
9122
  reason: "UNAVAILABLE",
8512
9123
  agentWallet,
8513
9124
  asset,
@@ -8516,20 +9127,114 @@ var YieldseekerAgent = class {
8516
9127
  this.id
8517
9128
  );
8518
9129
  }
8519
- }
8520
- if (!status.verified || status.agentWallet.toLowerCase() !== agentWallet.toLowerCase()) {
8521
- throw new OwneyError(
8522
- "YIELDSEEKER_WALLET_UNVERIFIED",
8523
- "The Yieldseeker Agent Wallet failed on-chain verification. Nothing was sent.",
8524
- { notSubmitted: true, safeToFallback: false, reason: "IDENTITY_MISMATCH", agentWallet, asset },
8525
- this.id
8526
- );
8527
- }
8528
- }
8529
- rememberWalletStatus(key2, status) {
8530
- if (status.verified && status.version === "v2") {
8531
- this.withdrawalVersionCache.set(key2, { at: Date.now(), status: { ...status } });
8532
- if (this.withdrawalVersionCache.size > 128)
9130
+ this.assertSession(generation, chainId, asset);
9131
+ return fresh2;
9132
+ };
9133
+ let fresh = await readWallet();
9134
+ let reopened = false;
9135
+ if (fresh.deactivatedDate) {
9136
+ this.forgetAgentWallet(agentId);
9137
+ const accounts = await this.agentAccounts(state, chainId);
9138
+ this.assertSession(generation, chainId, asset);
9139
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
9140
+ if (!verified || verified.providerAgentId !== agentId) {
9141
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
9142
+ }
9143
+ let result;
9144
+ try {
9145
+ result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
9146
+ } catch (error) {
9147
+ this.assertSession(generation, chainId, asset);
9148
+ const failure = error instanceof OwneyError ? error : this.mapApiError(error);
9149
+ if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
9150
+ const { providerCode, reason } = failure.details ?? {};
9151
+ throw this.agentClosed(
9152
+ chainId,
9153
+ asset,
9154
+ agentId,
9155
+ typeof providerCode === "string" ? providerCode : void 0,
9156
+ { ...refusal, ...typeof reason === "string" ? { reason } : {} }
9157
+ );
9158
+ }
9159
+ throw new OwneyError(
9160
+ failure.code,
9161
+ `Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
9162
+ { ...failure.details, ...refusal, cause: failure.message },
9163
+ failure.agentId
9164
+ );
9165
+ }
9166
+ this.assertSession(generation, chainId, asset);
9167
+ if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
9168
+ this.forgetAgentWallet(agentId);
9169
+ fresh = await readWallet();
9170
+ if (fresh.deactivatedDate) {
9171
+ this.rememberMissingSlot(
9172
+ slot,
9173
+ generation,
9174
+ this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
9175
+ );
9176
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
9177
+ }
9178
+ reopened = true;
9179
+ }
9180
+ if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
9181
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
9182
+ }
9183
+ return reopened ? { ...context, wallet: fresh } : context;
9184
+ }
9185
+ /**
9186
+ * Deposits go only to a wallet whose identity is verified on chain (factory
9187
+ * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
9188
+ * the provider API returned is not trusted on its own. V1 wallets still
9189
+ * accept deposits: only identity is required, not the V2 implementation.
9190
+ * A failed read fails closed (reason UNAVAILABLE): an unverified wallet never
9191
+ * receives funds. Session changes keep their own NOT_CONNECTED error.
9192
+ */
9193
+ async assertDepositWalletVerified(state, chainId, asset, context) {
9194
+ const generation = this.readGeneration;
9195
+ const agentWallet = context.wallet.walletAddress;
9196
+ const deployedAt = this.recentDeployments.get(agentWallet.toLowerCase());
9197
+ const justDeployed = deployedAt !== void 0 && Date.now() - deployedAt < YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS;
9198
+ let status;
9199
+ for (let attempt = 0; ; attempt++) {
9200
+ try {
9201
+ status = await this.readWalletStatus(state, chainId, asset, context, true);
9202
+ break;
9203
+ } catch (error) {
9204
+ this.assertSession(generation, chainId, asset);
9205
+ if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
9206
+ await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
9207
+ this.assertSession(generation, chainId, asset);
9208
+ continue;
9209
+ }
9210
+ throw new OwneyError(
9211
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9212
+ "Could not verify the Yieldseeker Agent Wallet on chain. Nothing was sent. Please retry.",
9213
+ {
9214
+ notSubmitted: true,
9215
+ safeToFallback: false,
9216
+ reason: "UNAVAILABLE",
9217
+ agentWallet,
9218
+ asset,
9219
+ cause: error instanceof Error ? error.message : String(error)
9220
+ },
9221
+ this.id
9222
+ );
9223
+ }
9224
+ }
9225
+ if (!status.verified || status.agentWallet.toLowerCase() !== agentWallet.toLowerCase()) {
9226
+ throw new OwneyError(
9227
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9228
+ "The Yieldseeker Agent Wallet failed on-chain verification. Nothing was sent.",
9229
+ { notSubmitted: true, safeToFallback: false, reason: "IDENTITY_MISMATCH", agentWallet, asset },
9230
+ this.id
9231
+ );
9232
+ }
9233
+ }
9234
+ rememberWalletStatus(key2, status) {
9235
+ if (status.verified && status.version === "v2") {
9236
+ this.withdrawalVersionCache.set(key2, { at: Date.now(), status: { ...status } });
9237
+ if (this.withdrawalVersionCache.size > 128)
8533
9238
  this.withdrawalVersionCache.delete(this.withdrawalVersionCache.keys().next().value);
8534
9239
  } else this.withdrawalVersionCache.delete(key2);
8535
9240
  }
@@ -8786,6 +9491,10 @@ var YieldseekerAgent = class {
8786
9491
  this.pendingSlotInvalidations.clear();
8787
9492
  this.knownContextKeys.clear();
8788
9493
  this.missingSlots.clear();
9494
+ this.closedSlots.clear();
9495
+ this.pendingReopens.clear();
9496
+ this.pendingReactivates.clear();
9497
+ this.unavailableSlots.clear();
8789
9498
  this.freshListReads.clear();
8790
9499
  this.balanceVaults.clear();
8791
9500
  this.pendingAgents.clear();
@@ -8813,11 +9522,43 @@ var YieldseekerAgent = class {
8813
9522
  this.planHistoryKeys.clear();
8814
9523
  this.lastLedgerRows.clear();
8815
9524
  }
9525
+ /**
9526
+ * Ready every asset's agent, `asset` first: a missing one is created and a
9527
+ * closed one reopened (2026-11-06). A slot Yieldseeker will never let the
9528
+ * user have (the agent limit, closed for good, missing with no way to
9529
+ * reopen) is rethrown with `details.permanent`, which refuses the connect.
9530
+ * A temporary failure (an API error or timeout) on another asset does not:
9531
+ * that slot answers again where it is needed. On the selected asset every
9532
+ * failure is thrown as before, without readying the rest, so a failed
9533
+ * sign-in never opens a second prompt.
9534
+ */
8816
9535
  async activateAgent(state, chainId, asset) {
8817
9536
  this.assertChain(chainId);
8818
9537
  const targetAsset = asset ?? "USDC";
8819
9538
  this.assertAsset(targetAsset);
8820
- await this.ensureAgent(state, chainId, targetAsset);
9539
+ const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
9540
+ for (const each of [targetAsset, ...others]) {
9541
+ try {
9542
+ await this.ensureAgent(state, chainId, each);
9543
+ } catch (error) {
9544
+ if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
9545
+ const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
9546
+ if (each === targetAsset || !temporary) throw error;
9547
+ debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
9548
+ code: error.code,
9549
+ statusCode: error.details?.statusCode
9550
+ });
9551
+ }
9552
+ }
9553
+ }
9554
+ /** The same failure, marked as one that will not go away this session. */
9555
+ permanentFailure(error) {
9556
+ const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
9557
+ return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
9558
+ }
9559
+ isSlotUnavailable(state, chainId, asset) {
9560
+ if (asset !== "USDC" && asset !== "WETH") return false;
9561
+ return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
8821
9562
  }
8822
9563
  async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
8823
9564
  this.assertChain(chainId);
@@ -8830,7 +9571,20 @@ var YieldseekerAgent = class {
8830
9571
  this.id
8831
9572
  );
8832
9573
  }
8833
- const context = await this.ensureAgent(state, chainId, asset);
9574
+ const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
9575
+ if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
9576
+ const { agentId, providerCode, reason } = error.details ?? {};
9577
+ throw this.agentClosed(
9578
+ chainId,
9579
+ asset,
9580
+ typeof agentId === "string" ? agentId : "",
9581
+ typeof providerCode === "string" ? providerCode : void 0,
9582
+ { notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
9583
+ );
9584
+ }
9585
+ throw error;
9586
+ });
9587
+ const context = await this.assertAgentOpen(state, chainId, asset, selected);
8834
9588
  await this.assertDepositWalletVerified(state, chainId, asset, context);
8835
9589
  const generation = this.readGeneration;
8836
9590
  const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
@@ -9020,15 +9774,14 @@ var YieldseekerAgent = class {
9020
9774
  if (timer) clearTimeout(timer);
9021
9775
  }
9022
9776
  };
9023
- const feeRateRead = amount === void 0 ? Promise.resolve(0) : boundedVerification(
9024
- (() => {
9025
- try {
9026
- return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9027
- } catch (error) {
9028
- return Promise.reject(error);
9029
- }
9030
- })().catch(() => void 0)
9031
- );
9777
+ const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
9778
+ try {
9779
+ return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9780
+ } catch (error) {
9781
+ return Promise.reject(error);
9782
+ }
9783
+ })().catch(() => void 0);
9784
+ const feeRateRead = boundedVerification(feeRateAnswer);
9032
9785
  const positionsRead = this.readWithdrawalPositions(state, chainId, context);
9033
9786
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
9034
9787
  const agentWallet = getAddress6(context.wallet.walletAddress);
@@ -9338,9 +10091,10 @@ var YieldseekerAgent = class {
9338
10091
  }
9339
10092
  const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
9340
10093
  const availableForOwner = ownerFunds.available;
9341
- const feeRate = feeRateBps ?? 0;
9342
- const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9343
10094
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10095
+ const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
10096
+ this.assertSession(generation, chainId, asset);
10097
+ const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9344
10098
  if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
9345
10099
  this.invalidateFundingRead(state, chainId, asset);
9346
10100
  if (amount === void 0 && positionsStatus !== "empty")
@@ -9594,7 +10348,7 @@ var YieldseekerAgent = class {
9594
10348
  positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
9595
10349
  const needsInventory = !proof.inventoryComplete;
9596
10350
  if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
9597
- const catalog = await this.loadVaultOptions(asset).catch(() => []);
10351
+ const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
9598
10352
  const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && isAddress4(o.address));
9599
10353
  if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
9600
10354
  for (const option of eligible) {
@@ -9670,7 +10424,8 @@ var YieldseekerAgent = class {
9670
10424
  const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
9671
10425
  const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
9672
10426
  const receivedAssets = new Set((historic?.movements ?? []).filter((movement) => movement.chainId === chainId && movement.agentWalletId === context.wallet.agentWalletId && movement.toAddress?.toLowerCase() === context.wallet.walletAddress.toLowerCase()).filter((movement) => typeof movement.assetAddress === "string").map((movement) => movement.assetAddress.toLowerCase()));
9673
- for (const option of this.vaultOptions.get(context.asset)?.value ?? []) {
10427
+ const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
10428
+ for (const option of cachedOptions?.value ?? []) {
9674
10429
  if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !isAddress4(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
9675
10430
  hints.set(option.address.toLowerCase(), {
9676
10431
  vaultOption: option,
@@ -9883,7 +10638,7 @@ var YieldseekerAgent = class {
9883
10638
  assertReadCurrent();
9884
10639
  return proof(true);
9885
10640
  }
9886
- const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
10641
+ const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
9887
10642
  assertReadCurrent();
9888
10643
  const eligible = /* @__PURE__ */ new Map();
9889
10644
  for (const option of catalog ?? []) {
@@ -9913,6 +10668,9 @@ var YieldseekerAgent = class {
9913
10668
  if (timer) clearTimeout(timer);
9914
10669
  }
9915
10670
  }
10671
+ hasReadSession(state, chainId) {
10672
+ return this.supportedChainIds.includes(chainId) && this.auth.peekToken(state, chainId) !== void 0;
10673
+ }
9916
10674
  async getBalances(state, chainId, asset) {
9917
10675
  this.assertChain(chainId);
9918
10676
  if (asset !== void 0) this.assertAsset(asset);
@@ -10023,8 +10781,37 @@ var YieldseekerAgent = class {
10023
10781
  }
10024
10782
  return false;
10025
10783
  }
10784
+ /**
10785
+ * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10786
+ * it now instead of on its next 30-minute check. Yieldseeker decides whether
10787
+ * anything moves (the funding minimum, a deployed agent, no manual
10788
+ * withdrawal in the last hour). Uses the agent this session already knows
10789
+ * for the asset and the saved sign-in only: never prompts, never retries,
10790
+ * never throws.
10791
+ */
10792
+ async depositConfirmed(state, chainId, evidence) {
10793
+ try {
10794
+ const asset = String(evidence.token).toUpperCase();
10795
+ if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10796
+ return { notified: false, reason: "UNSUPPORTED" };
10797
+ const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10798
+ if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10799
+ return { notified: false, reason: "NO_AGENT" };
10800
+ if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
10801
+ await this.walletRequest(
10802
+ state,
10803
+ chainId,
10804
+ this.agentPath(context, "deposit-made"),
10805
+ { method: "POST", body: {}, promptless: true }
10806
+ );
10807
+ return { notified: true };
10808
+ } catch (error) {
10809
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
10810
+ }
10811
+ }
10026
10812
  async getFundingWallet(state, chainId, asset) {
10027
10813
  this.assertAsset(asset);
10814
+ this.throwIfSlotUnavailable(state, chainId, asset);
10028
10815
  const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10029
10816
  if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
10030
10817
  return context.wallet.walletAddress;
@@ -10051,15 +10838,17 @@ var YieldseekerAgent = class {
10051
10838
  const contexts = await this.loadPortfolio(state, chainId, { includePositions: false, ledger: true });
10052
10839
  return mapYieldseekerEarnings(await Promise.all(contexts.map((context) => this.applyEarningsHold(state, chainId, context))));
10053
10840
  }
10054
- async getAccountApy(state, chainId, days, tokenSymbol) {
10841
+ async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
10055
10842
  this.assertChain(chainId);
10056
10843
  const asset = tokenSymbol?.toUpperCase();
10057
10844
  if (asset !== void 0) this.assertAsset(asset);
10845
+ if (typeof scopeChainId === "number" && !this.supportedChainIds.includes(scopeChainId))
10846
+ return mapYieldseekerApy(state.walletAddress, [], days);
10058
10847
  const contexts = await this.loadPortfolio(state, chainId, {
10059
10848
  ...asset ? { asset } : {},
10060
10849
  historic: true
10061
10850
  });
10062
- return mapYieldseekerApy(state.walletAddress, contexts, days);
10851
+ return mapYieldseekerApy(state.walletAddress, contexts, days, Date.now(), asset);
10063
10852
  }
10064
10853
  async getDailyEarnings(state, chainId, days, tokenSymbol) {
10065
10854
  this.assertChain(chainId);
@@ -10083,7 +10872,7 @@ var YieldseekerAgent = class {
10083
10872
  });
10084
10873
  const catalog = await Promise.all(
10085
10874
  [...new Set(contexts.map((context) => context.asset))].map(
10086
- (contextAsset) => this.loadVaultOptions(contextAsset)
10875
+ (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
10087
10876
  )
10088
10877
  );
10089
10878
  const vaultAddresses = new Set(
@@ -10108,11 +10897,11 @@ var YieldseekerAgent = class {
10108
10897
  );
10109
10898
  }
10110
10899
  async getAgentApy(days, options) {
10111
- if (!this.supportsAgentApyPeriod(days)) {
10900
+ if (days === "14D") {
10112
10901
  throw new OwneyError(
10113
10902
  "AGENT_APY_PERIOD_UNSUPPORTED",
10114
10903
  `Yieldseeker does not provide a representative ${days} strategy APY.`,
10115
- { days, supportedDays: ["7D"] },
10904
+ { days, supportedDays: ["7D", "30D"] },
10116
10905
  this.id
10117
10906
  );
10118
10907
  }
@@ -10125,10 +10914,10 @@ var YieldseekerAgent = class {
10125
10914
  return { asset, stats: await this.loadAssetApyStats(asset) };
10126
10915
  })
10127
10916
  );
10128
- return mapYieldseekerAgentApy(values);
10917
+ return mapYieldseekerAgentApy(values, days);
10129
10918
  }
10130
10919
  supportsAgentApyPeriod(days) {
10131
- return days === "7D";
10920
+ return days === "7D" || days === "30D";
10132
10921
  }
10133
10922
  async loadAssetApyStats(asset) {
10134
10923
  const cached = this.assetApyStats.get(asset);
@@ -10140,7 +10929,7 @@ var YieldseekerAgent = class {
10140
10929
  `/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
10141
10930
  ).then((response) => {
10142
10931
  const stats = response?.assetApyStats;
10143
- if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d)) {
10932
+ if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d) || typeof stats.expectedApy30d !== "number" || !Number.isFinite(stats.expectedApy30d)) {
10144
10933
  throw this.invalidResponse("asset APY statistics");
10145
10934
  }
10146
10935
  this.assetApyStats.set(asset, {
@@ -10152,27 +10941,321 @@ var YieldseekerAgent = class {
10152
10941
  this.pendingAssetApyStats.set(asset, request2);
10153
10942
  return request2;
10154
10943
  }
10155
- async loadVaultOptions(asset) {
10156
- const cached = this.vaultOptions.get(asset);
10944
+ /**
10945
+ * The deposit-time Pools step's catalogue: every vault Yieldseeker lists
10946
+ * for a new agent on `asset` on Base, grouped by provider (the provider is
10947
+ * both `protocolId` and `name`). Nothing is filtered on our side, on
10948
+ * liquidity, size or provider. `strategy` is accepted for the IAgent
10949
+ * contract and ignored.
10950
+ */
10951
+ async getPoolCatalog(params) {
10952
+ const asset = params.asset.toUpperCase();
10953
+ this.assertAsset(asset);
10954
+ const byProvider = /* @__PURE__ */ new Map();
10955
+ for (const vault of await this.loadVaultOptions(asset)) {
10956
+ const pools = byProvider.get(vault.provider) ?? [];
10957
+ pools.push({
10958
+ chainId: 8453,
10959
+ token: asset,
10960
+ name: vault.name,
10961
+ apy: apyAsPercent(vault.totalApy),
10962
+ tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
10963
+ link: null,
10964
+ address: vault.address
10965
+ });
10966
+ byProvider.set(vault.provider, pools);
10967
+ }
10968
+ return [...byProvider].map(([provider, pools]) => ({
10969
+ protocolId: provider,
10970
+ name: provider,
10971
+ logo: null,
10972
+ pools
10973
+ }));
10974
+ }
10975
+ /**
10976
+ * The asset's vaults on Base. By default only those a new agent can use:
10977
+ * Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
10978
+ * among them), gated or can't use, so the picker follows its list
10979
+ * (2026-11-04). `includeUnavailable` adds those back, for anything about
10980
+ * money an agent may still hold in one: withdrawals and activity.
10981
+ */
10982
+ async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
10983
+ const key2 = vaultOptionsKey(asset, includeUnavailable);
10984
+ const cached = this.vaultOptions.get(key2);
10157
10985
  if (cached && cached.expiresAt > Date.now()) return cached.value;
10158
- const pending = this.pendingVaultOptions.get(asset);
10986
+ const pending = this.pendingVaultOptions.get(key2);
10159
10987
  if (pending) return pending;
10160
10988
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
10161
10989
  const request2 = this.api.request(
10162
- `/chains/8453/assets/${metadata.address}/vault-options`
10990
+ `/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
10163
10991
  ).then((response) => {
10164
10992
  if (!Array.isArray(response?.vaultOptions)) {
10165
10993
  throw this.invalidResponse("vault options");
10166
10994
  }
10167
- this.vaultOptions.set(asset, {
10995
+ this.vaultOptions.set(key2, {
10168
10996
  expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
10169
10997
  value: response.vaultOptions
10170
10998
  });
10171
10999
  return response.vaultOptions;
10172
- }).finally(() => this.pendingVaultOptions.delete(asset));
10173
- this.pendingVaultOptions.set(asset, request2);
11000
+ }).finally(() => this.pendingVaultOptions.delete(key2));
11001
+ this.pendingVaultOptions.set(key2, request2);
10174
11002
  return request2;
10175
11003
  }
11004
+ /**
11005
+ * Save the user's Yieldseeker picks as the agent's managed vault list, then
11006
+ * read the rules back before any money moves. Each asset has its own agent,
11007
+ * so each is saved on its own. `pools` and `availablePools` hold vault
11008
+ * addresses.
11009
+ *
11010
+ * - Only Base entries are ours. An asset with no picks whose entries showed
11011
+ * no vault is skipped and nothing is sent.
11012
+ * - Some vaults picked: the managed list names them. Saving it again
11013
+ * replaces it, so there is only ever one.
11014
+ * - None picked (vaults shown): the managed list names no vault, and the
11015
+ * rules must read back as an empty allow-list. Yieldseeker then keeps the
11016
+ * agent's money out of every vault, as Zyfai does with an empty pool list,
11017
+ * and the next Pools step reads "none". Only an agent that already exists
11018
+ * is written: one is never created just to hold "none".
11019
+ * - Every vault picked: the managed list is deleted, and no allow-list may
11020
+ * remain, so vaults Yieldseeker adds later are allowed too.
11021
+ * - A free-text allow-list we saved before the managed list existed is
11022
+ * deleted once the new state is written. A failed delete does not fail the
11023
+ * save; it is debug-logged, and the read-back decides.
11024
+ * - A read-back that differs puts the previous managed list back (or deletes
11025
+ * the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
11026
+ * it back fails too, that is still the error thrown. An old free-text list
11027
+ * already deleted is not put back.
11028
+ * - An agent already holding the most active memories, none of them ours,
11029
+ * throws POOL_SELECTION_RULE_LIMIT before anything is written.
11030
+ *
11031
+ * Always Base, whichever chain the wallet is connected on.
11032
+ */
11033
+ async setPoolSelection(selection, state) {
11034
+ if (!state) {
11035
+ throw new OwneyError(
11036
+ "NOT_CONNECTED",
11037
+ "Connect a wallet before saving Yieldseeker pool picks.",
11038
+ void 0,
11039
+ this.id
11040
+ );
11041
+ }
11042
+ const byAsset = /* @__PURE__ */ new Map();
11043
+ for (const entry of selection.selections) {
11044
+ if (entry.chainId !== 8453) continue;
11045
+ this.assertAsset(entry.asset);
11046
+ const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
11047
+ group.picked.push(...entry.pools);
11048
+ group.shown.push(...entry.availablePools);
11049
+ byAsset.set(entry.asset, group);
11050
+ }
11051
+ for (const [asset, group] of byAsset) {
11052
+ const picks = uniqueAddresses(group.picked);
11053
+ const shown = uniqueAddresses(group.shown);
11054
+ if (picks.length === 0 && shown.length === 0) continue;
11055
+ const picked = new Set(picks.map((address) => address.toLowerCase()));
11056
+ const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11057
+ await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11058
+ }
11059
+ }
11060
+ async savePoolPicks(state, asset, picks, everyVaultPicked) {
11061
+ const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11062
+ if (!context) {
11063
+ debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11064
+ return;
11065
+ }
11066
+ const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11067
+ const managed = active.find(isManagedVaultList);
11068
+ const legacy = active.filter(isLegacyPoolSelectionMemory);
11069
+ const writing = !everyVaultPicked;
11070
+ if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
11071
+ throw new OwneyError(
11072
+ "POOL_SELECTION_RULE_LIMIT",
11073
+ `This Yieldseeker ${asset} agent already has ${active.length} active memories, the most it allows, so the pool selection could not be saved. Nothing was written.`,
11074
+ { asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
11075
+ this.id
11076
+ );
11077
+ }
11078
+ const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
11079
+ const change = { previous: managed, written: false };
11080
+ if (content === void 0) {
11081
+ if (managed) {
11082
+ await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
11083
+ method: "POST"
11084
+ });
11085
+ change.written = true;
11086
+ }
11087
+ } else {
11088
+ const answer = await this.memoryRequest(state, context, "memories", {
11089
+ method: "POST",
11090
+ body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11091
+ });
11092
+ change.written = true;
11093
+ if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
11094
+ }
11095
+ await this.deleteLegacyPoolMemories(state, context, asset, legacy);
11096
+ let failure;
11097
+ try {
11098
+ const allowed = await this.readAllowList(state, context);
11099
+ const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
11100
+ if (!applied) failure = "ALLOW_LIST_MISMATCH";
11101
+ } catch {
11102
+ failure = "READ_BACK_FAILED";
11103
+ }
11104
+ if (!failure) return;
11105
+ const restored = await this.restorePoolMemory(state, context, change);
11106
+ throw new OwneyError(
11107
+ "POOL_SELECTION_NOT_APPLIED",
11108
+ `Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
11109
+ { asset, reason: failure, restored },
11110
+ this.id
11111
+ );
11112
+ }
11113
+ /**
11114
+ * Delete the free-text allow-lists we saved before the managed list existed.
11115
+ * Never throws: a list left behind is caught by the read-back. Logs no
11116
+ * sign-in token.
11117
+ */
11118
+ async deleteLegacyPoolMemories(state, context, asset, memories) {
11119
+ for (const memory of memories) {
11120
+ try {
11121
+ await this.memoryRequest(state, context, `memories/${memory.agentMemoryId}/delete`, {
11122
+ method: "POST"
11123
+ });
11124
+ } catch (error) {
11125
+ debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
11126
+ memoryId: memory.agentMemoryId,
11127
+ code: error instanceof OwneyError ? error.code : void 0,
11128
+ message: error instanceof Error ? error.message : void 0
11129
+ });
11130
+ }
11131
+ }
11132
+ }
11133
+ /**
11134
+ * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11135
+ * has no brackets. No picks names no vault.
11136
+ */
11137
+ async poolMemoryContent(asset, picks) {
11138
+ if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11139
+ const vaults = new Map(
11140
+ (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11141
+ );
11142
+ const entries = picks.map((pick) => {
11143
+ const vault = vaults.get(pick.toLowerCase());
11144
+ const address = vault?.address ?? pick;
11145
+ return vault?.name ? `${address} (${vault.name})` : address;
11146
+ });
11147
+ return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
11148
+ }
11149
+ /** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
11150
+ async restorePoolMemory(state, context, change) {
11151
+ if (!change.written) return true;
11152
+ try {
11153
+ if (change.previous) {
11154
+ await this.memoryRequest(state, context, "memories", {
11155
+ method: "POST",
11156
+ body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11157
+ });
11158
+ return true;
11159
+ }
11160
+ const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory) => isActiveMemory(memory) && isManagedVaultList(memory)).map((memory) => memory.agentMemoryId);
11161
+ for (const id of ids) {
11162
+ await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
11163
+ }
11164
+ return true;
11165
+ } catch {
11166
+ return false;
11167
+ }
11168
+ }
11169
+ /**
11170
+ * What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
11171
+ * pairs: the allowed vault addresses under the provider each belongs to, for
11172
+ * the vaults a new agent can use. An agent with no allow-list adds nothing,
11173
+ * and no pairs at all means every shown vault is on. Reads never create an
11174
+ * agent, and always read Base. A read that fails throws, because "no
11175
+ * allow-list" would wrongly mean "everything".
11176
+ *
11177
+ * An allow-list naming none of the listed vaults (the saved "none", or vaults
11178
+ * Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
11179
+ * it reports none chosen for its asset: a pair with empty `pools` for every
11180
+ * provider listing vaults for it. With no vault listed at all there is
11181
+ * nothing to name that by, and it throws: the rules still restrict the agent.
11182
+ *
11183
+ * `pairs` is accepted for the contract but does not trim the answer: cutting
11184
+ * a real allow-list down to the pairs asked about could leave none, and none
11185
+ * reads as every vault on.
11186
+ */
11187
+ async getPoolSelection(state, _chainId, params) {
11188
+ const byProvider = /* @__PURE__ */ new Map();
11189
+ for (const asset of new Set(params.assets)) {
11190
+ this.assertAsset(asset);
11191
+ const context = await this.findAgent(state, 8453, asset);
11192
+ if (!context) continue;
11193
+ const allowed = await this.readAllowList(state, context);
11194
+ if (allowed === void 0) continue;
11195
+ const options = await this.loadVaultOptions(asset);
11196
+ if (options.length === 0) {
11197
+ throw this.invalidResponse("pool selection", {
11198
+ reason: "vault-options lists no vault while an allow-list restricts the agent.",
11199
+ asset
11200
+ });
11201
+ }
11202
+ const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
11203
+ const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
11204
+ if (known.length === 0) {
11205
+ for (const vault of options) {
11206
+ if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
11207
+ }
11208
+ continue;
11209
+ }
11210
+ for (const vault of known) {
11211
+ const pools = byProvider.get(vault.provider) ?? [];
11212
+ byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
11213
+ }
11214
+ }
11215
+ return {
11216
+ strategies: [],
11217
+ pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
11218
+ };
11219
+ }
11220
+ /**
11221
+ * The allow-list in the agent's rules: every `allowedVaultAddresses` on an
11222
+ * `ignored_vault` user rule. Undefined when no rule has one, which allows
11223
+ * every vault; an empty list allows none. A response that does not have the
11224
+ * expected shape throws rather than reading as no allow-list.
11225
+ */
11226
+ async readAllowList(state, context) {
11227
+ const rules = await this.memoryRequest(
11228
+ state,
11229
+ context,
11230
+ "memories/effective-rules"
11231
+ );
11232
+ if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
11233
+ let allowed;
11234
+ for (const rule of rules.userRules) {
11235
+ if (rule?.ruleType !== "ignored_vault") continue;
11236
+ const list = rule.ruleConfig?.allowedVaultAddresses;
11237
+ if (list === void 0 || list === null) continue;
11238
+ if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
11239
+ throw this.invalidResponse("effective rules");
11240
+ }
11241
+ allowed = [...allowed ?? [], ...list];
11242
+ }
11243
+ return allowed;
11244
+ }
11245
+ async listMemories(state, context) {
11246
+ const response = await this.memoryRequest(state, context, "memories");
11247
+ if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
11248
+ return response.memories;
11249
+ }
11250
+ /** A memory call for an agent, on Base whichever chain the wallet is on. */
11251
+ async memoryRequest(state, context, suffix, options = {}) {
11252
+ try {
11253
+ return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
11254
+ } catch (error) {
11255
+ if (error instanceof OwneyError) throw error;
11256
+ throw this.mapRequestFailure(error);
11257
+ }
11258
+ }
10176
11259
  userKey(state, chainId) {
10177
11260
  return `${state.walletAddress.toLowerCase()}:${chainId}`;
10178
11261
  }
@@ -10225,6 +11308,7 @@ var YieldseekerAgent = class {
10225
11308
  this.agentContexts.set(slot, context);
10226
11309
  this.pendingSlotInvalidations.delete(slot);
10227
11310
  this.missingSlots.delete(slot);
11311
+ this.closedSlots.delete(slot);
10228
11312
  }
10229
11313
  assertSession(generation, chainId, asset) {
10230
11314
  if (this.readGeneration !== generation) {
@@ -10336,8 +11420,10 @@ var YieldseekerAgent = class {
10336
11420
  * highest-priority set of `priorities` (index 0 first). Hinted agentIds are
10337
11421
  * resolved first and a hinted top-priority match ends the search; then other
10338
11422
  * listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
11423
+ * A candidate whose wallet shows it closed (deactivated) never ranks, and its
11424
+ * agentId is added to `closed`.
10339
11425
  */
10340
- async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
11426
+ async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
10341
11427
  const fitting = /* @__PURE__ */ new Map();
10342
11428
  for (const agent of agents) {
10343
11429
  if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
@@ -10359,6 +11445,10 @@ var YieldseekerAgent = class {
10359
11445
  failure ??= { error: result.reason };
10360
11446
  continue;
10361
11447
  }
11448
+ if (result.value.wallet.deactivatedDate) {
11449
+ closed?.add(result.value.agent.agentId);
11450
+ continue;
11451
+ }
10362
11452
  const wallet = result.value.wallet.walletAddress.toLowerCase();
10363
11453
  const rank = priorities.findIndex((wallets) => wallets.has(wallet));
10364
11454
  if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
@@ -10373,32 +11463,213 @@ var YieldseekerAgent = class {
10373
11463
  }
10374
11464
  /**
10375
11465
  * chooseAgent, re-reading a cached list once (bypassing its cache) when the
10376
- * verified agent is missing. A slot still missing after that re-read is
10377
- * remembered for the list cache window, so later reads fail from the cached
10378
- * list without another re-read.
11466
+ * verified agent is missing. Still missing, Yieldseeker may have closed
11467
+ * (deactivated) it: the verified record's agent is reactivated and selected
11468
+ * from a fresh list, by the verified wallet only (never created). A slot
11469
+ * that still fails is remembered with its error for the list cache window,
11470
+ * so later reads fail without another re-read or reactivate. A slot
11471
+ * Yieldseeker will not reopen because of its active-agent limit throws
11472
+ * YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
11473
+ * no request.
10379
11474
  */
10380
11475
  async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
11476
+ this.throwIfSlotUnavailable(state, chainId, asset);
10381
11477
  try {
10382
11478
  return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
10383
11479
  } catch (error) {
10384
11480
  if (!this.isAgentMissing(error)) throw error;
10385
11481
  const slot = this.slotKey(state, chainId, asset);
10386
- if (this.isSlotMissing(slot)) throw error;
11482
+ this.throwIfSlotMissing(slot);
10387
11483
  const generation = this.readGeneration;
10388
11484
  const fresh = await this.listAgents(state, chainId, user, true);
10389
11485
  this.assertSession(generation, chainId, asset);
11486
+ let missing;
10390
11487
  try {
10391
11488
  return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
10392
11489
  } catch (retryError) {
10393
- if (this.isAgentMissing(retryError) && this.readGeneration === generation) {
10394
- this.missingSlots.set(slot, Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS);
11490
+ if (!this.isAgentMissing(retryError)) throw retryError;
11491
+ missing = retryError;
11492
+ }
11493
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
11494
+ const agentId = verified?.providerAgentId;
11495
+ if (!verified || !agentId) {
11496
+ this.rememberMissingSlot(slot, generation, missing);
11497
+ throw missing;
11498
+ }
11499
+ this.throwIfSlotMissing(slot);
11500
+ let reopened;
11501
+ try {
11502
+ reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
11503
+ this.assertSession(generation, chainId, asset);
11504
+ } catch (reopenError) {
11505
+ this.rememberMissingSlot(slot, generation, reopenError);
11506
+ throw reopenError;
11507
+ }
11508
+ try {
11509
+ const agent = await this.agentWithWallet(
11510
+ state,
11511
+ chainId,
11512
+ user,
11513
+ reopened,
11514
+ asset,
11515
+ [/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
11516
+ [agentId]
11517
+ );
11518
+ if (agent) return agent;
11519
+ throw this.agentMissing(chainId, asset, agentId);
11520
+ } catch (reopenedError) {
11521
+ if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
11522
+ throw reopenedError;
11523
+ }
11524
+ }
11525
+ }
11526
+ throwIfSlotUnavailable(state, chainId, asset) {
11527
+ const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
11528
+ if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
11529
+ }
11530
+ /**
11531
+ * Rethrow the error a slot's lookup failed with while the slot is still
11532
+ * marked, or for the session when Yieldseeker will never reopen its agent.
11533
+ * A remembered rate limit is rethrown with the time left on its marker as
11534
+ * its retry delay (`retryAfterSeconds`): no new attempt is made before then,
11535
+ * so a caller that waits it out retries once instead of every few seconds.
11536
+ */
11537
+ throwIfSlotMissing(slot) {
11538
+ const closed = this.closedSlots.get(slot);
11539
+ if (closed) throw closed;
11540
+ const missing = this.missingSlots.get(slot);
11541
+ if (!missing || missing.until <= Date.now()) return;
11542
+ const { error } = missing;
11543
+ if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
11544
+ const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
11545
+ const rethrown = new OwneyError(
11546
+ error.code,
11547
+ error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
11548
+ { ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
11549
+ error.agentId
11550
+ );
11551
+ this.rethrownSlotFailures.set(rethrown, error);
11552
+ throw rethrown;
11553
+ }
11554
+ /**
11555
+ * Remember a slot's failed lookup or reactivate for the list-cache window.
11556
+ * A sign-in failure is not remembered (the wallet's rejection,
11557
+ * AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
11558
+ * remembered it would refuse the next sign-in, even one the user starts,
11559
+ * with no request for the whole window.
11560
+ */
11561
+ rememberMissingSlot(slot, generation, error) {
11562
+ if (this.readGeneration !== generation) return;
11563
+ if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
11564
+ this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
11565
+ }
11566
+ /**
11567
+ * Reactivate the slot's verified agent, then read the list bypassing its
11568
+ * cache, with a read sent after the reactivate answered. Concurrent lookups
11569
+ * of one slot share one reopen. Resolves to the fresh list. At the
11570
+ * active-agent limit the slot is recorded unavailable and this throws
11571
+ * YIELDSEEKER_SLOT_UNAVAILABLE.
11572
+ */
11573
+ reopenAgent(state, chainId, user, asset, agentId) {
11574
+ const slot = this.slotKey(state, chainId, asset);
11575
+ const pending = this.pendingReopens.get(slot);
11576
+ if (pending) return pending;
11577
+ const generation = this.readGeneration;
11578
+ const request2 = (async () => {
11579
+ const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
11580
+ this.assertSession(generation, chainId, asset);
11581
+ if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
11582
+ this.forgetAgentWallet(agentId);
11583
+ this.missingSlots.delete(slot);
11584
+ await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
11585
+ this.assertSession(generation, chainId, asset);
11586
+ const fresh = await this.listAgents(state, chainId, user, true);
11587
+ this.assertSession(generation, chainId, asset);
11588
+ return fresh;
11589
+ })().finally(() => {
11590
+ if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
11591
+ });
11592
+ this.pendingReopens.set(slot, request2);
11593
+ return request2;
11594
+ }
11595
+ /**
11596
+ * The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
11597
+ * and the pre-deposit check (assertAgentOpen), so a slot costs at most one
11598
+ * reactivate per list-cache window:
11599
+ * - a slot recorded unavailable (the limit) answers "limit" with no request;
11600
+ * - concurrent callers share one request;
11601
+ * - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
11602
+ * remembered as the slot's failure for the list-cache window (missingSlots)
11603
+ * and rethrown to later callers with no request; a closed code
11604
+ * (closedSlots) for the session; a sign-in failure is not remembered;
11605
+ * - the limit is recorded in unavailableSlots only while the session is
11606
+ * unchanged, so a disconnect during the request is not undone by its late
11607
+ * answer.
11608
+ */
11609
+ async reactivateSlot(state, chainId, user, asset, agentId) {
11610
+ const slot = this.slotKey(state, chainId, asset);
11611
+ const limit = this.unavailableSlots.get(slot);
11612
+ if (limit !== void 0) return { outcome: "limit", providerCode: limit };
11613
+ const key2 = `${slot}:${agentId}`;
11614
+ const pending = this.pendingReactivates.get(key2);
11615
+ if (pending) return pending;
11616
+ this.throwIfSlotMissing(slot);
11617
+ const generation = this.readGeneration;
11618
+ const request2 = (async () => {
11619
+ try {
11620
+ const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
11621
+ if (result.outcome === "limit" && this.readGeneration === generation) {
11622
+ this.unavailableSlots.set(slot, result.providerCode);
10395
11623
  }
10396
- throw retryError;
11624
+ return result;
11625
+ } catch (error) {
11626
+ if (this.readGeneration === generation && error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED" && typeof error.details?.providerCode === "string" && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(error.details.providerCode)) {
11627
+ this.closedSlots.set(slot, error);
11628
+ }
11629
+ this.rememberMissingSlot(slot, generation, error);
11630
+ throw error;
11631
+ }
11632
+ })().finally(() => {
11633
+ if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
11634
+ });
11635
+ this.pendingReactivates.set(key2, request2);
11636
+ return request2;
11637
+ }
11638
+ /**
11639
+ * Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
11640
+ * Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
11641
+ * by another tab) counts as reopened; the active-agent limit is an outcome,
11642
+ * not an error. An agent that cannot come back throws
11643
+ * YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
11644
+ * 5xx, an unknown code) throws the mapped API error.
11645
+ */
11646
+ async reactivateAgent(state, chainId, user, asset, agentId) {
11647
+ try {
11648
+ await this.providerRequest(
11649
+ state,
11650
+ chainId,
11651
+ `/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
11652
+ { method: "POST", body: {} }
11653
+ );
11654
+ return { outcome: "reopened" };
11655
+ } catch (error) {
11656
+ if (error instanceof OwneyError) throw error;
11657
+ const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
11658
+ if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
11659
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
11660
+ return { outcome: "limit", providerCode };
10397
11661
  }
11662
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
11663
+ throw this.agentClosed(chainId, asset, agentId, providerCode);
11664
+ }
11665
+ throw this.mapRequestFailure(error);
10398
11666
  }
10399
11667
  }
10400
- isSlotMissing(slot) {
10401
- return (this.missingSlots.get(slot) ?? 0) > Date.now();
11668
+ /** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
11669
+ forgetAgentWallet(agentId) {
11670
+ const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
11671
+ for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
11672
+ for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
10402
11673
  }
10403
11674
  /**
10404
11675
  * The agent that serves deposits and withdrawals for a slot (Ruling 23):
@@ -10406,7 +11677,8 @@ var YieldseekerAgent = class {
10406
11677
  * whatever its name; the stored agentId is only a hint;
10407
11678
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
10408
11679
  * 3. else the fitting agent named "owney" (first use, migration, or a
10409
- * verified wallet that is not a fitting listed agent);
11680
+ * verified wallet that is not a fitting listed agent), unless step 1/2
11681
+ * read its wallet and it is closed (deactivated): that agent is not listed;
10410
11682
  * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
10411
11683
  * create); without one, undefined (the caller may create).
10412
11684
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
@@ -10417,6 +11689,7 @@ var YieldseekerAgent = class {
10417
11689
  const slot = this.slotAccounts(accounts, chainId, asset);
10418
11690
  const verified = slot.find((account) => account.status === "verified");
10419
11691
  const superseded = slot.filter((account) => account.status === "superseded");
11692
+ const closed = /* @__PURE__ */ new Set();
10420
11693
  if (verified || superseded.length) {
10421
11694
  const priorities = [];
10422
11695
  if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
@@ -10430,11 +11703,12 @@ var YieldseekerAgent = class {
10430
11703
  agents,
10431
11704
  asset,
10432
11705
  priorities,
10433
- [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
11706
+ [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
11707
+ closed
10434
11708
  );
10435
11709
  if (match) return match;
10436
11710
  }
10437
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
11711
+ const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
10438
11712
  if (named) return named;
10439
11713
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
10440
11714
  return void 0;
@@ -10450,6 +11724,39 @@ var YieldseekerAgent = class {
10450
11724
  this.id
10451
11725
  );
10452
11726
  }
11727
+ slotUnavailable(chainId, asset, providerCode) {
11728
+ return new OwneyError(
11729
+ "YIELDSEEKER_SLOT_UNAVAILABLE",
11730
+ `Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
11731
+ { rpcSource: "agent-api", chainId, asset, providerCode },
11732
+ this.id
11733
+ );
11734
+ }
11735
+ /** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
11736
+ isSlotEmpty(error) {
11737
+ return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
11738
+ }
11739
+ /**
11740
+ * The slot's lookup failed through the missing-agent / reopen path and was
11741
+ * remembered with this very error, even a transient one (429, 5xx, timeout),
11742
+ * or with the copy of it a remembered rate limit is rethrown as. Compares
11743
+ * the remembered error, not its expiry, so it holds however long the rest
11744
+ * of the read takes.
11745
+ */
11746
+ isMarkedSlotFailure(slot, error) {
11747
+ const marker = this.missingSlots.get(slot);
11748
+ if (!marker) return false;
11749
+ return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
11750
+ }
11751
+ /** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
11752
+ agentClosed(chainId, asset, agentId, providerCode, extra) {
11753
+ return new OwneyError(
11754
+ "YIELDSEEKER_AGENT_CLOSED",
11755
+ `Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
11756
+ { rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
11757
+ this.id
11758
+ );
11759
+ }
10453
11760
  /**
10454
11761
  * Fire-and-forget: record which agent serves this slot. Never awaited on the
10455
11762
  * funds path and never throws; once per agent wallet and deployment state
@@ -10539,7 +11846,7 @@ var YieldseekerAgent = class {
10539
11846
  } catch (error) {
10540
11847
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
10541
11848
  if (error instanceof OwneyError) throw error;
10542
- throw this.mapApiError(error);
11849
+ throw this.mapRequestFailure(error);
10543
11850
  }
10544
11851
  let created;
10545
11852
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
@@ -10560,7 +11867,7 @@ var YieldseekerAgent = class {
10560
11867
  } catch (createError) {
10561
11868
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
10562
11869
  if (canRetry) continue;
10563
- throw this.mapApiError(createError);
11870
+ throw this.mapRequestFailure(createError);
10564
11871
  }
10565
11872
  }
10566
11873
  user = created?.user ?? null;
@@ -10617,6 +11924,7 @@ var YieldseekerAgent = class {
10617
11924
  return context;
10618
11925
  }
10619
11926
  async resolveAgent(state, chainId, asset, createIfMissing) {
11927
+ this.throwIfSlotUnavailable(state, chainId, asset);
10620
11928
  const generation = this.readGeneration;
10621
11929
  const accountsRead = this.agentAccounts(state, chainId);
10622
11930
  const user = await this.resolveUser(state, chainId);
@@ -10659,7 +11967,7 @@ var YieldseekerAgent = class {
10659
11967
  );
10660
11968
  } catch (error) {
10661
11969
  const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
10662
- if (!conflict) throw this.mapApiError(error);
11970
+ if (!conflict) throw this.mapRequestFailure(error);
10663
11971
  this.assertSession(generation, chainId, asset);
10664
11972
  return this.adoptConflictingAgent(
10665
11973
  state,
@@ -10752,10 +12060,11 @@ var YieldseekerAgent = class {
10752
12060
  const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
10753
12061
  if (agent) selected.set(asset, agent);
10754
12062
  } catch (error) {
10755
- if (assetFilter || !this.isAgentMissing(error)) throw error;
12063
+ if (assetFilter) throw error;
12064
+ if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
10756
12065
  missing.push(error);
10757
12066
  missingAssets?.add(asset);
10758
- console.warn(`[owney-sdk] Yieldseeker ${asset} agent is missing:`, error);
12067
+ console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
10759
12068
  }
10760
12069
  }));
10761
12070
  this.assertSession(generation, chainId);
@@ -11390,6 +12699,7 @@ var YieldseekerAgent = class {
11390
12699
  try {
11391
12700
  return await this.providerRequest(state, chainId, path, options);
11392
12701
  } catch (error) {
12702
+ if (isWalletRejection(error)) throw error;
11393
12703
  const mapped = this.mapApiError(error);
11394
12704
  const delay = read2 ? rateLimitDelay(mapped) : void 0;
11395
12705
  if (delay !== void 0 && this.readGeneration === generation) {
@@ -11413,8 +12723,9 @@ var YieldseekerAgent = class {
11413
12723
  options.assertCurrent?.();
11414
12724
  return this.api.request(path, { method: options.method, body: options.body, signature: signature2 });
11415
12725
  };
11416
- const cached = options.promptless ? this.auth.peekToken(state, chainId) : void 0;
11417
- if (options.promptless && !cached)
12726
+ const promptless = options.promptless || state.promptless === true;
12727
+ const cached = promptless ? this.auth.peekToken(state, chainId) : void 0;
12728
+ if (promptless && !cached)
11418
12729
  throw new OwneyError(
11419
12730
  "AGENT_AUTH_FAILED",
11420
12731
  "No Yieldseeker sign-in is available without a prompt.",
@@ -11428,7 +12739,10 @@ var YieldseekerAgent = class {
11428
12739
  if (!(error instanceof YieldseekerApiError)) throw error;
11429
12740
  if (error.providerCode === "NO_USER") throw error;
11430
12741
  if (!error.isAuthenticationError) throw error;
11431
- if (options.promptless) throw error;
12742
+ if (promptless) {
12743
+ this.auth.discardToken(state, chainId, signature);
12744
+ throw error;
12745
+ }
11432
12746
  signature = await this.auth.refreshToken(state, chainId, signature);
11433
12747
  try {
11434
12748
  return await request2(signature);
@@ -11440,6 +12754,16 @@ var YieldseekerAgent = class {
11440
12754
  }
11441
12755
  }
11442
12756
  }
12757
+ /**
12758
+ * mapApiError for a request that may have opened the Yieldseeker sign-in
12759
+ * prompt (providerRequest signs when no sign-in is saved, and again when
12760
+ * Yieldseeker refuses one). The wallet's rejection, the user cancelling that
12761
+ * prompt, is returned unchanged: the client and the app must see the user's
12762
+ * cancel (no further prompt, no retry), never a provider failure.
12763
+ */
12764
+ mapRequestFailure(error) {
12765
+ return isWalletRejection(error) ? error : this.mapApiError(error);
12766
+ }
11443
12767
  mapApiError(error) {
11444
12768
  if (!(error instanceof YieldseekerApiError)) {
11445
12769
  return new OwneyError(
@@ -11655,6 +12979,120 @@ var YieldseekerAgent = class {
11655
12979
  }
11656
12980
  };
11657
12981
 
12982
+ // src/lib/history-fanout.ts
12983
+ var SEPARATOR = "@";
12984
+ function isSupportedChainId(value) {
12985
+ return SUPPORTED_CHAIN_IDS.includes(value);
12986
+ }
12987
+ function fanoutKey(leg) {
12988
+ return leg.chainId === void 0 ? leg.agentId : `${leg.agentId}${SEPARATOR}${leg.chainId}`;
12989
+ }
12990
+ function encodeFanoutCursor(map) {
12991
+ return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
12992
+ }
12993
+ function decodeFanoutCursor(token) {
12994
+ let parsed;
12995
+ try {
12996
+ parsed = JSON.parse(Buffer.from(token, "base64").toString("utf8"));
12997
+ } catch {
12998
+ throw new InvalidHistoryCursorError(
12999
+ "History fan-out cursor is not valid base64 JSON."
13000
+ );
13001
+ }
13002
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !Object.values(parsed).every((v) => typeof v === "string")) {
13003
+ throw new InvalidHistoryCursorError(
13004
+ "History fan-out cursor payload has wrong shape."
13005
+ );
13006
+ }
13007
+ return parsed;
13008
+ }
13009
+ function transactionChainId(entry) {
13010
+ let found;
13011
+ for (const tx of entry.transactions ?? []) {
13012
+ if (tx.chainId === void 0) continue;
13013
+ if (!isSupportedChainId(tx.chainId)) return void 0;
13014
+ if (found !== void 0 && found !== tx.chainId) return void 0;
13015
+ found = tx.chainId;
13016
+ }
13017
+ return found;
13018
+ }
13019
+ function mergeHistoryPages(pages) {
13020
+ const merged = [];
13021
+ const nextCursorMap = {};
13022
+ let hasMore = false;
13023
+ const identity = (e) => [
13024
+ e.agent,
13025
+ e.action,
13026
+ e.date ?? "",
13027
+ e.transactions?.[0]?.txHashes?.[0] ?? ""
13028
+ ].join("\0");
13029
+ const seen = /* @__PURE__ */ new Map();
13030
+ for (const { leg, page } of pages) {
13031
+ if (!page) continue;
13032
+ for (const e of page.data) {
13033
+ const id = identity(e);
13034
+ const prior = seen.get(id);
13035
+ if (prior) {
13036
+ prior.legs += 1;
13037
+ const own = transactionChainId(prior.entry);
13038
+ if (own === void 0) delete prior.entry.chainId;
13039
+ else prior.entry.chainId = own;
13040
+ continue;
13041
+ }
13042
+ const entry = leg.chainId === void 0 ? { ...e } : { ...e, chainId: leg.chainId };
13043
+ seen.set(id, { entry, legs: 1 });
13044
+ merged.push(entry);
13045
+ }
13046
+ if (page.hasMore && page.nextCursor) {
13047
+ nextCursorMap[fanoutKey(leg)] = page.nextCursor;
13048
+ hasMore = true;
13049
+ }
13050
+ }
13051
+ merged.sort((a, b) => {
13052
+ const dateDiff = new Date(b.date).getTime() - new Date(a.date).getTime();
13053
+ if (dateDiff !== 0) return dateDiff;
13054
+ if (a.agent !== b.agent) return a.agent < b.agent ? -1 : 1;
13055
+ const aChain = a.chainId ?? 0;
13056
+ const bChain = b.chainId ?? 0;
13057
+ if (aChain !== bChain) return aChain - bChain;
13058
+ const aTx = a.transactions?.[0]?.txHashes?.[0] ?? "";
13059
+ const bTx = b.transactions?.[0]?.txHashes?.[0] ?? "";
13060
+ if (aTx !== bTx) return aTx < bTx ? -1 : 1;
13061
+ if (a.action !== b.action) return a.action < b.action ? -1 : 1;
13062
+ return 0;
13063
+ });
13064
+ return {
13065
+ data: merged,
13066
+ hasMore,
13067
+ nextCursor: hasMore ? encodeFanoutCursor(nextCursorMap) : void 0
13068
+ };
13069
+ }
13070
+
13071
+ // src/lib/daily-earnings-merge.ts
13072
+ function mergeDailyEarnings(series) {
13073
+ const byAsset = /* @__PURE__ */ new Map();
13074
+ for (const s of series) {
13075
+ for (const { asset, points } of s.assets) {
13076
+ const byDate = byAsset.get(asset) ?? /* @__PURE__ */ new Map();
13077
+ for (const point of points) {
13078
+ byDate.set(point.date, (byDate.get(point.date) ?? 0) + point.amount);
13079
+ }
13080
+ byAsset.set(asset, byDate);
13081
+ }
13082
+ }
13083
+ return {
13084
+ walletAddress: series[0]?.walletAddress ?? "",
13085
+ // Names the first source's chain. On a fanned-out read the payload spans
13086
+ // several, so this is provenance rather than scope — `assets` is the part
13087
+ // that carries the merged figures.
13088
+ chainId: series[0]?.chainId ?? 0,
13089
+ assets: [...byAsset.entries()].map(([asset, byDate]) => ({
13090
+ asset,
13091
+ points: [...byDate.entries()].map(([date, amount]) => ({ date, amount })).sort((a, b) => a.date.localeCompare(b.date))
13092
+ })).sort((a, b) => a.asset.localeCompare(b.asset))
13093
+ };
13094
+ }
13095
+
11658
13096
  // src/lib/swap/swap-api.ts
11659
13097
  var FUSION_SECRET_SERVER_PUBLISH = 1;
11660
13098
  var FUSION_SECRET_HANDOFF_TIMEOUT_MS = 5e3;
@@ -11916,6 +13354,8 @@ var FALLBACK_WRAP_GAS = 50000n;
11916
13354
  var APPROVE_GAS = 60000n;
11917
13355
  var GAS_SAFETY = 2n;
11918
13356
  var MIN_WALLET_GAS_PRICE = 3000000000n;
13357
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
13358
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
11919
13359
  async function wrapNative(deps, options) {
11920
13360
  const { chainId, wrapper, nativeSymbol, requested } = options;
11921
13361
  const balance = await deps.readNativeBalance();
@@ -11973,16 +13413,90 @@ async function wrapNative(deps, options) {
11973
13413
  }
11974
13414
  );
11975
13415
  }
13416
+ let baseline;
13417
+ if (deps.readWrappedBalance) {
13418
+ try {
13419
+ baseline = await deps.readWrappedBalance();
13420
+ } catch (error) {
13421
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
13422
+ message: error instanceof Error ? error.message : String(error)
13423
+ });
13424
+ }
13425
+ }
11976
13426
  await deps.ensureChain(chainId);
11977
13427
  debugLog("owney-sdk", "wrap: sending deposit()", {
11978
13428
  wrapper,
11979
13429
  value: wrapped.toString()
11980
13430
  });
11981
- const txHash = await deps.sendTransaction(
11982
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
11983
- options.onSubmitted
11984
- );
11985
- return { wrapped, txHash };
13431
+ let notified = false;
13432
+ const notify2 = (hash2) => {
13433
+ if (notified) return;
13434
+ notified = true;
13435
+ options.onSubmitted?.(hash2);
13436
+ };
13437
+ const outcome = await new Promise((resolve, reject) => {
13438
+ let done = false;
13439
+ let timer;
13440
+ const finish = (settle) => {
13441
+ if (done) return;
13442
+ done = true;
13443
+ clearTimeout(timer);
13444
+ settle();
13445
+ };
13446
+ timer = setTimeout(
13447
+ () => finish(
13448
+ () => reject(
13449
+ new OwneyError(
13450
+ "SWAP_WALLET_PROMPT_TIMEOUT",
13451
+ // Hedged on purpose: a wallet that never answered may still have
13452
+ // sent it, and wrapping again would wrap twice.
13453
+ `Your wallet didn't answer the request to wrap your ${nativeSymbol}. Check your wallet before trying again \u2014 if the wrap went through, your funds are there as wrapped ${nativeSymbol}.`,
13454
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
13455
+ )
13456
+ )
13457
+ ),
13458
+ WRAP_PROMPT_TIMEOUT_MS
13459
+ );
13460
+ deps.sendTransaction(
13461
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
13462
+ (hash2) => {
13463
+ clearTimeout(timer);
13464
+ notify2(hash2);
13465
+ }
13466
+ ).then(
13467
+ (txHash) => finish(() => resolve({ txHash })),
13468
+ (error) => finish(() => reject(error))
13469
+ );
13470
+ if (baseline !== void 0 && deps.readWrappedBalance) {
13471
+ const read2 = deps.readWrappedBalance;
13472
+ const target = baseline + wrapped;
13473
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13474
+ void (async () => {
13475
+ while (!done) {
13476
+ await sleep4(WRAP_WATCH_INTERVAL_MS);
13477
+ if (done) return;
13478
+ try {
13479
+ if (await read2() >= target) {
13480
+ debugLog(
13481
+ "owney-sdk",
13482
+ "wrap: landed on chain before the wallet answered"
13483
+ );
13484
+ finish(() => {
13485
+ notify2();
13486
+ resolve({});
13487
+ });
13488
+ return;
13489
+ }
13490
+ } catch {
13491
+ }
13492
+ }
13493
+ })();
13494
+ }
13495
+ });
13496
+ return {
13497
+ wrapped,
13498
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
13499
+ };
11986
13500
  }
11987
13501
  function requireWrapper(quote) {
11988
13502
  const wrapper = quote.wrappedNative;
@@ -12127,6 +13641,10 @@ var DEFAULT_POLL_MS2 = 5e3;
12127
13641
  var MAX_BACKOFF_MS = 3e4;
12128
13642
  var backoffFor = (failures, base7) => Math.min(base7 * 2 ** Math.min(failures, 5), MAX_BACKOFF_MS);
12129
13643
  var DEFAULT_TIMEOUT_MS3 = 15 * 60 * 1e3;
13644
+ var NOT_FOUND_GRACE_MS = 2 * 60 * 1e3;
13645
+ function isNotFound(error) {
13646
+ return error instanceof OwneyError && error.details?.statusCode === 404;
13647
+ }
12130
13648
  async function runFusionOrderInternal(deps, options) {
12131
13649
  const {
12132
13650
  orderHash,
@@ -12157,6 +13675,7 @@ async function runFusionOrderInternal(deps, options) {
12157
13675
  assertTime();
12158
13676
  };
12159
13677
  let failures = 0;
13678
+ let notFoundSince;
12160
13679
  const published = /* @__PURE__ */ new Set();
12161
13680
  onStage?.("swapping");
12162
13681
  for (; ; ) {
@@ -12192,7 +13711,20 @@ async function runFusionOrderInternal(deps, options) {
12192
13711
  status = state.status;
12193
13712
  partial ||= status === "partially-filled" || !!state.fills?.length;
12194
13713
  failures = 0;
12195
- } catch {
13714
+ notFoundSince = void 0;
13715
+ } catch (error) {
13716
+ if (isNotFound(error)) {
13717
+ notFoundSince ??= deps.now();
13718
+ if (deps.now() - notFoundSince >= NOT_FOUND_GRACE_MS) {
13719
+ throw new OwneyError(
13720
+ "SWAP_ORDER_NOT_FOUND",
13721
+ "The swap provider has no record of this order, so nothing was exchanged.",
13722
+ { orderHash }
13723
+ );
13724
+ }
13725
+ } else {
13726
+ notFoundSince = void 0;
13727
+ }
12196
13728
  failures += 1;
12197
13729
  await pause(backoffFor(failures, pollIntervalMs));
12198
13730
  continue;
@@ -12464,7 +13996,7 @@ async function executeSwap(deps, options) {
12464
13996
  });
12465
13997
  const before = await deps.readTargetBalance();
12466
13998
  debugLog("owney-sdk", "swap: target balance before", before.toString());
12467
- const result = quote.rail === "classic" ? await runClassic(deps, options) : quote.rail === "fusion" ? await runSameChainFusion(deps, options, walletAddress) : await runFusion(deps, options, walletAddress);
13999
+ 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);
12468
14000
  const { arrived } = await awaitBalanceIncrease({
12469
14001
  readBalance: () => deps.readTargetBalance(),
12470
14002
  baseline: before,
@@ -12483,6 +14015,17 @@ async function executeSwap(deps, options) {
12483
14015
  active = false;
12484
14016
  }
12485
14017
  }
14018
+ async function doubtVerdict(deps, error, before) {
14019
+ if (!(error instanceof OwneyError) || error.code !== "SWAP_ORDER_EXPIRED" && error.code !== "SWAP_ORDER_CANCELLED" || error.details?.outcome !== "not-submitted") throw error;
14020
+ const now = await deps.readTargetBalance().catch(() => before);
14021
+ if (now <= before) throw error;
14022
+ debugLog("owney-sdk", "swap: rail said no but the wallet received funds", { status: error.details?.status });
14023
+ throw new OwneyError(
14024
+ "SWAP_REQUEST_FAILED",
14025
+ "The swap's status says it did not fill, but funds arrived in your wallet since it started. Check your wallet before retrying.",
14026
+ { ...error.details, settlementUnconfirmed: true, outcome: "submitted-unknown" }
14027
+ );
14028
+ }
12486
14029
  async function runClassic(deps, options) {
12487
14030
  const {
12488
14031
  quote,
@@ -12507,8 +14050,8 @@ async function runClassic(deps, options) {
12507
14050
  onStage?.("quoting");
12508
14051
  debugLog("owney-sdk", "swap: fetching classic calldata");
12509
14052
  let { tx } = await deps.api.swapTx(swapTxRequest);
12510
- const isNative = BigInt(tx.value ?? "0") > 0n;
12511
- if (!isNative) {
14053
+ const isNative2 = BigInt(tx.value ?? "0") > 0n;
14054
+ if (!isNative2) {
12512
14055
  const needed = amount;
12513
14056
  const current = await deps.readAllowance(tx.to);
12514
14057
  debugLog("owney-sdk", "swap: allowance", {
@@ -12732,7 +14275,7 @@ async function runFusion(deps, options, walletAddress) {
12732
14275
  ...onStage ? { onStage } : {}
12733
14276
  });
12734
14277
  } catch (error) {
12735
- if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
14278
+ if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || error.code === "SWAP_ORDER_NOT_FOUND")) {
12736
14279
  clearOrder(built.orderHash);
12737
14280
  }
12738
14281
  throw error;
@@ -13014,6 +14557,33 @@ function verifiedFee(payout) {
13014
14557
  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;
13015
14558
  }
13016
14559
 
14560
+ // src/lib/swap/swap.gas-check.ts
14561
+ var CLASSIC_SWAP_GAS = 300000n;
14562
+ var APPROVE_GAS2 = 60000n;
14563
+ var isNative = (address) => address.toLowerCase().startsWith("0xeeee");
14564
+ async function swapGasShortfall(deps, quote) {
14565
+ if (quote.rail !== "classic" || isNative(quote.src.address)) return null;
14566
+ const gas = CLASSIC_SWAP_GAS + APPROVE_GAS2;
14567
+ const [balance, gasPrice] = await Promise.all([
14568
+ deps.readNativeBalance(),
14569
+ deps.getMaxFeePerGas()
14570
+ ]);
14571
+ const required = gas * gasPrice;
14572
+ return balance < required ? { chainId: quote.src.chainId, balance, required } : null;
14573
+ }
14574
+ function swapGasError(shortfall, nativeSymbol) {
14575
+ return new OwneyError(
14576
+ "SWAP_INSUFFICIENT_GAS",
14577
+ `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.`,
14578
+ {
14579
+ chainId: shortfall.chainId,
14580
+ symbol: nativeSymbol,
14581
+ balance: shortfall.balance.toString(),
14582
+ required: shortfall.required.toString()
14583
+ }
14584
+ );
14585
+ }
14586
+
13017
14587
  // src/lib/swap/swap.permit.ts
13018
14588
  import {
13019
14589
  domainSeparator,
@@ -13484,9 +15054,40 @@ function aggregateApyHistory(agentApys) {
13484
15054
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
13485
15055
  if (total <= 0 || !Number.isFinite(total)) return [];
13486
15056
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
13487
- return Number.isFinite(apy) ? [{ date, apy }] : [];
15057
+ if (!Number.isFinite(apy)) return [];
15058
+ const incentives = aggregateIncentives(points, total);
15059
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
13488
15060
  });
13489
15061
  }
15062
+ function incentiveKey(incentive) {
15063
+ return JSON.stringify([
15064
+ incentive.source,
15065
+ incentive.agentId,
15066
+ incentive.opportunityId,
15067
+ [...incentive.campaignIds].sort()
15068
+ ]);
15069
+ }
15070
+ function aggregateIncentives(points, totalBalance) {
15071
+ const byProgram = /* @__PURE__ */ new Map();
15072
+ for (const point of points) {
15073
+ const weight = point.historicalBalance.amount / totalBalance;
15074
+ for (const incentive of point.incentives ?? []) {
15075
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
15076
+ const key2 = incentiveKey(incentive);
15077
+ const existing = byProgram.get(key2);
15078
+ if (existing) {
15079
+ existing.apyContribution += incentive.apyContribution * weight;
15080
+ } else {
15081
+ byProgram.set(key2, {
15082
+ ...incentive,
15083
+ campaignIds: [...incentive.campaignIds],
15084
+ apyContribution: incentive.apyContribution * weight
15085
+ });
15086
+ }
15087
+ }
15088
+ }
15089
+ return [...byProgram.values()];
15090
+ }
13490
15091
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
13491
15092
  const sums = {};
13492
15093
  const weights = {};
@@ -14099,7 +15700,9 @@ async function execute(i, key2, plan) {
14099
15700
  if (balance < total)
14100
15701
  throw new OwneyError(
14101
15702
  "DEPOSIT_INSUFFICIENT_BALANCE",
14102
- "Insufficient token balance for this deposit."
15703
+ "Insufficient token balance for this deposit.",
15704
+ // What was seen: a swap's deposit retries once at a small shortfall (ROUT-618).
15705
+ { token: i.token, chainId: i.chainId, balance: balance.toString(), amount: total.toString() }
14103
15706
  );
14104
15707
  if (allowance < total && !supportsSponsoredErc2612(i.chainId, i.token))
14105
15708
  throw new OwneyError(
@@ -14134,15 +15737,20 @@ async function execute(i, key2, plan) {
14134
15737
  tokenName,
14135
15738
  tokenVersion
14136
15739
  };
14137
- const signature2 = await i.wallet.signTypedData({
14138
- account: i.owner,
14139
- ...erc2612TypedData({
14140
- chainId: i.chainId,
14141
- token: i.token,
14142
- owner: i.owner,
14143
- permit: unsignedPermit
15740
+ const signature2 = await signWithChainRetry(
15741
+ i.walletChain ?? i.pub,
15742
+ i.wallet,
15743
+ i.chainId,
15744
+ () => i.wallet.signTypedData({
15745
+ account: i.owner,
15746
+ ...erc2612TypedData({
15747
+ chainId: i.chainId,
15748
+ token: i.token,
15749
+ owner: i.owner,
15750
+ permit: unsignedPermit
15751
+ })
14144
15752
  })
14145
- });
15753
+ );
14146
15754
  erc2612Permit = { ...unsignedPermit, signature: signature2 };
14147
15755
  }
14148
15756
  const spender = await getSponsorRelayerAddress({
@@ -14159,10 +15767,15 @@ async function execute(i, key2, plan) {
14159
15767
  deadline: (now + 900n).toString(),
14160
15768
  ...erc2612Permit ? { erc2612Permit } : {}
14161
15769
  };
14162
- const signature = await i.wallet.signTypedData({
14163
- account: i.owner,
14164
- ...batchTypedData(unsigned, spender)
14165
- });
15770
+ const signature = await signWithChainRetry(
15771
+ i.walletChain ?? i.pub,
15772
+ i.wallet,
15773
+ i.chainId,
15774
+ () => i.wallet.signTypedData({
15775
+ account: i.owner,
15776
+ ...batchTypedData(unsigned, spender)
15777
+ })
15778
+ );
14166
15779
  i.onApproved?.();
14167
15780
  return send({ ...unsigned, signature });
14168
15781
  }
@@ -14191,6 +15804,7 @@ function makeSponsoredTokenCallback(deps) {
14191
15804
  chainId,
14192
15805
  transfers,
14193
15806
  pub,
15807
+ walletChain,
14194
15808
  wallet,
14195
15809
  onApproved: deps.onApproved,
14196
15810
  // Rest arguments keep the callbacks' arity: the flag appears only when set.
@@ -14285,6 +15899,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
14285
15899
  }
14286
15900
  }
14287
15901
 
15902
+ // src/lib/walletconnect-switch.ts
15903
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
15904
+ var HOLD_CHAIN_MS = 15e3;
15905
+ var MAX_RESENDS = 2;
15906
+ var holds = /* @__PURE__ */ new Map();
15907
+ function parseChainId(raw2) {
15908
+ if (typeof raw2 === "number") return raw2;
15909
+ if (typeof raw2 !== "string") return void 0;
15910
+ const ref = raw2.split(":").pop() ?? raw2;
15911
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
15912
+ return Number.isFinite(id) ? id : void 0;
15913
+ }
15914
+ function walletConnectCore(provider) {
15915
+ const p = provider;
15916
+ const core = p?.signer ?? p;
15917
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
15918
+ return null;
15919
+ }
15920
+ const peer = core.session.peer?.metadata?.name ?? "";
15921
+ if (!/metamask/i.test(peer)) return null;
15922
+ return core;
15923
+ }
15924
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
15925
+ const core = walletConnectCore(provider);
15926
+ if (!core) return false;
15927
+ holds.get(core.session.topic)?.();
15928
+ await requestSwitch(core, provider, chainId, timeoutMs);
15929
+ holdChain(core, provider, chainId);
15930
+ return true;
15931
+ }
15932
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
15933
+ const current = Number(
15934
+ await provider.request({ method: "eth_chainId" })
15935
+ );
15936
+ const hexChainId = `0x${chainId.toString(16)}`;
15937
+ let timer;
15938
+ try {
15939
+ await Promise.race([
15940
+ core.client.request({
15941
+ topic: core.session.topic,
15942
+ chainId: `eip155:${current}`,
15943
+ request: {
15944
+ method: "wallet_switchEthereumChain",
15945
+ params: [{ chainId: hexChainId }]
15946
+ }
15947
+ }),
15948
+ new Promise((_, reject) => {
15949
+ timer = setTimeout(
15950
+ () => reject(
15951
+ new Error("The wallet did not answer the network switch in time")
15952
+ ),
15953
+ timeoutMs
15954
+ );
15955
+ })
15956
+ ]);
15957
+ } finally {
15958
+ clearTimeout(timer);
15959
+ }
15960
+ try {
15961
+ core.setDefaultChain(`eip155:${chainId}`);
15962
+ } catch {
15963
+ }
15964
+ }
15965
+ function holdChain(core, provider, chainId) {
15966
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
15967
+ return;
15968
+ }
15969
+ let resends = 0;
15970
+ const listener = (raw2) => {
15971
+ const reported = parseChainId(raw2);
15972
+ debugLog("wc-switch", "wallet reported chain", {
15973
+ reported,
15974
+ holding: chainId,
15975
+ resends
15976
+ });
15977
+ if (reported === void 0 || reported === chainId) return;
15978
+ if (resends >= MAX_RESENDS) return;
15979
+ resends += 1;
15980
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
15981
+ (error) => debugLog("wc-switch", "re-switch failed", {
15982
+ error: error instanceof Error ? error.message : String(error)
15983
+ })
15984
+ );
15985
+ };
15986
+ const release = () => {
15987
+ clearTimeout(timer);
15988
+ core.removeListener?.("chainChanged", listener);
15989
+ if (holds.get(core.session.topic) === release) {
15990
+ holds.delete(core.session.topic);
15991
+ }
15992
+ };
15993
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
15994
+ core.on("chainChanged", listener);
15995
+ holds.set(core.session.topic, release);
15996
+ }
15997
+ function withWalletConnectSwitch(provider) {
15998
+ if (!walletConnectCore(provider)) return provider;
15999
+ const target = provider;
16000
+ const request2 = async (args) => {
16001
+ if (args?.method !== "wallet_switchEthereumChain") {
16002
+ return target.request(args);
16003
+ }
16004
+ const [param] = args.params ?? [];
16005
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
16006
+ if (!Number.isFinite(chainId)) return target.request(args);
16007
+ await switchWalletConnectChain(target, chainId);
16008
+ return null;
16009
+ };
16010
+ return new Proxy(target, {
16011
+ get(obj, prop) {
16012
+ if (prop === "request") return request2;
16013
+ const value = Reflect.get(obj, prop, obj);
16014
+ return typeof value === "function" ? value.bind(obj) : value;
16015
+ }
16016
+ });
16017
+ }
16018
+
14288
16019
  // src/lib/sponsored-calls-deposit.ts
14289
16020
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
14290
16021
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -14463,6 +16194,19 @@ function makeSponsoredCallsCallback(deps) {
14463
16194
  var WALLET_CATCHUP_TIMEOUT_MS = 3e4;
14464
16195
  var PERMIT2_ALLOWANCE_VERIFY_ATTEMPTS = 6;
14465
16196
  var PERMIT2_ALLOWANCE_VERIFY_DELAY_MS = 250;
16197
+ function shortfallBalance(error, asked) {
16198
+ if (!(error instanceof OwneyError)) return void 0;
16199
+ if (error.code !== "DEPOSIT_INSUFFICIENT_BALANCE") return void 0;
16200
+ const seen = error.details?.balance;
16201
+ if (typeof seen !== "string") return void 0;
16202
+ const balance = BigInt(seen);
16203
+ if (balance <= 0n || balance >= asked) return void 0;
16204
+ return (asked - balance) * 100n <= asked ? balance : void 0;
16205
+ }
16206
+ function agentRunsOn(agent, chainId) {
16207
+ const chains = agent.supportedChainIds;
16208
+ return !chains || chains.includes(chainId);
16209
+ }
14466
16210
  function encodeMultiAgentCursor(map) {
14467
16211
  return Buffer.from(JSON.stringify(map), "utf8").toString("base64");
14468
16212
  }
@@ -14542,6 +16286,14 @@ var OwneySDK = class {
14542
16286
  * withdraw, but they are excluded from new deposits / activations.
14543
16287
  */
14544
16288
  disabledAgents = /* @__PURE__ */ new Set();
16289
+ /**
16290
+ * Agents whose sign-in the user cancelled this session (the wallet rejected
16291
+ * the prompt), keyed by chain. Until the app ends the session they are read
16292
+ * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
16293
+ * the user cancelled. A later successful activation of the agent removes
16294
+ * it, and `disconnect()` or a different wallet's `connect()` clears the map.
16295
+ */
16296
+ declinedSignIns = /* @__PURE__ */ new Map();
14545
16297
  state = null;
14546
16298
  connectionRevision = 0;
14547
16299
  disconnectingAgents = null;
@@ -14556,6 +16308,7 @@ var OwneySDK = class {
14556
16308
  zyfaiRpcUrls;
14557
16309
  yieldseekerApiBaseUrl;
14558
16310
  yieldseekerSiweOrigin;
16311
+ userPoolCustomization = false;
14559
16312
  routingApiBaseUrl;
14560
16313
  referralSource;
14561
16314
  ledger;
@@ -14576,6 +16329,8 @@ var OwneySDK = class {
14576
16329
  * session started: true when it armed the refresh, false when its deadline
14577
16330
  * had passed (it only dropped the cache and forced one snapshot read). */
14578
16331
  recoveredFundingReads = /* @__PURE__ */ new Map();
16332
+ /** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
16333
+ announcedDeposits = /* @__PURE__ */ new Set();
14579
16334
  fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
14580
16335
  activationChecks = /* @__PURE__ */ new Map();
14581
16336
  // Protect the SDK entry point as well as the mini-app hook. This owns only
@@ -14606,6 +16361,7 @@ var OwneySDK = class {
14606
16361
  this.routingApiBaseUrl = config.routingApiBaseUrl;
14607
16362
  this.paymasterServiceUrl = config.paymasterServiceUrl;
14608
16363
  this.referralSource = config.referralSource;
16364
+ this.userPoolCustomization = config.userPoolCustomization ?? false;
14609
16365
  this.ledger = createFundingLedger({
14610
16366
  apiKey: config.apiKey,
14611
16367
  baseUrl: config.routingApiBaseUrl,
@@ -14830,10 +16586,15 @@ var OwneySDK = class {
14830
16586
  }
14831
16587
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
14832
16588
  this.clearConnectionState();
16589
+ if (replacingOwner) this.declinedSignIns.clear();
14833
16590
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
14834
16591
  if (revision !== this.connectionRevision)
14835
16592
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
14836
- this.state = { provider, walletAddress, chainId: null };
16593
+ this.state = {
16594
+ provider: withWalletConnectSwitch(provider),
16595
+ walletAddress,
16596
+ chainId: null
16597
+ };
14837
16598
  }
14838
16599
  /**
14839
16600
  * Disconnect from all agents and clear connection state.
@@ -14842,6 +16603,7 @@ var OwneySDK = class {
14842
16603
  async disconnect() {
14843
16604
  ++this.connectionRevision;
14844
16605
  this.clearConnectionState();
16606
+ this.declinedSignIns.clear();
14845
16607
  await this.disconnectAgents();
14846
16608
  }
14847
16609
  clearConnectionState() {
@@ -14871,6 +16633,44 @@ var OwneySDK = class {
14871
16633
  isAgentDisabled(agentId) {
14872
16634
  return this.disabledAgents.has(agentId);
14873
16635
  }
16636
+ /**
16637
+ * True when `id` takes no new deposits on this chain and asset this
16638
+ * session: its adapter reports no agent for the slot.
16639
+ */
16640
+ isAgentUnavailable(id, chainId, asset) {
16641
+ if (asset === void 0) return false;
16642
+ return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
16643
+ }
16644
+ /**
16645
+ * The agents that take no new deposits on this chain and asset this
16646
+ * session, so the app can show them as unavailable: each agent whose
16647
+ * provider has no agent for this slot. They stay withdrawable.
16648
+ */
16649
+ getUnavailableAgentIds(chainId, asset) {
16650
+ return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
16651
+ }
16652
+ /**
16653
+ * The adapter reports no agent for this chain and asset this session (see
16654
+ * `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
16655
+ * withdrawal without an explicit agent leaves it out instead of failing its
16656
+ * leg.
16657
+ */
16658
+ hasNoAgentForSlot(agent, state, chainId, asset) {
16659
+ return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
16660
+ }
16661
+ /**
16662
+ * The state an agent's reads use. An agent whose sign-in the user cancelled
16663
+ * on the connection chain this session is read from a saved sign-in only,
16664
+ * as `offChainPortfolioAgents` reads: a read that would need a wallet
16665
+ * prompt fails for that agent instead of reopening the prompt the user
16666
+ * cancelled. A later successful activation of the agent, or `disconnect()`,
16667
+ * lifts it.
16668
+ */
16669
+ readStateFor(agentId, state) {
16670
+ const chainId = state.chainId;
16671
+ if (state.promptless === true || chainId === null) return state;
16672
+ return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
16673
+ }
14874
16674
  /**
14875
16675
  * Check if the SDK has an active connection state.
14876
16676
  * @returns `true` if `connect()` has been called and `disconnect()` has not
@@ -15066,6 +16866,35 @@ var OwneySDK = class {
15066
16866
  }
15067
16867
  return active;
15068
16868
  }
16869
+ /**
16870
+ * Agents that do not run on the connection chain but can be read on their
16871
+ * own from a saved sign-in: Yieldseeker, Base-only, while the wallet sits on
16872
+ * Arbitrum or Ethereum. The whole-portfolio reads (ROUT-479) add them, under
16873
+ * a promptless state; with no saved sign-in they are left out, as before.
16874
+ */
16875
+ offChainPortfolioAgents(state) {
16876
+ const connectionChain = state.chainId;
16877
+ if (connectionChain === null) return [];
16878
+ const active = this.getActiveAgents();
16879
+ const promptless = { ...state, promptless: true };
16880
+ return [...this.agents.values()].flatMap((agent) => {
16881
+ if (active.has(agent.id) || agentRunsOn(agent, connectionChain) || !agent.hasReadSession) return [];
16882
+ const chainIds = agent.supportedChainIds.filter((id) => agent.hasReadSession(promptless, id));
16883
+ return chainIds.length ? [{ agent, state: promptless, chainIds }] : [];
16884
+ });
16885
+ }
16886
+ /** Every agent a whole-portfolio read covers: the active ones on the
16887
+ * connection chain, then the off-chain ones on their own chain. */
16888
+ portfolioReads(state, chainId) {
16889
+ return [
16890
+ ...this.activeReads(state, chainId),
16891
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
16892
+ ];
16893
+ }
16894
+ /** The active agents, each with the state its reads use (`readStateFor`). */
16895
+ activeReads(state, chainId) {
16896
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
16897
+ }
15069
16898
  /**
15070
16899
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
15071
16900
  * throws — it degrades to null — so this cannot break activation.
@@ -15102,7 +16931,8 @@ var OwneySDK = class {
15102
16931
  try {
15103
16932
  const policy = await this.getOrgAgentConfig();
15104
16933
  if (!policy) return;
15105
- await agent.applyOrgPolicy(state, chainId, policy);
16934
+ const effective = orgPolicyForConnect(policy, this.userPoolCustomization);
16935
+ await agent.applyOrgPolicy(state, chainId, effective);
15106
16936
  } catch (error) {
15107
16937
  console.warn(
15108
16938
  `[owney-sdk] applyOrgPolicy(${agent.id}) failed (non-fatal):`,
@@ -15188,7 +17018,7 @@ var OwneySDK = class {
15188
17018
  */
15189
17019
  async getAvailableAgents(options = {}) {
15190
17020
  await this.ensureAgentsInitialized();
15191
- const { chainId, asset, includeDisabled = false } = options;
17021
+ const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
15192
17022
  const available = [];
15193
17023
  for (const [id, agent] of this.agents) {
15194
17024
  const isEnabled = !this.isAgentDisabled(id);
@@ -15204,6 +17034,9 @@ var OwneySDK = class {
15204
17034
  continue;
15205
17035
  }
15206
17036
  }
17037
+ if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
17038
+ continue;
17039
+ }
15207
17040
  available.push({
15208
17041
  id,
15209
17042
  isEnabled,
@@ -15223,8 +17056,17 @@ var OwneySDK = class {
15223
17056
  * that support the given chainId (incompatible agents are silently skipped).
15224
17057
  * If provided, ALL specified agents must support the chainId or the call
15225
17058
  * throws before activating any agent.
17059
+ * @param options - Optional. `asset` limits setup to that asset;
17060
+ * `onAgentsSelected` fires once reads can start.
17061
+ * @throws Activation stops at the first agent that fails, and the caller
17062
+ * should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
17063
+ * earlier agent activated; `walletRejected` in its details means the user
17064
+ * rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
17065
+ * never be readied (`details.permanent`). Otherwise the agent's own error
17066
+ * is thrown as is. Until it signs in, an agent whose signature the user
17067
+ * rejected is read from a saved sign-in only and opens no prompt.
15226
17068
  */
15227
- async activateAgent(chainId, agentId, asset) {
17069
+ async activateAgent(chainId, agentId, options = {}) {
15228
17070
  const state = this.requireState();
15229
17071
  await this.ensureAgentsInitialized();
15230
17072
  this.assertActivationSession(state);
@@ -15261,7 +17103,8 @@ var OwneySDK = class {
15261
17103
  this.activeAgents.add(id);
15262
17104
  }
15263
17105
  state.chainId = chainId;
15264
- await this.activateAgentsInTurn(agents, state, chainId, asset);
17106
+ options.onAgentsSelected?.();
17107
+ await this.activateAgentsInTurn(agents, state, chainId, options.asset);
15265
17108
  return;
15266
17109
  }
15267
17110
  const compatible = [...this.agents.values()].filter(
@@ -15279,10 +17122,11 @@ var OwneySDK = class {
15279
17122
  this.activeAgents.add(agent.id);
15280
17123
  }
15281
17124
  state.chainId = chainId;
17125
+ options.onAgentsSelected?.();
15282
17126
  const enabledCompatible = compatible.filter(
15283
17127
  (agent) => !this.isAgentDisabled(agent.id)
15284
17128
  );
15285
- await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
17129
+ await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
15286
17130
  }
15287
17131
  assertActivationSession(state) {
15288
17132
  if (this.state !== state) {
@@ -15302,12 +17146,17 @@ var OwneySDK = class {
15302
17146
  * Serializing costs no real wall-clock: the user can only approve one prompt
15303
17147
  * at a time anyway.
15304
17148
  *
15305
- * Stop at the first failure so a canceled sign-in does not open another
15306
- * agent's wallet prompt. Report any earlier successes for diagnostics; the
15307
- * app discards the session when the complete sign-in does not succeed.
17149
+ * Stop at the first failure (2026-11-06): a connect needs every agent, so
17150
+ * no later agent's wallet prompt opens for a sign-in that already failed.
17151
+ * When an earlier agent activated, the partial failure reports it, and
17152
+ * `walletRejected` tells the app the user canceled; the app ends the
17153
+ * session either way. When none activated, the agent's own error is thrown.
17154
+ * A failure the provider marks `permanent` is thrown as
17155
+ * `AGENT_ACTIVATION_BLOCKED`.
15308
17156
  */
15309
17157
  async activateAgentsInTurn(agents, state, chainId, asset) {
15310
17158
  let firstError = null;
17159
+ let walletRejected = false;
15311
17160
  const activatedAgentIds = [];
15312
17161
  const failedAgents = [];
15313
17162
  for (const agent of agents) {
@@ -15318,6 +17167,7 @@ var OwneySDK = class {
15318
17167
  await this.applyOrgPolicyTo(agent, state, chainId);
15319
17168
  this.assertActivationSession(state);
15320
17169
  activatedAgentIds.push(agent.id);
17170
+ this.declinedSignIns.get(chainId)?.delete(agent.id);
15321
17171
  } catch (error) {
15322
17172
  this.assertActivationSession(state);
15323
17173
  const message = error !== null && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "No activation error message was returned.";
@@ -15327,15 +17177,28 @@ var OwneySDK = class {
15327
17177
  message,
15328
17178
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
15329
17179
  });
15330
- if (firstError === null) {
15331
- firstError = error;
15332
- } else {
15333
- console.error(`activateAgent(${agent.id}) failed:`, error);
17180
+ firstError = error;
17181
+ if (this.isUserRejectedWithdrawal(error)) {
17182
+ walletRejected = true;
17183
+ const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
17184
+ declined.add(agent.id);
17185
+ this.declinedSignIns.set(chainId, declined);
15334
17186
  }
15335
17187
  break;
15336
17188
  }
15337
17189
  }
15338
17190
  if (firstError === null) return;
17191
+ if (failedAgents.some(({ details }) => details?.permanent === true)) {
17192
+ throw new OwneyError(
17193
+ "AGENT_ACTIVATION_BLOCKED",
17194
+ failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
17195
+ {
17196
+ activatedAgentIds,
17197
+ failedAgentIds: failedAgents.map(({ agentId }) => agentId),
17198
+ failures: failedAgents
17199
+ }
17200
+ );
17201
+ }
15339
17202
  if (activatedAgentIds.length === 0) throw firstError;
15340
17203
  const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
15341
17204
  const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
@@ -15345,7 +17208,7 @@ var OwneySDK = class {
15345
17208
  throw new OwneyError(
15346
17209
  "AGENT_ACTIVATION_PARTIAL_FAILURE",
15347
17210
  `${activeNames} activated. ${failureMessages}`,
15348
- { activatedAgentIds, failedAgentIds, failures: failedAgents }
17211
+ { activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
15349
17212
  );
15350
17213
  }
15351
17214
  /**
@@ -15360,6 +17223,10 @@ var OwneySDK = class {
15360
17223
  * all shares into one signature; custom callbacks still run once per agent.
15361
17224
  * @param options.agentId - Optional explicit target. Otherwise split equally,
15362
17225
  * or fund remaining agents when a recovery deposit cannot meet every minimum.
17226
+ * @param options.excludeAgentIds - Agents that must receive nothing. The rest
17227
+ * split the whole amount under their own minimums. Throws
17228
+ * `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
17229
+ * when resuming a signed batch.
15363
17230
  * @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
15364
17231
  */
15365
17232
  async deposit(options) {
@@ -15388,6 +17255,7 @@ var OwneySDK = class {
15388
17255
  const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
15389
17256
  if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
15390
17257
  if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
17258
+ this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
15391
17259
  } catch {
15392
17260
  }
15393
17261
  };
@@ -15421,15 +17289,18 @@ var OwneySDK = class {
15421
17289
  return { agentResults: {} };
15422
17290
  }
15423
17291
  const state = this.requireState();
15424
- const chainId = this.requireChainId();
17292
+ const chainId = options.chainId ?? this.requireChainId();
17293
+ const activatedChain = state.chainId;
17294
+ const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
17295
+ this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
15425
17296
  let checkpointFailure;
15426
17297
  let checkpointFailedEvidence = [];
15427
17298
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
15428
17299
  try {
15429
- if (this.state !== state || state.chainId !== chainId) throw new Error("Wallet changed before deposit submission.");
17300
+ if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
15430
17301
  const submitting = evidence.map((leg) => ({ ...leg, depositSubmission: "started" }));
15431
17302
  await options.onBeforeSubmission(submitting);
15432
- if (this.state !== state || state.chainId !== chainId) throw new Error("Wallet changed before deposit submission.");
17303
+ if (this.state !== state || state.chainId !== activatedChain) throw new Error("Wallet changed before deposit submission.");
15433
17304
  submitting.forEach((leg) => notifyFunding(onProgress, leg));
15434
17305
  } catch (cause) {
15435
17306
  checkpointFailedEvidence = evidence;
@@ -15471,7 +17342,8 @@ var OwneySDK = class {
15471
17342
  chainId,
15472
17343
  token: ledgerToken?.address ?? "",
15473
17344
  asset: asset.toLowerCase(),
15474
- requestedAmountRaw: amount
17345
+ requestedAmountRaw: amount,
17346
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
15475
17347
  });
15476
17348
  } catch {
15477
17349
  }
@@ -15497,7 +17369,7 @@ var OwneySDK = class {
15497
17369
  const wallet = await (agent.getFundingWallet ? agent.getFundingWallet(state, chainId, asset) : agent.getUserProfile(state, chainId).then((profile) => profile.smartWallet)).catch(() => void 0);
15498
17370
  return { agent, wallet };
15499
17371
  }));
15500
- if (this.state !== state || this.state.chainId !== chainId)
17372
+ if (this.state !== state || this.state.chainId !== activatedChain)
15501
17373
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while recovering the deposit.");
15502
17374
  const usedAgents = /* @__PURE__ */ new Set();
15503
17375
  const legs = pending.transfers.map((transfer) => {
@@ -15517,11 +17389,11 @@ var OwneySDK = class {
15517
17389
  const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
15518
17390
  if (!batchTransfer2) throw invalid2();
15519
17391
  const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
15520
- if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
17392
+ if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
15521
17393
  throw new OwneyError(
15522
17394
  error.code,
15523
- "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
15524
- { ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
17395
+ error.code === "YIELDSEEKER_WALLET_UNVERIFIED" ? "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier." : "The saved deposit was not re-sent. It may already have been submitted earlier.",
17396
+ { cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
15525
17397
  error.agentId
15526
17398
  );
15527
17399
  throw error;
@@ -15537,6 +17409,7 @@ var OwneySDK = class {
15537
17409
  );
15538
17410
  }
15539
17411
  const agent = this.getAgent(agentId);
17412
+ this.validateChainSupport(agent, chainId);
15540
17413
  this.validateAssetSupport(agent, chainId, asset);
15541
17414
  await this.validateMinDepositAmount(agent, state, chainId, asset, amount);
15542
17415
  return ledgerDone(await this.depositWithFallback(
@@ -15555,9 +17428,10 @@ var OwneySDK = class {
15555
17428
  ));
15556
17429
  }
15557
17430
  const totalAmount = BigInt(amount);
17431
+ this.validateChainHasAgents(chainId);
15558
17432
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
15559
17433
  excludeDisabled: true
15560
- });
17434
+ }).filter((agent) => !excludeAgentIds?.includes(agent.id));
15561
17435
  const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
15562
17436
  const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
15563
17437
  const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
@@ -15705,7 +17579,7 @@ var OwneySDK = class {
15705
17579
  }
15706
17580
  try {
15707
17581
  if (!depositCallback && appObserves && !options.resumeTxHash) {
15708
- const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
17582
+ const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
15709
17583
  for (const id of ids) {
15710
17584
  const evidence = [...prepared.values()].find((value) => value.agentId === id);
15711
17585
  const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
@@ -15805,6 +17679,29 @@ var OwneySDK = class {
15805
17679
  }
15806
17680
  }
15807
17681
  }
17682
+ /**
17683
+ * Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
17684
+ * the explicit `agentId` is listed, or every agent that can take this asset
17685
+ * on this chain (and is not disabled) is. A no-op without a list, so a deposit
17686
+ * without exclusions is exactly as it was. Reads no provider.
17687
+ */
17688
+ assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
17689
+ if (!excludeAgentIds?.length) return;
17690
+ const refuse = (message) => new OwneyError(
17691
+ "ALL_AGENTS_EXCLUDED",
17692
+ message,
17693
+ { phase: "prepare", rejectedBeforeSubmission: true }
17694
+ );
17695
+ if (agentId) {
17696
+ if (excludeAgentIds.includes(agentId))
17697
+ throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
17698
+ return;
17699
+ }
17700
+ this.validateChainHasAgents(chainId);
17701
+ const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
17702
+ if (remaining.length === 0)
17703
+ throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
17704
+ }
15808
17705
  getMinDepositAmount(agent, chainId, asset) {
15809
17706
  const chainAssets = agent.supportedAssets.find(
15810
17707
  (sa) => sa.chainId === chainId
@@ -15911,6 +17808,41 @@ var OwneySDK = class {
15911
17808
  return false;
15912
17809
  }
15913
17810
  }
17811
+ /**
17812
+ * Guard an explicitly requested chain against one agent's own list.
17813
+ *
17814
+ * Only reachable when the caller passes `chainId` — the activated chain has
17815
+ * already been checked by `activateAgent`. Kept separate from
17816
+ * `validateAssetSupport` so "this agent is not on Ethereum" does not arrive
17817
+ * worded as "this agent does not support USDC".
17818
+ */
17819
+ validateChainSupport(agent, chainId) {
17820
+ if (!agent.supportedChainIds.includes(chainId)) {
17821
+ throw new AgentChainIncompatibleError(
17822
+ [{ agentId: agent.id, supportedChainIds: agent.supportedChainIds }],
17823
+ chainId
17824
+ );
17825
+ }
17826
+ }
17827
+ /**
17828
+ * Guard an explicitly requested chain before a fan-out.
17829
+ *
17830
+ * Without this the split simply produces no agents, and the caller is told
17831
+ * their amount "cannot activate every eligible agent" against a combined
17832
+ * minimum of 0 — an error about the amount when the chain is at fault.
17833
+ */
17834
+ validateChainHasAgents(chainId) {
17835
+ const compatible = [...this.agents.values()].some(
17836
+ (agent) => agent.supportedChainIds.includes(chainId)
17837
+ );
17838
+ if (!compatible) {
17839
+ throw new OwneyError(
17840
+ "CHAIN_NO_COMPATIBLE_AGENTS",
17841
+ `No agents support chain ${chainId}.`,
17842
+ { chainId }
17843
+ );
17844
+ }
17845
+ }
15914
17846
  validateAssetSupport(agent, chainId, asset) {
15915
17847
  const chainAssets = agent.supportedAssets.find(
15916
17848
  (sa) => sa.chainId === chainId
@@ -15924,9 +17856,15 @@ var OwneySDK = class {
15924
17856
  );
15925
17857
  }
15926
17858
  }
17859
+ /**
17860
+ * The agents that support this asset on this chain. `excludeDisabled` is for
17861
+ * new deposits: it also leaves out the agents unavailable for this slot this
17862
+ * session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
17863
+ * recovery still see every agent that may hold funds.
17864
+ */
15927
17865
  getEligibleAgents(chainId, asset, opts) {
15928
17866
  const eligible = [...this.agents.values()].filter((agent) => {
15929
- if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
17867
+ if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
15930
17868
  return false;
15931
17869
  }
15932
17870
  const chainAssets = agent.supportedAssets.find(
@@ -15954,20 +17892,13 @@ var OwneySDK = class {
15954
17892
  return approvalOrder || left.index - right.index;
15955
17893
  }).map(({ agent }) => agent);
15956
17894
  }
17895
+ /**
17896
+ * The user cancelled a wallet prompt, for any agent: see isWalletRejection.
17897
+ * That includes an agent error that kept the rejection only as text in
17898
+ * `details.cause`.
17899
+ */
15957
17900
  isUserRejectedWithdrawal(error) {
15958
- let current = error;
15959
- const seen = /* @__PURE__ */ new Set();
15960
- while (current && typeof current === "object" && !seen.has(current)) {
15961
- seen.add(current);
15962
- const candidate = current;
15963
- if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
15964
- const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
15965
- if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
15966
- return true;
15967
- }
15968
- current = candidate.cause;
15969
- }
15970
- return false;
17901
+ return isWalletRejection(error);
15971
17902
  }
15972
17903
  captureReadScope(requestedChain) {
15973
17904
  const original = this.requireState();
@@ -16068,6 +17999,7 @@ var OwneySDK = class {
16068
17999
  if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
16069
18000
  verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
16070
18001
  }
18002
+ if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
16071
18003
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
16072
18004
  if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
16073
18005
  agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
@@ -16076,6 +18008,33 @@ var OwneySDK = class {
16076
18008
  }
16077
18009
  return verified;
16078
18010
  }
18011
+ /**
18012
+ * Tells the agent, once per confirmed deposit transfer, that its deposit
18013
+ * landed (`IAgent.depositConfirmed`), and records the outcome on the
18014
+ * deposit's ledger operation when there is one. In the background: never
18015
+ * throws and never delays the deposit. A missed notice only leaves the
18016
+ * provider on its own schedule.
18017
+ */
18018
+ announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18019
+ try {
18020
+ if (evidence.transfer !== "confirmed") return;
18021
+ const agent = this.agents.get(evidence.agentId);
18022
+ const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
18023
+ if (!agent?.depositConfirmed || !movement) return;
18024
+ const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
18025
+ if (this.announcedDeposits.has(key2)) return;
18026
+ this.announcedDeposits.add(key2);
18027
+ if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18028
+ const legKey = `agent:${evidence.agentId}`;
18029
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18030
+ try {
18031
+ ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18032
+ } catch {
18033
+ }
18034
+ });
18035
+ } catch {
18036
+ }
18037
+ }
16079
18038
  noteFundingRefresh(key2, armed) {
16080
18039
  this.recoveredFundingReads.delete(key2);
16081
18040
  this.recoveredFundingReads.set(key2, armed);
@@ -16564,6 +18523,14 @@ var OwneySDK = class {
16564
18523
  return hash2;
16565
18524
  },
16566
18525
  ensureChain: (id) => this.ensureSwapChain(id),
18526
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
18527
+ // page cannot also hide that it landed (ROUT-726).
18528
+ readWrappedBalance: () => publicClient.readContract({
18529
+ address: wrapper.address,
18530
+ abi: ERC20_ALLOWANCE_ABI,
18531
+ functionName: "balanceOf",
18532
+ args: [walletAddress]
18533
+ }),
16567
18534
  // Read through the same public client as every other sizing input, so
16568
18535
  // a wallet sitting on the wrong chain cannot answer for this one.
16569
18536
  readAllowance: (token, spender) => publicClient.readContract({
@@ -16646,6 +18613,19 @@ var OwneySDK = class {
16646
18613
  chain: dstChain,
16647
18614
  transport: swapReadTransport(quote.dst.chainId, this.zyfaiRpcUrls)
16648
18615
  });
18616
+ const walletPublic = createPublicClient4({
18617
+ chain: srcChain,
18618
+ transport: custom5(provider)
18619
+ });
18620
+ const signOnSource = (payload) => signWithChainRetry(
18621
+ walletPublic,
18622
+ wallet,
18623
+ quote.src.chainId,
18624
+ () => wallet.signTypedData({
18625
+ account: state.walletAddress,
18626
+ ...payload
18627
+ })
18628
+ );
16649
18629
  return {
16650
18630
  api: this.swapApi(),
16651
18631
  // Native-aware, like readSourceBalance below. Native ETH is never a
@@ -16696,10 +18676,7 @@ var OwneySDK = class {
16696
18676
  },
16697
18677
  signTypedData: (typedData) => {
16698
18678
  assertWallet();
16699
- return wallet.signTypedData({
16700
- account: state.walletAddress,
16701
- ...typedData
16702
- });
18679
+ return signOnSource(typedData);
16703
18680
  },
16704
18681
  // Chain-bound like every other read here: the wallet provider's chain is
16705
18682
  // not ours to rely on mid-swap.
@@ -16768,10 +18745,7 @@ var OwneySDK = class {
16768
18745
  chainId: quote.src.chainId,
16769
18746
  signTypedData: (payload) => {
16770
18747
  assertWallet();
16771
- return wallet.signTypedData({
16772
- account: state.walletAddress,
16773
- ...payload
16774
- });
18748
+ return signOnSource(payload);
16775
18749
  }
16776
18750
  }
16777
18751
  ),
@@ -16798,13 +18772,27 @@ var OwneySDK = class {
16798
18772
  * would strand funds we might have been able to move.
16799
18773
  */
16800
18774
  /** ERC20 balance of the connected wallet, read through the wallet's own node. */
18775
+ /**
18776
+ * A read client pinned to `chainId`, over HTTP rather than the wallet.
18777
+ *
18778
+ * The swap rail has read this way from the start, and the reason is written
18779
+ * out at `buildSwapDeps`: a provider-backed client reads from whatever chain
18780
+ * the WALLET is on, which after a cross-chain swap is the source chain, not
18781
+ * the one the funds landed on. The deposit's own reads did not, so a Permit2
18782
+ * check for WETH on Arbitrum went to Base — where that address is not a
18783
+ * contract at all, so viem got "0x" back and threw "The contract function
18784
+ * 'allowance' returned no data".
18785
+ */
18786
+ chainReader(chainId) {
18787
+ return createPublicClient4({
18788
+ chain: swapChain(chainId),
18789
+ transport: swapReadTransport(chainId, this.zyfaiRpcUrls)
18790
+ });
18791
+ }
16801
18792
  async readTokenBalance(chainId, token) {
16802
18793
  const state = this.requireState();
16803
18794
  return readErc20Balance(
16804
- createPublicClient4({
16805
- chain: swapChain(chainId),
16806
- transport: custom5(this.requireConnectedProvider())
16807
- }),
18795
+ this.chainReader(chainId),
16808
18796
  token,
16809
18797
  state.walletAddress
16810
18798
  );
@@ -16813,10 +18801,7 @@ var OwneySDK = class {
16813
18801
  async readTokenPermit2Allowance(chainId, token) {
16814
18802
  const state = this.requireState();
16815
18803
  return readPermit2Allowance(
16816
- createPublicClient4({
16817
- chain: swapChain(chainId),
16818
- transport: custom5(this.requireConnectedProvider())
16819
- }),
18804
+ this.chainReader(chainId),
16820
18805
  token,
16821
18806
  state.walletAddress
16822
18807
  );
@@ -16845,6 +18830,34 @@ var OwneySDK = class {
16845
18830
  const balance = await this.readTokenBalance(chainId, token);
16846
18831
  return (balance < received ? balance : received).toString();
16847
18832
  }
18833
+ /**
18834
+ * Deposit a swap's output, retrying once at the balance the deposit saw.
18835
+ *
18836
+ * `settleSwapDepositAmount` approves and THEN reads, but the read and the
18837
+ * deposit's own pre-check can disagree: the approval is confirmed through
18838
+ * the wallet's node, the read goes to a pinned RPC, and gas paid in WETH
18839
+ * (MetaMask offers this to a wallet with no ETH) can land after either.
18840
+ * ROUT-618 failed that way with the settle step in place.
18841
+ *
18842
+ * The pre-check reports the balance it saw, and that is the authority, so
18843
+ * a shortfall is retried once at that figure. Only a small one: a node that
18844
+ * has not caught up can read near zero, and depositing that would leave the
18845
+ * rest of the swap stranded behind a "success".
18846
+ */
18847
+ async depositSwapOutput(options) {
18848
+ const attempt = (amount) => this.deposit({ ...options, amount });
18849
+ try {
18850
+ return {
18851
+ deposit: await attempt(options.amount),
18852
+ deposited: options.amount
18853
+ };
18854
+ } catch (error) {
18855
+ const balance = shortfallBalance(error, BigInt(options.amount));
18856
+ if (balance === void 0) throw error;
18857
+ const deposited = balance.toString();
18858
+ return { deposit: await attempt(deposited), deposited };
18859
+ }
18860
+ }
16848
18861
  async walletSeesBalance(chainId, token, amount) {
16849
18862
  const provider = this.requireConnectedProvider();
16850
18863
  const state = this.requireState();
@@ -16870,9 +18883,39 @@ var OwneySDK = class {
16870
18883
  * Runs a quoted swap. A named seam rather than an inline `executeSwap` call
16871
18884
  * so the deposit half of `swapAndDeposit` can be exercised on its own.
16872
18885
  */
16873
- runSwap(quote, options, onTransactionHash) {
18886
+ async runSwap(quote, options, onTransactionHash) {
18887
+ await this.checkSwapGas(quote);
16874
18888
  return executeSwap(this.buildSwapDeps(quote, options.assertCurrent, onTransactionHash), { quote, ...options });
16875
18889
  }
18890
+ /**
18891
+ * Throws SWAP_INSUFFICIENT_GAS when the wallet cannot pay for this swap.
18892
+ *
18893
+ * Only the classic rail is ever refused: it is the one where the user sends
18894
+ * the transactions. Call it on a preview quote to warn BEFORE a withdrawal
18895
+ * moves anything — `withdrawAndSwap` repeats it on its own quote, but by
18896
+ * then the funds have already left the agent (ROUT-622).
18897
+ */
18898
+ async checkSwapGas(quote) {
18899
+ const state = this.requireState();
18900
+ const chain2 = swapChain(quote.src.chainId);
18901
+ if (!chain2) return;
18902
+ const pub = createPublicClient4({
18903
+ chain: chain2,
18904
+ transport: swapReadTransport(quote.src.chainId, this.zyfaiRpcUrls)
18905
+ });
18906
+ const shortfall = await swapGasShortfall(
18907
+ {
18908
+ readNativeBalance: () => pub.getBalance({ address: state.walletAddress }),
18909
+ // The 1559 ceiling, as the wrap reserve reads it.
18910
+ getMaxFeePerGas: async () => {
18911
+ const fees = await pub.estimateFeesPerGas();
18912
+ return fees.maxFeePerGas ?? pub.getGasPrice();
18913
+ }
18914
+ },
18915
+ quote
18916
+ );
18917
+ if (shortfall) throw swapGasError(shortfall, chain2.nativeCurrency.symbol);
18918
+ }
16876
18919
  /**
16877
18920
  * The half of the swap deps that only ever talks to the routing API.
16878
18921
  *
@@ -16933,8 +18976,17 @@ var OwneySDK = class {
16933
18976
  * second half of `swapAndDeposit` on its own. Cleared only once the deposit
16934
18977
  * has actually gone through — a failure here leaves the record in place so it
16935
18978
  * can be offered again rather than silently dropped.
18979
+ *
18980
+ * The record does not remember `excludeAgentIds`, on purpose: the caller must
18981
+ * pass the CURRENT list, because the user's choice may have changed since the
18982
+ * swap (a deposit reads it fresh each time). Without it, a record with no
18983
+ * `agentId` splits across every eligible agent. When the list leaves nobody to
18984
+ * fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
18985
+ * before the wallet is touched and keeps the record.
18986
+ *
18987
+ * @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
16936
18988
  */
16937
- async completePendingDeposit(id) {
18989
+ async completePendingDeposit(id, options = {}) {
16938
18990
  const entry = listPendingDeposits().find((p) => p.id === id);
16939
18991
  if (!entry) {
16940
18992
  throw new OwneyError(
@@ -16943,13 +18995,28 @@ var OwneySDK = class {
16943
18995
  { id }
16944
18996
  );
16945
18997
  }
18998
+ this.assertDepositAgentsRemain(
18999
+ entry.chainId,
19000
+ entry.symbol,
19001
+ entry.agentId,
19002
+ options.excludeAgentIds
19003
+ );
16946
19004
  await this.ensureSwapChain(entry.chainId);
16947
- const deposit = await this.deposit({
16948
- amount: entry.received,
19005
+ const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
19006
+ const amount = token ? await this.settleSwapDepositAmount(
19007
+ entry.chainId,
19008
+ token,
19009
+ entry.symbol,
19010
+ BigInt(entry.received)
19011
+ ) : entry.received;
19012
+ const { deposit } = await this.depositSwapOutput({
19013
+ amount,
16949
19014
  asset: entry.symbol,
16950
19015
  ...entry.agentId ? { agentId: entry.agentId } : {},
19016
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
16951
19017
  // The swap's own funding-ledger operation; older records have none.
16952
- ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {}
19018
+ ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
19019
+ ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
16953
19020
  });
16954
19021
  clearPendingDeposit(entry.id);
16955
19022
  return deposit;
@@ -17008,13 +19075,15 @@ var OwneySDK = class {
17008
19075
  chainId: deposit.chainId,
17009
19076
  createdAt: Date.now(),
17010
19077
  ...typeof deposit.agentId === "string" ? { agentId: deposit.agentId } : {},
17011
- ...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {}
19078
+ ...typeof deposit.operationId === "string" ? { operationId: deposit.operationId } : {},
19079
+ ...typeof deposit.batchId === "string" ? { batchId: deposit.batchId } : {}
17012
19080
  });
17013
19081
  clearOrder(order.orderHash);
17014
19082
  updateWithdrawSwap(order.orderHash, { status: "landed" });
17015
19083
  return { orderHash: order.orderHash, status: "completed" };
17016
19084
  } catch (error) {
17017
- if (error instanceof OwneyError && error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded") {
19085
+ if (error instanceof OwneyError && (error.code === "SWAP_ORDER_REFUNDED" && error.details?.outcome === "refunded" || // The provider never accepted it: nothing was escrowed.
19086
+ error.code === "SWAP_ORDER_NOT_FOUND")) {
17018
19087
  clearOrder(order.orderHash);
17019
19088
  updateWithdrawSwap(order.orderHash, { status: "refunded" });
17020
19089
  } else {
@@ -17173,6 +19242,7 @@ var OwneySDK = class {
17173
19242
  async swapAndDeposit(options) {
17174
19243
  const state = this.requireState();
17175
19244
  options.assertCurrent?.();
19245
+ this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
17176
19246
  if (options.agentId) {
17177
19247
  this.validateAssetSupport(
17178
19248
  this.getAgent(options.agentId),
@@ -17187,7 +19257,8 @@ var OwneySDK = class {
17187
19257
  owner: state.walletAddress,
17188
19258
  chainId: options.to.chainId,
17189
19259
  token: SupportedAssets.find((value) => value.chainId === options.to.chainId && value.symbol === options.to.symbol)?.address ?? "",
17190
- asset: options.to.symbol.toLowerCase()
19260
+ asset: options.to.symbol.toLowerCase(),
19261
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17191
19262
  });
17192
19263
  const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
17193
19264
  try {
@@ -17225,7 +19296,8 @@ var OwneySDK = class {
17225
19296
  symbol: options.to.symbol,
17226
19297
  chainId: quote.dst.chainId,
17227
19298
  ...options.agentId ? { agentId: options.agentId } : {},
17228
- ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
19299
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
19300
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17229
19301
  },
17230
19302
  ...secretHandoff ? { secretHandoff } : {},
17231
19303
  ...ledgerOp ? { onOrderSubmitted: (orderHash) => {
@@ -17268,17 +19340,18 @@ var OwneySDK = class {
17268
19340
  options.assertCurrent?.();
17269
19341
  await options.onBeforeDeposit?.();
17270
19342
  options.assertCurrent?.();
17271
- const deposit = await this.deposit({
19343
+ const { deposit, deposited } = await this.depositSwapOutput({
17272
19344
  amount,
17273
19345
  asset: options.to.symbol,
17274
19346
  ...options.agentId ? { agentId: options.agentId } : {},
19347
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
17275
19348
  ...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
17276
19349
  ...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
17277
19350
  ...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
17278
19351
  ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
17279
19352
  });
17280
19353
  if (backgroundDepositId) clearPendingDeposit(backgroundDepositId);
17281
- return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited: amount });
19354
+ return this.ledgerSucceeded(ledgerOp, { swap, deposit, deposited });
17282
19355
  } catch (error) {
17283
19356
  const pending = {
17284
19357
  // Keyed by the order when there is one, so it replaces any record a
@@ -17290,7 +19363,11 @@ var OwneySDK = class {
17290
19363
  ...options.agentId ? { agentId: options.agentId } : {},
17291
19364
  createdAt: Date.now()
17292
19365
  };
17293
- savePendingDeposit(ledgerOp ? { ...pending, operationId: ledgerOp.operationId } : pending);
19366
+ savePendingDeposit({
19367
+ ...pending,
19368
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
19369
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
19370
+ });
17294
19371
  throw new OwneyError(
17295
19372
  "SWAP_DEPOSIT_PENDING",
17296
19373
  `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.`,
@@ -17340,7 +19417,8 @@ var OwneySDK = class {
17340
19417
  token: asset.address,
17341
19418
  asset: asset.symbol.toLowerCase(),
17342
19419
  isMax: recovery.requested === void 0,
17343
- ...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested }
19420
+ ...recovery.requested === void 0 ? {} : { requestedAmountRaw: recovery.requested },
19421
+ ...record2.batchId === void 0 ? {} : { batchId: record2.batchId }
17344
19422
  });
17345
19423
  } catch {
17346
19424
  }
@@ -17495,6 +19573,7 @@ var OwneySDK = class {
17495
19573
  let ledgerInput;
17496
19574
  ledgerOp = this.openSwapLedger(() => {
17497
19575
  const requestedRaw = saved ? saved.recovery.requested : options.amount === void 0 ? void 0 : parseUnits4(options.amount, asset.decimals).toString();
19576
+ const batchId = saved?.batchId ?? options.batchId;
17498
19577
  return ledgerInput = {
17499
19578
  operationId: saved?.operationId ?? options.operationId,
17500
19579
  kind: "withdraw_swap",
@@ -17503,7 +19582,8 @@ var OwneySDK = class {
17503
19582
  token: asset.address,
17504
19583
  asset: asset.symbol.toLowerCase(),
17505
19584
  isMax: requestedRaw === void 0,
17506
- ...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw }
19585
+ ...requestedRaw === void 0 ? {} : { requestedAmountRaw: requestedRaw },
19586
+ ...batchId === void 0 ? {} : { batchId }
17507
19587
  };
17508
19588
  });
17509
19589
  const secretHandoff = this.secretHandoffFor(ledgerOp, ledgerInput);
@@ -17548,7 +19628,8 @@ var OwneySDK = class {
17548
19628
  agentId: options.agentId,
17549
19629
  evidence: {}
17550
19630
  },
17551
- ...ledgerOp ? { operationId: ledgerOp.operationId } : {}
19631
+ ...ledgerOp ? { operationId: ledgerOp.operationId } : {},
19632
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17552
19633
  };
17553
19634
  if (ledgerOp && !record2.operationId) record2.operationId = ledgerOp.operationId;
17554
19635
  hadDurableRecord = saveWithdrawSwap(record2);
@@ -17664,6 +19745,8 @@ var OwneySDK = class {
17664
19745
  () => new OwneyError("SWAP_WALLET_PROMPT_TIMEOUT", "The wallet did not confirm its chain. No swap was submitted.", { outcome: "not-submitted" })
17665
19746
  );
17666
19747
  assertCurrent();
19748
+ await this.checkSwapGas(quote);
19749
+ assertCurrent();
17667
19750
  const swap = await executeSwap(this.buildSwapDeps(quote, assertCurrent, (hash2) => {
17668
19751
  record2.txHash = hash2;
17669
19752
  saveWithdrawSwap(record2);
@@ -17793,7 +19876,7 @@ var OwneySDK = class {
17793
19876
  { phase: "prepare", rejectedBeforeSubmission: true }
17794
19877
  );
17795
19878
  const state = this.requireState();
17796
- const chainId = this.requireChainId();
19879
+ const chainId = options.chainId ?? this.requireChainId();
17797
19880
  const submissionKey = `${state.walletAddress.toLowerCase()}:${chainId}:${options.asset.toUpperCase()}`;
17798
19881
  if (this.withdrawalSubmissions.has(submissionKey))
17799
19882
  throw new OwneyError(
@@ -17801,7 +19884,7 @@ var OwneySDK = class {
17801
19884
  "A withdrawal request is already running.",
17802
19885
  { chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
17803
19886
  );
17804
- const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
19887
+ const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
17805
19888
  const attempted = /* @__PURE__ */ new Set();
17806
19889
  this.withdrawalSubmissions.add(submissionKey);
17807
19890
  let ledgerOp;
@@ -17815,7 +19898,8 @@ var OwneySDK = class {
17815
19898
  token: ledgerToken?.address ?? "",
17816
19899
  asset: options.asset.toLowerCase(),
17817
19900
  isMax: options.amount === void 0,
17818
- ...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {}
19901
+ ...options.amount !== void 0 ? { requestedAmountRaw: BigInt(options.amount).toString() } : {},
19902
+ ...options.batchId === void 0 ? {} : { batchId: options.batchId }
17819
19903
  });
17820
19904
  } catch {
17821
19905
  }
@@ -18140,6 +20224,7 @@ var OwneySDK = class {
18140
20224
  }
18141
20225
  async withdrawFromAgents(options, state, chainId, attempted, ledgerLeg, reservation, plannedLegs, settleLedger, serverLegs = /* @__PURE__ */ new Map()) {
18142
20226
  const { asset, amount, agentId, onAgentResult } = options;
20227
+ const activatedChain = state.chainId;
18143
20228
  const notifyAgentResult = (id, result) => {
18144
20229
  try {
18145
20230
  if (result.evidence) notifyFunding(options.onProgress, result.evidence);
@@ -18200,7 +20285,7 @@ var OwneySDK = class {
18200
20285
  const plannedTask = serverLegs.get(agent.id);
18201
20286
  const serverTask = plannedTask ? await plannedTask.answer : void 0;
18202
20287
  if (serverTask) await settleLedger?.(3e3);
18203
- if (this.state !== state || this.state.chainId !== chainId)
20288
+ if (this.state !== state || this.state.chainId !== activatedChain)
18204
20289
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed before withdrawal submission.");
18205
20290
  attempted.add(agent.id);
18206
20291
  let evidence = {
@@ -18270,6 +20355,8 @@ var OwneySDK = class {
18270
20355
  progress({ ...evidence, transfer: "failed", delivery: "failed" });
18271
20356
  if (serverLegs.size && requested2 === void 0 && agent.withdrawalRequiresWalletApproval && error instanceof OwneyError && error.code === "WITHDRAW_INSUFFICIENT_BALANCE" && error.details?.available === "0" && evidence.transfer === "failed" && !evidence.txHash && !evidence.userOpHash && !evidence.callsId)
18272
20357
  ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
20358
+ else if (error instanceof OwneyError && /^[A-Z0-9_]{1,64}$/.test(error.code) && evidence.transfer === "failed" && !evidence.withdrawalRequest?.failure && !(requested2 === void 0 && error.code === "WITHDRAW_INSUFFICIENT_BALANCE"))
20359
+ ledgerLeg?.(evidence, error.code);
18273
20360
  settled({ settled: "threw", evidence });
18274
20361
  throw error;
18275
20362
  }
@@ -18285,6 +20372,7 @@ var OwneySDK = class {
18285
20372
  }
18286
20373
  if (agentId) {
18287
20374
  const agent = this.getAgent(agentId);
20375
+ this.validateChainSupport(agent, chainId);
18288
20376
  this.validateAssetSupport(agent, chainId, asset);
18289
20377
  const result = await withFailureReporting(
18290
20378
  this.apiKey,
@@ -18376,7 +20464,7 @@ var OwneySDK = class {
18376
20464
  serverLegs.set(planned.agentId, leg);
18377
20465
  }
18378
20466
  };
18379
- const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
20467
+ const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
18380
20468
  const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
18381
20469
  if (!amount) {
18382
20470
  const results2 = {};
@@ -18508,7 +20596,7 @@ var OwneySDK = class {
18508
20596
  const verified = await entry.agent.getWithdrawableBalance(state, chainId, token, minimumAmount);
18509
20597
  if (typeof verified !== "bigint" || verified < 0n)
18510
20598
  throw new OwneyError("WITHDRAW_BALANCE_UNAVAILABLE", "Invalid withdrawal balance proof.", {}, entry.agent.id);
18511
- if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== chainId)
20599
+ if (this.state !== state || this.state.walletAddress !== state.walletAddress || this.state.chainId !== activatedChain)
18512
20600
  throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
18513
20601
  entry.balance = verified;
18514
20602
  const unavailableIndex = unavailableAgents.indexOf(entry.agent);
@@ -18523,7 +20611,7 @@ var OwneySDK = class {
18523
20611
  };
18524
20612
  }
18525
20613
  }));
18526
- if (this.state !== state || this.state.chainId !== chainId)
20614
+ if (this.state !== state || this.state.chainId !== activatedChain)
18527
20615
  throw new OwneyError("NOT_CONNECTED", "Account changed while planning withdrawal.");
18528
20616
  const unavailableAgentIds = unavailableAgents.map((agent) => agent.id);
18529
20617
  const totalAvailable = balances.reduce((sum, x) => sum + x.balance, 0n);
@@ -18704,11 +20792,82 @@ var OwneySDK = class {
18704
20792
  * @param agentId - Optional. Agent to query. Omit for aggregated balances.
18705
20793
  * @returns {AgentBalance} for a single agent, or {OwneyBalances} with totalBalance and per-agent breakdown
18706
20794
  */
20795
+ /**
20796
+ * Withdraw every position the wallet holds, across chains and assets.
20797
+ *
20798
+ * `withdraw()` drains one asset on one chain, so this is N of those. It
20799
+ * deliberately does not stop at the first failure: the funds in the other
20800
+ * positions are just as withdrawable, and someone who asked for everything
20801
+ * is better served by three of four than by none. Each leg reports its own
20802
+ * outcome so the caller can name the ones that did not arrive; only a total
20803
+ * failure throws.
20804
+ *
20805
+ * @returns {OwneyWithdrawAllResult} one leg per position attempted.
20806
+ */
20807
+ async withdrawAll() {
20808
+ this.requireState();
20809
+ const balances = await this.readBalances(void 0, false);
20810
+ const positions = /* @__PURE__ */ new Map();
20811
+ for (const agentBalance of Object.values(balances.agentBalances ?? {})) {
20812
+ for (const token of agentBalance.tokens ?? []) {
20813
+ if (!(Number(token.amount) > 0)) continue;
20814
+ const key2 = `${token.chainId}:${token.asset}`;
20815
+ const seen = positions.get(key2);
20816
+ if (seen) {
20817
+ seen.amount = String(Number(seen.amount) + Number(token.amount));
20818
+ continue;
20819
+ }
20820
+ positions.set(key2, {
20821
+ chainId: token.chainId,
20822
+ asset: token.asset,
20823
+ amount: token.amount
20824
+ });
20825
+ }
20826
+ }
20827
+ if (positions.size === 0) {
20828
+ throw new OwneyError(
20829
+ "WITHDRAW_NOTHING_TO_WITHDRAW",
20830
+ "There is nothing to withdraw."
20831
+ );
20832
+ }
20833
+ const legs = [];
20834
+ for (const position2 of positions.values()) {
20835
+ try {
20836
+ const result = await this.withdraw({
20837
+ asset: position2.asset,
20838
+ chainId: position2.chainId
20839
+ });
20840
+ legs.push({ ...position2, result });
20841
+ } catch (err) {
20842
+ console.error(
20843
+ `withdrawAll failed for ${position2.asset} on ${position2.chainId}:`,
20844
+ err
20845
+ );
20846
+ legs.push({
20847
+ ...position2,
20848
+ error: err instanceof Error ? err.message : String(err)
20849
+ });
20850
+ }
20851
+ }
20852
+ if (legs.every((leg) => leg.error !== void 0)) {
20853
+ throw new OwneyError(
20854
+ "WITHDRAW_ALL_FAILED",
20855
+ "Failed to withdraw from every position.",
20856
+ {
20857
+ legErrors: Object.fromEntries(
20858
+ legs.map((leg) => [`${leg.asset}:${leg.chainId}`, leg.error])
20859
+ )
20860
+ }
20861
+ );
20862
+ }
20863
+ return { legs };
20864
+ }
18707
20865
  async getBalances(agentId, options) {
18708
20866
  if (agentId) {
18709
- const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20867
+ const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
18710
20868
  const asset = options?.asset;
18711
20869
  const agent = this.getAgent(agentId);
20870
+ const state = this.readStateFor(agentId, scope);
18712
20871
  const result = await this.readAgent(
18713
20872
  agent,
18714
20873
  "balances",
@@ -18721,7 +20880,11 @@ var OwneySDK = class {
18721
20880
  balanceComposition: agent.balanceComposition ?? "tokens-include-positions"
18722
20881
  };
18723
20882
  }
18724
- const { balances, failures } = await this.readAggregatedBalances(options);
20883
+ const portfolio = options?.chainId === void 0 && options?.asset === void 0;
20884
+ return this.readBalances(options, portfolio);
20885
+ }
20886
+ async readBalances(options, portfolio) {
20887
+ const { balances, failures } = await this.readAggregatedBalances(options, portfolio);
18725
20888
  if (Object.keys(balances.agentBalances).length === 0) {
18726
20889
  throw new OwneyError(
18727
20890
  "BALANCE_ALL_FAILED",
@@ -18732,21 +20895,27 @@ var OwneySDK = class {
18732
20895
  return balances;
18733
20896
  }
18734
20897
  /** Preserve failure objects for withdrawal recovery without changing public balance results. */
18735
- async readAggregatedBalances(options) {
20898
+ async readAggregatedBalances(options, portfolio = false) {
18736
20899
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
18737
20900
  const asset = options?.asset;
18738
- const readBalance = (agent) => this.readAgent(
18739
- agent,
20901
+ const readBalance = (read2) => !read2.offChain ? this.readAgent(
20902
+ read2.agent,
18740
20903
  "balances",
18741
- () => asset ? agent.getBalances(state, chainId, asset) : agent.getBalances(state, chainId),
20904
+ () => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
18742
20905
  asset ? { asset } : null
20906
+ ) : this.readAgent(
20907
+ read2.agent,
20908
+ "balances",
20909
+ () => read2.agent.getBalances(read2.state, read2.chainId),
20910
+ { chainId: read2.chainId }
18743
20911
  );
18744
20912
  let totalBalance = 0;
18745
20913
  const results = {};
18746
- const entries = [...this.getActiveAgents().entries()];
20914
+ const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
18747
20915
  const balanceResults = await Promise.allSettled(
18748
- entries.map(async ([id, agent]) => {
18749
- const b = await readBalance(agent);
20916
+ entries.map(async ([id, read2]) => {
20917
+ const { agent } = read2;
20918
+ const b = await readBalance(read2);
18750
20919
  return [
18751
20920
  id,
18752
20921
  {
@@ -18797,16 +20966,21 @@ var OwneySDK = class {
18797
20966
  const chainId = this.requireChainId();
18798
20967
  if (agentId) {
18799
20968
  const agent = this.getAgent(agentId);
20969
+ const readState = this.readStateFor(agentId, state);
18800
20970
  return this.readAgent(
18801
20971
  agent,
18802
20972
  "earnings",
18803
- () => agent.getEarnings(state, chainId)
20973
+ () => agent.getEarnings(readState, chainId)
18804
20974
  );
18805
20975
  }
18806
- const entries = [...this.getActiveAgents().entries()];
18807
20976
  return this.aggregateEarnings(
18808
- entries,
18809
- (agent) => this.readAgent(agent, "earnings", () => agent.getEarnings(state, chainId))
20977
+ this.portfolioReads(state, chainId),
20978
+ (read2) => this.readAgent(
20979
+ read2.agent,
20980
+ "earnings",
20981
+ () => read2.agent.getEarnings(read2.state, read2.chainId),
20982
+ read2.offChain ? { chainId: read2.chainId } : null
20983
+ )
18810
20984
  );
18811
20985
  }
18812
20986
  /**
@@ -18816,23 +20990,24 @@ var OwneySDK = class {
18816
20990
  async refreshEarnings(agentId) {
18817
20991
  const state = this.requireState();
18818
20992
  const chainId = this.requireChainId();
18819
- const refreshAgent = (agent) => this.readAgent(
20993
+ const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
18820
20994
  agent,
18821
20995
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
18822
- () => agent.refreshEarnings?.(state, chainId) ?? agent.getEarnings(state, chainId)
20996
+ () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
20997
+ offChain ? { chainId: readChain } : null
18823
20998
  );
18824
- if (agentId) return refreshAgent(this.getAgent(agentId));
18825
- return this.aggregateEarnings([...this.getActiveAgents().entries()], refreshAgent);
20999
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
21000
+ return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
18826
21001
  }
18827
21002
  async aggregateEarnings(entries, read2) {
18828
- const settled = await Promise.allSettled(entries.map(([, agent]) => read2(agent)));
21003
+ const settled = await Promise.allSettled(entries.map(read2));
18829
21004
  const agentEarnings = {};
18830
21005
  const agentErrors = {};
18831
21006
  const agentRetryAt = {};
18832
21007
  const failures = [];
18833
21008
  let totalEarnings = 0;
18834
21009
  for (let i = 0; i < settled.length; i++) {
18835
- const [id] = entries[i];
21010
+ const { id } = entries[i];
18836
21011
  const result = settled[i];
18837
21012
  if (result.status === "fulfilled") {
18838
21013
  agentEarnings[id] = result.value;
@@ -18879,9 +21054,46 @@ var OwneySDK = class {
18879
21054
  async getDailyEarnings({
18880
21055
  agentId,
18881
21056
  days,
18882
- tokenSymbol
21057
+ tokenSymbol,
21058
+ chainIds
18883
21059
  }) {
18884
21060
  const state = this.requireState();
21061
+ if (chainIds?.length) {
21062
+ const agents = (agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()]).filter((agent) => agent.getDailyEarnings);
21063
+ const legs = [];
21064
+ for (const agent of agents) {
21065
+ for (const legChainId of chainIds) {
21066
+ if (agentRunsOn(agent, legChainId))
21067
+ legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
21068
+ }
21069
+ }
21070
+ if (!agentId) {
21071
+ for (const extra of this.offChainPortfolioAgents(state)) {
21072
+ if (!extra.agent.getDailyEarnings) continue;
21073
+ for (const legChainId of chainIds) {
21074
+ if (extra.chainIds.includes(legChainId))
21075
+ legs.push({ agent: extra.agent, legChainId, legState: extra.state });
21076
+ }
21077
+ }
21078
+ }
21079
+ const settled2 = await Promise.allSettled(
21080
+ legs.map(
21081
+ ({ agent, legChainId, legState }) => this.readAgent(
21082
+ agent,
21083
+ "dailyEarnings",
21084
+ () => agent.getDailyEarnings(legState, legChainId, days, tokenSymbol),
21085
+ // The leg's chain must be in the key: the read key otherwise names
21086
+ // only the CONNECTION chain, so every leg shared the first leg's
21087
+ // request and the sum counted that chain once per leg. (ROUT-561)
21088
+ { days, tokenSymbol, chainId: legChainId }
21089
+ )
21090
+ )
21091
+ );
21092
+ const series2 = settled2.flatMap((result) => result.status === "fulfilled" ? [result.value] : []);
21093
+ const failure = settled2.find((result) => result.status === "rejected");
21094
+ if (!series2.length && failure?.status === "rejected") throw failure.reason;
21095
+ return mergeDailyEarnings(series2);
21096
+ }
18885
21097
  const chainId = this.requireChainId();
18886
21098
  if (agentId) {
18887
21099
  const agent = this.getAgent(agentId);
@@ -18892,22 +21104,21 @@ var OwneySDK = class {
18892
21104
  assets: []
18893
21105
  };
18894
21106
  }
21107
+ const readState = this.readStateFor(agentId, state);
18895
21108
  return this.readAgent(
18896
21109
  agent,
18897
21110
  "dailyEarnings",
18898
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21111
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
18899
21112
  { days, tokenSymbol }
18900
21113
  );
18901
21114
  }
18902
- const entries = [...this.getActiveAgents().entries()].filter(
18903
- ([, agent]) => agent.getDailyEarnings
18904
- );
21115
+ const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
18905
21116
  const settled = await Promise.allSettled(
18906
21117
  entries.map(
18907
- ([, agent]) => this.readAgent(
21118
+ ({ agent, state: readState }) => this.readAgent(
18908
21119
  agent,
18909
21120
  "dailyEarnings",
18910
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21121
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
18911
21122
  { days, tokenSymbol }
18912
21123
  )
18913
21124
  )
@@ -18923,49 +21134,136 @@ var OwneySDK = class {
18923
21134
  assets: aggregateDailyEarnings(series, tokenSymbol)
18924
21135
  };
18925
21136
  }
21137
+ /**
21138
+ * The deposit-time pool catalogue (ROUT-569): every protocol with its
21139
+ * selectable pools (name, APY, TVL, link) for `asset` under `strategy`.
21140
+ * Defaults to the zyfai agent, the only one with pool customization today.
21141
+ */
21142
+ async getPoolCatalog(params) {
21143
+ await this.ensureAgentsInitialized();
21144
+ const agent = this.getAgent(params.agentId ?? "zyfai");
21145
+ if (!agent.getPoolCatalog) {
21146
+ throw new OwneyError(
21147
+ "POOL_CATALOG_UNSUPPORTED",
21148
+ `Agent ${agent.id} does not support pool customization`
21149
+ );
21150
+ }
21151
+ return agent.getPoolCatalog({
21152
+ asset: params.asset,
21153
+ strategy: params.strategy
21154
+ });
21155
+ }
21156
+ /**
21157
+ * Apply a user's deposit-time pool selection to their account (ROUT-569).
21158
+ * The request carries explicit pool choices plus the resulting strategy for
21159
+ * each asset reviewed in the deposit flow.
21160
+ */
21161
+ async setPoolSelection(params) {
21162
+ await this.ensureAgentsInitialized();
21163
+ const agent = this.getAgent(params.agentId ?? "zyfai");
21164
+ if (!agent.setPoolSelection) {
21165
+ throw new OwneyError(
21166
+ "POOL_SELECTION_UNSUPPORTED",
21167
+ `Agent ${agent.id} does not support pool customization`
21168
+ );
21169
+ }
21170
+ await agent.setPoolSelection(params.selection, this.state ?? void 0);
21171
+ }
21172
+ /**
21173
+ * The pool selection saved on the user's account (ROUT-650), so the Pools
21174
+ * step can show what applies now rather than the defaults. `pairs` and
21175
+ * `assets` say which protocol/chain lists and strategies to read.
21176
+ */
21177
+ async getPoolSelection(params) {
21178
+ const state = this.requireState();
21179
+ const chainId = this.requireChainId();
21180
+ await this.ensureAgentsInitialized();
21181
+ const agent = this.getAgent(params.agentId ?? "zyfai");
21182
+ if (!agent.getPoolSelection) {
21183
+ throw new OwneyError(
21184
+ "POOL_SELECTION_UNSUPPORTED",
21185
+ `Agent ${agent.id} does not support pool customization`
21186
+ );
21187
+ }
21188
+ return agent.getPoolSelection(state, chainId, {
21189
+ pairs: params.pairs,
21190
+ assets: params.assets
21191
+ });
21192
+ }
21193
+ /**
21194
+ * The agents a person can customize pools for: registered, enabled, and
21195
+ * able to list a pool catalogue. Waits for agent initialization, so an agent
21196
+ * the organization disabled is known and left out.
21197
+ */
21198
+ async getPoolCustomizationAgents() {
21199
+ await this.ensureAgentsInitialized();
21200
+ return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
21201
+ }
18926
21202
  async getAccountApy({
18927
21203
  agentId,
18928
21204
  days,
18929
- tokenSymbol
21205
+ tokenSymbol,
21206
+ chainId: scope
18930
21207
  }) {
18931
21208
  const state = this.requireState();
18932
21209
  const chainId = this.requireChainId();
21210
+ const scopeChainId = scope === "all" ? null : scope;
18933
21211
  if (agentId) {
18934
21212
  const agent = this.getAgent(agentId);
18935
- return this.readAgent(
21213
+ const readState = this.readStateFor(agentId, state);
21214
+ const accountApy = await this.readAgent(
18936
21215
  agent,
18937
21216
  "accountApy",
18938
- () => agent.getAccountApy(state, chainId, days, tokenSymbol),
18939
- { days, tokenSymbol }
21217
+ () => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
21218
+ { days, tokenSymbol, scopeChainId }
21219
+ );
21220
+ return this.enrichApyHistory(
21221
+ accountApy,
21222
+ agentId,
21223
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21224
+ tokenSymbol
18940
21225
  );
18941
21226
  }
18942
- const activeAgents = this.getActiveAgents();
18943
- const entries = [...activeAgents.entries()];
18944
- const [apyResults, balanceResults] = await Promise.all([
18945
- Promise.all(
18946
- entries.map(async ([id, agent]) => {
18947
- const apy = await this.readAgent(
21227
+ const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
21228
+ const reads = await Promise.all(
21229
+ entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
21230
+ const pair = Promise.all([
21231
+ this.readAgent(
18948
21232
  agent,
18949
21233
  "accountApy",
18950
- () => agent.getAccountApy(state, chainId, days, tokenSymbol),
18951
- { days, tokenSymbol }
18952
- );
18953
- return [id, apy];
18954
- })
18955
- ),
18956
- Promise.all(
18957
- entries.map(async ([id, agent]) => {
18958
- const b = await this.readAgent(agent, "balances", () => agent.getBalances(state, chainId));
18959
- return [
18960
- id,
18961
- balanceForApyScope(b, chainId, tokenSymbol)
18962
- ];
18963
- })
18964
- )
18965
- ]);
21234
+ () => agent.getAccountApy(
21235
+ readState,
21236
+ readChain,
21237
+ days,
21238
+ tokenSymbol,
21239
+ scopeChainId
21240
+ ),
21241
+ offChain ? { days, tokenSymbol, scopeChainId, chainId: readChain } : { days, tokenSymbol, scopeChainId }
21242
+ ),
21243
+ this.readAgent(
21244
+ agent,
21245
+ "balances",
21246
+ () => agent.getBalances(readState, readChain),
21247
+ offChain ? { chainId: readChain } : null
21248
+ ).then((b) => balanceForApyScope(b, readChain, tokenSymbol))
21249
+ ]);
21250
+ if (!offChain) return [id, ...await pair];
21251
+ return pair.then(([apy, balance]) => [id, apy, balance], (error) => {
21252
+ console.error(`[owney-sdk] APY fetch failed for agent "${id}" on chain ${readChain}:`, error);
21253
+ return null;
21254
+ });
21255
+ })
21256
+ );
21257
+ const apyResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[1]]] : []);
21258
+ const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
18966
21259
  const results = {};
18967
21260
  for (const [id, apy] of apyResults) {
18968
- results[id] = apy;
21261
+ results[id] = await this.enrichApyHistory(
21262
+ apy,
21263
+ id,
21264
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21265
+ tokenSymbol
21266
+ );
18969
21267
  }
18970
21268
  const balances = {};
18971
21269
  for (const [id, bal] of balanceResults) {
@@ -18995,6 +21293,36 @@ var OwneySDK = class {
18995
21293
  history
18996
21294
  };
18997
21295
  }
21296
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
21297
+ const history = accountApy.history;
21298
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
21299
+ const incentives = await fetchApyIncentives(
21300
+ this.apiKey,
21301
+ {
21302
+ walletAddress: accountApy.walletAddress,
21303
+ agentId,
21304
+ chainId,
21305
+ asset: tokenSymbol,
21306
+ from: history[0].date,
21307
+ to: history[history.length - 1].date
21308
+ },
21309
+ this.routingApiBaseUrl
21310
+ );
21311
+ if (incentives.length === 0) return accountApy;
21312
+ const byDate = /* @__PURE__ */ new Map();
21313
+ for (const { date, ...incentive } of incentives) {
21314
+ const entries = byDate.get(date) ?? [];
21315
+ entries.push(incentive);
21316
+ byDate.set(date, entries);
21317
+ }
21318
+ return {
21319
+ ...accountApy,
21320
+ history: history.map((point) => {
21321
+ const pointIncentives = byDate.get(point.date);
21322
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
21323
+ })
21324
+ };
21325
+ }
18998
21326
  /**
18999
21327
  * Get transaction history for a specific agent, or all agents.
19000
21328
  *
@@ -19013,11 +21341,61 @@ var OwneySDK = class {
19013
21341
  * @returns {OwneyAgentHistory} `data` (up to `limit` entries), `hasMore`, `nextCursor`.
19014
21342
  */
19015
21343
  async getHistory(options) {
21344
+ const { agentId, filters, chainIds } = options ?? {};
21345
+ if (chainIds?.length) {
21346
+ const state2 = this.requireState();
21347
+ const agents = agentId ? [this.getAgent(agentId)] : [...this.getActiveAgents().values()];
21348
+ const cursorMap2 = filters?.cursor ? decodeFanoutCursor(filters.cursor) : void 0;
21349
+ const legs = [];
21350
+ for (const agent of agents) {
21351
+ for (const legChainId of chainIds) {
21352
+ if (agentRunsOn(agent, legChainId))
21353
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
21354
+ }
21355
+ }
21356
+ if (!agentId) {
21357
+ for (const extra of this.offChainPortfolioAgents(state2)) {
21358
+ for (const legChainId of chainIds) {
21359
+ if (extra.chainIds.includes(legChainId))
21360
+ legs.push({ agentId: extra.agent.id, chainId: legChainId, legState: extra.state });
21361
+ }
21362
+ }
21363
+ }
21364
+ const agentErrors2 = {};
21365
+ let firstFailure;
21366
+ const pages = await Promise.all(
21367
+ legs.map(async (leg) => {
21368
+ const legCursor = cursorMap2?.[fanoutKey(leg)];
21369
+ if (cursorMap2 && legCursor === void 0) {
21370
+ return { leg, page: null };
21371
+ }
21372
+ const legFilters = { ...filters, cursor: legCursor };
21373
+ const agent = this.getAgent(leg.agentId);
21374
+ try {
21375
+ const page = await this.readAgent(
21376
+ agent,
21377
+ "history",
21378
+ () => agent.getHistory(leg.legState, leg.chainId, legFilters),
21379
+ // Keyed per leg for the same reason as getDailyEarnings' fan-out.
21380
+ { ...legFilters, chainId: leg.chainId }
21381
+ );
21382
+ return { leg, page };
21383
+ } catch (error) {
21384
+ firstFailure ??= error;
21385
+ agentErrors2[leg.agentId] = error instanceof Error ? error.message : String(error);
21386
+ return { leg, page: null };
21387
+ }
21388
+ })
21389
+ );
21390
+ if (firstFailure !== void 0 && pages.every(({ page }) => page === null)) throw firstFailure;
21391
+ const merged2 = mergeHistoryPages(pages);
21392
+ return Object.keys(agentErrors2).length ? { ...merged2, agentErrors: agentErrors2 } : merged2;
21393
+ }
19016
21394
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19017
- const { agentId, filters } = options ?? {};
19018
21395
  if (agentId) {
19019
21396
  const agent = this.getAgent(agentId);
19020
- const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
21397
+ const readState = this.readStateFor(agentId, state);
21398
+ const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
19021
21399
  assertCurrent();
19022
21400
  return page;
19023
21401
  }
@@ -19031,10 +21409,11 @@ var OwneySDK = class {
19031
21409
  }
19032
21410
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
19033
21411
  try {
21412
+ const readState = this.readStateFor(agent.id, state);
19034
21413
  const page = await this.readAgent(
19035
21414
  agent,
19036
21415
  "history",
19037
- () => agent.getHistory(state, chainId, agentFilters),
21416
+ () => agent.getHistory(readState, chainId, agentFilters),
19038
21417
  agentFilters
19039
21418
  );
19040
21419
  return { agentId: agent.id, page };
@@ -19092,20 +21471,20 @@ var OwneySDK = class {
19092
21471
  const chainId = this.requireChainId();
19093
21472
  if (agentId) {
19094
21473
  const agent = this.getAgent(agentId);
21474
+ const readState = this.readStateFor(agentId, state);
19095
21475
  return this.readAgent(
19096
21476
  agent,
19097
21477
  "profile",
19098
- () => agent.getUserProfile(state, chainId)
21478
+ () => agent.getUserProfile(readState, chainId)
19099
21479
  );
19100
21480
  }
19101
21481
  const results = {};
19102
- const entries = [...this.getActiveAgents().entries()];
19103
21482
  const profileResults = await Promise.all(
19104
- entries.map(async ([id, agent]) => {
21483
+ this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
19105
21484
  const p = await this.readAgent(
19106
21485
  agent,
19107
21486
  "profile",
19108
- () => agent.getUserProfile(state, chainId)
21487
+ () => agent.getUserProfile(readState, chainId)
19109
21488
  );
19110
21489
  return [id, p];
19111
21490
  })
@@ -19315,10 +21694,11 @@ var OwneySDK = class {
19315
21694
  const entries = [...activeAgents.entries()];
19316
21695
  const balanceResults = await Promise.allSettled(
19317
21696
  entries.map(async ([id, agent]) => {
21697
+ const readState = this.readStateFor(id, state);
19318
21698
  const b = await this.readAgent(
19319
21699
  agent,
19320
21700
  "balances",
19321
- () => agent.getBalances(state, chainId)
21701
+ () => agent.getBalances(readState, chainId)
19322
21702
  );
19323
21703
  return [id, b.positions ?? []];
19324
21704
  })
@@ -19600,5 +21980,6 @@ export {
19600
21980
  saveWithdrawSwap,
19601
21981
  setOwneyDebug,
19602
21982
  subscribeWithdrawSwaps,
21983
+ switchWalletConnectChain,
19603
21984
  updateWithdrawSwap
19604
21985
  };