@owney/sdk 0.7.32-beta.5 → 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.cjs CHANGED
@@ -679,6 +679,7 @@ __export(index_exports, {
679
679
  saveWithdrawSwap: () => saveWithdrawSwap,
680
680
  setOwneyDebug: () => setOwneyDebug,
681
681
  subscribeWithdrawSwaps: () => subscribeWithdrawSwaps,
682
+ switchWalletConnectChain: () => switchWalletConnectChain,
682
683
  updateWithdrawSwap: () => updateWithdrawSwap
683
684
  });
684
685
  module.exports = __toCommonJS(index_exports);
@@ -1123,6 +1124,35 @@ function debugLog(scope, message, data) {
1123
1124
  init_errors();
1124
1125
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
1125
1126
  var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
1127
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
1128
+ const query2 = new URLSearchParams({
1129
+ walletAddress: input.walletAddress,
1130
+ agentId: input.agentId,
1131
+ chainId: String(input.chainId),
1132
+ asset: input.asset.toUpperCase(),
1133
+ from: input.from,
1134
+ to: input.to
1135
+ });
1136
+ try {
1137
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
1138
+ headers: {
1139
+ Accept: "application/json",
1140
+ "x-owney-api-key": apiKey
1141
+ }
1142
+ });
1143
+ if (!response.ok) return [];
1144
+ const body = await response.json();
1145
+ if (!body.success || !Array.isArray(body.data)) return [];
1146
+ return body.data.filter(
1147
+ (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)
1148
+ );
1149
+ } catch (error) {
1150
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
1151
+ error: error instanceof Error ? error.message : String(error)
1152
+ });
1153
+ return [];
1154
+ }
1155
+ }
1126
1156
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
1127
1157
  const url = `${baseUrl}/api/v1/agent/org-config`;
1128
1158
  try {
@@ -1653,7 +1683,7 @@ var SnapshotHistory = class {
1653
1683
  };
1654
1684
 
1655
1685
  // src/lib/funding-ledger.ts
1656
- var SDK_VERSION = "0.7.32-beta.5";
1686
+ var SDK_VERSION = "0.7.32-beta.6";
1657
1687
  var SCOPE2 = "funding-ledger";
1658
1688
  var REQUEST_TIMEOUT_MS2 = 5e3;
1659
1689
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -2968,7 +2998,7 @@ var CHAIN_NAMES = {
2968
2998
  function chainName(chainId) {
2969
2999
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2970
3000
  }
2971
- var SETTLE_TIMEOUT_MS = 8e3;
3001
+ var SETTLE_TIMEOUT_MS = 15e3;
2972
3002
  var POLL_INTERVAL_MS = 200;
2973
3003
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2974
3004
  async function readChainId(pub) {
@@ -5114,11 +5144,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
5114
5144
  if (typeof window === "undefined") return;
5115
5145
  const internals = sdk;
5116
5146
  const original = internals.authenticateUser.bind(internals);
5117
- internals.authenticateUser = async () => {
5147
+ let inFlight2 = null;
5148
+ const authenticate = async () => {
5118
5149
  if (internals.authenticatedUserId !== null) return;
5119
5150
  const address = internals.walletClient?.account?.address;
5120
- const chainId = internals.currentChainId;
5121
- if (address && chainId) {
5151
+ const chainId = internals.currentChainId ?? 0;
5152
+ if (address) {
5122
5153
  const cached = readSession(address, chainId);
5123
5154
  if (cached) {
5124
5155
  internals.httpClient.setAuthToken(cached.token);
@@ -5130,9 +5161,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
5130
5161
  }
5131
5162
  await original();
5132
5163
  const newAddress = internals.walletClient?.account?.address;
5133
- const newChainId = internals.currentChainId;
5164
+ const newChainId = internals.currentChainId ?? 0;
5134
5165
  const newToken = internals.httpClient.authToken;
5135
- if (newAddress && newChainId && newToken) {
5166
+ if (newAddress && newToken) {
5136
5167
  writeSession(newAddress, newChainId, {
5137
5168
  token: newToken,
5138
5169
  userId: internals.authenticatedUserId,
@@ -5141,6 +5172,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
5141
5172
  });
5142
5173
  }
5143
5174
  };
5175
+ internals.authenticateUser = () => {
5176
+ const address = internals.walletClient?.account?.address?.toLowerCase();
5177
+ if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
5178
+ const promise = authenticate().finally(() => {
5179
+ if (inFlight2?.promise === promise) inFlight2 = null;
5180
+ });
5181
+ inFlight2 = { address, promise };
5182
+ return promise;
5183
+ };
5144
5184
  }
5145
5185
  // --- Private helpers ---
5146
5186
  getAddress() {
@@ -5373,12 +5413,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
5373
5413
  }
5374
5414
  // --- IAgent: Account lifecycle ---
5375
5415
  async activateAgent(state, chainId) {
5416
+ const startedAt = Date.now();
5376
5417
  try {
5377
5418
  debugLog("zyfai:activation", "starting", {
5378
5419
  walletAddress: state.walletAddress,
5379
5420
  chainId
5380
5421
  });
5381
5422
  await this.connectAuth(state, chainId);
5423
+ debugLog("zyfai:activation", "signed in", {
5424
+ ms: Date.now() - startedAt
5425
+ });
5382
5426
  const validChainId = isValidChainId(chainId);
5383
5427
  await Promise.all([
5384
5428
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -5389,7 +5433,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5389
5433
  // validator, so pool-wallet users see no prompt. Non-fatal.
5390
5434
  this.ensureSessionKeyIfDeployed(validChainId)
5391
5435
  ]);
5392
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
5436
+ debugLog("zyfai:activation", "completed", {
5437
+ chainId: validChainId,
5438
+ ms: Date.now() - startedAt
5439
+ });
5393
5440
  } catch (error) {
5394
5441
  throw error;
5395
5442
  }
@@ -7085,6 +7132,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7085
7132
  const generation = this.earningsGeneration;
7086
7133
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
7087
7134
  const raw2 = await this.sdk.getPortfolio(this.getAddress());
7135
+ debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
7088
7136
  const balance = mapBalances(raw2, validChainId, smartWallet);
7089
7137
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
7090
7138
  for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
@@ -7488,6 +7536,27 @@ var import_viem17 = require("viem");
7488
7536
  var import_chains4 = require("viem/chains");
7489
7537
  init_errors();
7490
7538
 
7539
+ // src/lib/wallet-rejection.ts
7540
+ var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
7541
+ function isWalletRejection(error) {
7542
+ let current = error;
7543
+ const seen = /* @__PURE__ */ new Set();
7544
+ while (current && typeof current === "object" && !seen.has(current)) {
7545
+ seen.add(current);
7546
+ const candidate = current;
7547
+ if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
7548
+ const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
7549
+ if (REJECTION_MESSAGE.test(message)) return true;
7550
+ const details = candidate.details;
7551
+ if (details && typeof details === "object") {
7552
+ const cause = details.cause;
7553
+ if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
7554
+ }
7555
+ current = candidate.cause;
7556
+ }
7557
+ return false;
7558
+ }
7559
+
7491
7560
  // src/agents/yieldseeker/yieldseeker.auth.ts
7492
7561
  var import_siwe = require("siwe");
7493
7562
  var import_viem11 = require("viem");
@@ -8530,11 +8599,13 @@ function mapYieldseekerProfile(address, contexts) {
8530
8599
  protocols: [...protocols]
8531
8600
  };
8532
8601
  }
8533
- function mapYieldseekerAgentApy(stats) {
8602
+ function mapYieldseekerAgentApy(stats, days) {
8534
8603
  const perAsset = {};
8535
8604
  const all = [];
8536
8605
  for (const entry of stats) {
8537
- const expected = percent(entry.stats.expectedApy7d);
8606
+ const expected = percent(
8607
+ days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
8608
+ );
8538
8609
  if (!Number.isFinite(expected)) continue;
8539
8610
  perAsset[entry.asset] = expected;
8540
8611
  all.push(expected);
@@ -8705,6 +8776,15 @@ function sponsorError(message, safeToFallback, details = {}) {
8705
8776
  "yieldseeker"
8706
8777
  );
8707
8778
  }
8779
+ function cannotSignRawHash(error) {
8780
+ for (let current = error, depth = 0; current && depth < 5; depth++) {
8781
+ const code = current.code;
8782
+ if (code === -32602 || code === -32601 || code === 4200) return true;
8783
+ if (code === 4001) return false;
8784
+ current = current.cause;
8785
+ }
8786
+ return false;
8787
+ }
8708
8788
  function assertIntentFresh(expiresAt) {
8709
8789
  if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
8710
8790
  throw sponsorError(
@@ -9066,7 +9146,18 @@ async function submitEoa(input) {
9066
9146
  transport: (0, import_viem15.custom)(input.state.provider)
9067
9147
  });
9068
9148
  input.assertCurrent?.();
9069
- const signature = await wallet.signMessage({ message: { raw: userOpHash } });
9149
+ let signature;
9150
+ try {
9151
+ signature = await wallet.signMessage({ message: { raw: userOpHash } });
9152
+ } catch (error) {
9153
+ if (cannotSignRawHash(error))
9154
+ throw sponsorError(
9155
+ "This wallet cannot sign the gas-free withdrawal.",
9156
+ true,
9157
+ { failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
9158
+ );
9159
+ throw error;
9160
+ }
9070
9161
  operation = { ...operation, signature };
9071
9162
  await assertOwnerSession(input.state, input.owner);
9072
9163
  assertIntentFresh(input.expiresAt);
@@ -9338,11 +9429,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
9338
9429
  var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
9339
9430
  var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
9340
9431
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
9432
+ var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
9433
+ var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
9434
+ var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
9435
+ var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
9341
9436
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
9342
9437
  var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
9343
9438
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
9344
9439
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
9345
9440
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
9441
+ function apyAsPercent(fraction) {
9442
+ if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
9443
+ return Number((fraction * 100).toPrecision(12));
9444
+ }
9445
+ function isActiveMemory(memory2) {
9446
+ return !!memory2 && memory2.isActive !== false && memory2.isDeleted !== true;
9447
+ }
9448
+ function vaultOptionsKey(asset, includeUnavailable) {
9449
+ return `${asset}:${includeUnavailable ? "all" : "usable"}`;
9450
+ }
9451
+ function isManagedVaultList(memory2) {
9452
+ return memory2.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
9453
+ }
9454
+ function isLegacyPoolSelectionMemory(memory2) {
9455
+ if (isManagedVaultList(memory2) || typeof memory2.content !== "string") return false;
9456
+ const content = memory2.content.trim();
9457
+ return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
9458
+ }
9459
+ function uniqueAddresses(addresses) {
9460
+ const seen = /* @__PURE__ */ new Set();
9461
+ return addresses.filter((address) => {
9462
+ const key2 = address.toLowerCase();
9463
+ if (seen.has(key2)) return false;
9464
+ seen.add(key2);
9465
+ return true;
9466
+ });
9467
+ }
9468
+ function sameVaults(actual, expected) {
9469
+ const want = new Set(expected.map((address) => address.toLowerCase()));
9470
+ const got = new Set(actual.map((address) => address.toLowerCase()));
9471
+ return got.size === want.size && [...want].every((address) => got.has(address));
9472
+ }
9346
9473
  function isYieldseekerWalletCodeMissing(error) {
9347
9474
  for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
9348
9475
  const { name, message } = current;
@@ -9352,6 +9479,8 @@ function isYieldseekerWalletCodeMissing(error) {
9352
9479
  return false;
9353
9480
  }
9354
9481
  var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
9482
+ var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
9483
+ var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
9355
9484
  var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
9356
9485
  var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
9357
9486
  var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
@@ -9371,6 +9500,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
9371
9500
  var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
9372
9501
  var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
9373
9502
  var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
9503
+ var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
9374
9504
  var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
9375
9505
  var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
9376
9506
  function generateYieldseekerUsername() {
@@ -9463,9 +9593,31 @@ var YieldseekerAgent = class {
9463
9593
  walletContexts = /* @__PURE__ */ new Map();
9464
9594
  agentAccountReads = /* @__PURE__ */ new Map();
9465
9595
  reportedAccounts = /* @__PURE__ */ new Set();
9466
- // Slots whose verified agent is missing even from a re-read list, until the
9467
- // list cache window ends. Stops a re-read on every portfolio poll.
9596
+ // Slots whose verified agent is missing even from a re-read list (and could
9597
+ // not be reopened), with the error the lookup failed with, until the list
9598
+ // cache window ends. Stops a re-read and a reactivate on every portfolio poll.
9468
9599
  missingSlots = /* @__PURE__ */ new Map();
9600
+ // A remembered rate limit rethrown with the time left on its marker
9601
+ // (throwIfSlotMissing), mapped to the remembered error it copies, so
9602
+ // isMarkedSlotFailure still recognises it.
9603
+ rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
9604
+ // Slots whose verified agent Yieldseeker will never reopen (a reactivate
9605
+ // answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
9606
+ // slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
9607
+ // it is kept for the session, like unavailableSlots: reads and deposits get
9608
+ // it with no request until disconnect, or until a lookup selects an agent
9609
+ // for the slot.
9610
+ closedSlots = /* @__PURE__ */ new Map();
9611
+ // In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
9612
+ // shared by concurrent lookups of one slot.
9613
+ pendingReopens = /* @__PURE__ */ new Map();
9614
+ // Slots Yieldseeker will not give an agent this session (a reactivate answered
9615
+ // an active-agent limit), keyed by slotKey, with the provider's limit code.
9616
+ // Never expires: it answers without a request until disconnect.
9617
+ unavailableSlots = /* @__PURE__ */ new Map();
9618
+ // In-flight reactivates keyed by slotKey + agentId, shared by every caller
9619
+ // (a read-time reopen, deposits): one request however many ask.
9620
+ pendingReactivates = /* @__PURE__ */ new Map();
9469
9621
  // In-flight cache-bypassing list reads, shared by concurrent callers.
9470
9622
  freshListReads = /* @__PURE__ */ new Map();
9471
9623
  // Every contextKey computed this session; asset-only calls fall back to them.
@@ -9518,6 +9670,7 @@ var YieldseekerAgent = class {
9518
9670
  ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
9519
9671
  /** slotKey -> the last successful ledger rows and when they arrived. */
9520
9672
  lastLedgerRows = /* @__PURE__ */ new Map();
9673
+ /** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
9521
9674
  vaultOptions = /* @__PURE__ */ new Map();
9522
9675
  pendingVaultOptions = /* @__PURE__ */ new Map();
9523
9676
  assetApyStats = /* @__PURE__ */ new Map();
@@ -9574,6 +9727,121 @@ var YieldseekerAgent = class {
9574
9727
  this.pendingWalletStatus.set(key2, pending2);
9575
9728
  return { ...await pending2 };
9576
9729
  }
9730
+ /**
9731
+ * Deposits go only to an agent Yieldseeker still has open. The session caches
9732
+ * the selected agent, so a tab left open can hold one Yieldseeker has since
9733
+ * closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
9734
+ * bypassing the cached wallet contexts, and:
9735
+ * - open, same wallet address: returns the context to deposit with;
9736
+ * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9737
+ * continues only when it is now open with the same address. Only the
9738
+ * verified record's agent is reopened: any other closed agent (a
9739
+ * superseded-wallet match, or a named agent with no verified record, also
9740
+ * when the accounts could not be read) refuses without a request;
9741
+ * - anything else refuses with nothing sent, before any progress event,
9742
+ * signature or callback. Every refusal carries `notSubmitted` and
9743
+ * `safeToFallback: false`, so no paid fallback runs.
9744
+ * A slot recorded unavailable (the active-agent limit) refuses at once with
9745
+ * no request. The reactivate goes through reactivateSlot, which shares one
9746
+ * request per slot and remembers a failure for the list-cache window, so
9747
+ * repeated deposits do not repeat it. A failed wallet read fails closed
9748
+ * (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
9749
+ * gate. A reactivate that fails keeps its error code
9750
+ * (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
9751
+ * failure). At the limit the slot is also recorded unavailable for the
9752
+ * session (see isSlotUnavailable). Session changes keep their own
9753
+ * NOT_CONNECTED error.
9754
+ */
9755
+ async assertAgentOpen(state, chainId, asset, context) {
9756
+ const generation = this.readGeneration;
9757
+ const agentId = context.agent.agentId;
9758
+ const agentWallet = context.wallet.walletAddress;
9759
+ const refusal = { notSubmitted: true, safeToFallback: false };
9760
+ const slot = this.slotKey(state, chainId, asset);
9761
+ const unavailable = this.unavailableSlots.get(slot);
9762
+ if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
9763
+ const readWallet = async () => {
9764
+ let fresh2;
9765
+ try {
9766
+ const answer = await this.walletRequest(
9767
+ state,
9768
+ chainId,
9769
+ this.agentPath(context, "wallet")
9770
+ );
9771
+ if (!answer?.agentWallet || !(0, import_viem17.isAddress)(answer.agentWallet.walletAddress)) {
9772
+ throw this.invalidResponse("agent wallet");
9773
+ }
9774
+ fresh2 = answer.agentWallet;
9775
+ } catch (error) {
9776
+ this.assertSession(generation, chainId, asset);
9777
+ throw new OwneyError(
9778
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9779
+ "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
9780
+ {
9781
+ ...refusal,
9782
+ reason: "UNAVAILABLE",
9783
+ agentWallet,
9784
+ asset,
9785
+ cause: error instanceof Error ? error.message : String(error)
9786
+ },
9787
+ this.id
9788
+ );
9789
+ }
9790
+ this.assertSession(generation, chainId, asset);
9791
+ return fresh2;
9792
+ };
9793
+ let fresh = await readWallet();
9794
+ let reopened = false;
9795
+ if (fresh.deactivatedDate) {
9796
+ this.forgetAgentWallet(agentId);
9797
+ const accounts = await this.agentAccounts(state, chainId);
9798
+ this.assertSession(generation, chainId, asset);
9799
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
9800
+ if (!verified || verified.providerAgentId !== agentId) {
9801
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
9802
+ }
9803
+ let result;
9804
+ try {
9805
+ result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
9806
+ } catch (error) {
9807
+ this.assertSession(generation, chainId, asset);
9808
+ const failure = error instanceof OwneyError ? error : this.mapApiError(error);
9809
+ if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
9810
+ const { providerCode, reason } = failure.details ?? {};
9811
+ throw this.agentClosed(
9812
+ chainId,
9813
+ asset,
9814
+ agentId,
9815
+ typeof providerCode === "string" ? providerCode : void 0,
9816
+ { ...refusal, ...typeof reason === "string" ? { reason } : {} }
9817
+ );
9818
+ }
9819
+ throw new OwneyError(
9820
+ failure.code,
9821
+ `Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
9822
+ { ...failure.details, ...refusal, cause: failure.message },
9823
+ failure.agentId
9824
+ );
9825
+ }
9826
+ this.assertSession(generation, chainId, asset);
9827
+ if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
9828
+ this.forgetAgentWallet(agentId);
9829
+ fresh = await readWallet();
9830
+ if (fresh.deactivatedDate) {
9831
+ this.rememberMissingSlot(
9832
+ slot,
9833
+ generation,
9834
+ this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
9835
+ );
9836
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
9837
+ }
9838
+ reopened = true;
9839
+ }
9840
+ if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
9841
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
9842
+ }
9843
+ return reopened ? { ...context, wallet: fresh } : context;
9844
+ }
9577
9845
  /**
9578
9846
  * Deposits go only to a wallet whose identity is verified on chain (factory
9579
9847
  * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
@@ -9883,6 +10151,10 @@ var YieldseekerAgent = class {
9883
10151
  this.pendingSlotInvalidations.clear();
9884
10152
  this.knownContextKeys.clear();
9885
10153
  this.missingSlots.clear();
10154
+ this.closedSlots.clear();
10155
+ this.pendingReopens.clear();
10156
+ this.pendingReactivates.clear();
10157
+ this.unavailableSlots.clear();
9886
10158
  this.freshListReads.clear();
9887
10159
  this.balanceVaults.clear();
9888
10160
  this.pendingAgents.clear();
@@ -9910,11 +10182,43 @@ var YieldseekerAgent = class {
9910
10182
  this.planHistoryKeys.clear();
9911
10183
  this.lastLedgerRows.clear();
9912
10184
  }
10185
+ /**
10186
+ * Ready every asset's agent, `asset` first: a missing one is created and a
10187
+ * closed one reopened (2026-11-06). A slot Yieldseeker will never let the
10188
+ * user have (the agent limit, closed for good, missing with no way to
10189
+ * reopen) is rethrown with `details.permanent`, which refuses the connect.
10190
+ * A temporary failure (an API error or timeout) on another asset does not:
10191
+ * that slot answers again where it is needed. On the selected asset every
10192
+ * failure is thrown as before, without readying the rest, so a failed
10193
+ * sign-in never opens a second prompt.
10194
+ */
9913
10195
  async activateAgent(state, chainId, asset) {
9914
10196
  this.assertChain(chainId);
9915
10197
  const targetAsset = asset ?? "USDC";
9916
10198
  this.assertAsset(targetAsset);
9917
- await this.ensureAgent(state, chainId, targetAsset);
10199
+ const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
10200
+ for (const each of [targetAsset, ...others]) {
10201
+ try {
10202
+ await this.ensureAgent(state, chainId, each);
10203
+ } catch (error) {
10204
+ if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
10205
+ const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
10206
+ if (each === targetAsset || !temporary) throw error;
10207
+ debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
10208
+ code: error.code,
10209
+ statusCode: error.details?.statusCode
10210
+ });
10211
+ }
10212
+ }
10213
+ }
10214
+ /** The same failure, marked as one that will not go away this session. */
10215
+ permanentFailure(error) {
10216
+ const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
10217
+ return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
10218
+ }
10219
+ isSlotUnavailable(state, chainId, asset) {
10220
+ if (asset !== "USDC" && asset !== "WETH") return false;
10221
+ return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
9918
10222
  }
9919
10223
  async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
9920
10224
  this.assertChain(chainId);
@@ -9927,7 +10231,20 @@ var YieldseekerAgent = class {
9927
10231
  this.id
9928
10232
  );
9929
10233
  }
9930
- const context = await this.ensureAgent(state, chainId, asset);
10234
+ const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
10235
+ if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
10236
+ const { agentId, providerCode, reason } = error.details ?? {};
10237
+ throw this.agentClosed(
10238
+ chainId,
10239
+ asset,
10240
+ typeof agentId === "string" ? agentId : "",
10241
+ typeof providerCode === "string" ? providerCode : void 0,
10242
+ { notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
10243
+ );
10244
+ }
10245
+ throw error;
10246
+ });
10247
+ const context = await this.assertAgentOpen(state, chainId, asset, selected);
9931
10248
  await this.assertDepositWalletVerified(state, chainId, asset, context);
9932
10249
  const generation = this.readGeneration;
9933
10250
  const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
@@ -10117,15 +10434,14 @@ var YieldseekerAgent = class {
10117
10434
  if (timer) clearTimeout(timer);
10118
10435
  }
10119
10436
  };
10120
- const feeRateRead = amount === void 0 ? Promise.resolve(0) : boundedVerification(
10121
- (() => {
10122
- try {
10123
- return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
10124
- } catch (error) {
10125
- return Promise.reject(error);
10126
- }
10127
- })().catch(() => void 0)
10128
- );
10437
+ const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
10438
+ try {
10439
+ return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
10440
+ } catch (error) {
10441
+ return Promise.reject(error);
10442
+ }
10443
+ })().catch(() => void 0);
10444
+ const feeRateRead = boundedVerification(feeRateAnswer);
10129
10445
  const positionsRead = this.readWithdrawalPositions(state, chainId, context);
10130
10446
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
10131
10447
  const agentWallet = (0, import_viem17.getAddress)(context.wallet.walletAddress);
@@ -10435,9 +10751,10 @@ var YieldseekerAgent = class {
10435
10751
  }
10436
10752
  const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10437
10753
  const availableForOwner = ownerFunds.available;
10438
- const feeRate = feeRateBps ?? 0;
10439
- const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
10440
10754
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10755
+ const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
10756
+ this.assertSession(generation, chainId, asset);
10757
+ const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
10441
10758
  if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
10442
10759
  this.invalidateFundingRead(state, chainId, asset);
10443
10760
  if (amount === void 0 && positionsStatus !== "empty")
@@ -10691,7 +11008,7 @@ var YieldseekerAgent = class {
10691
11008
  positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
10692
11009
  const needsInventory = !proof.inventoryComplete;
10693
11010
  if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
10694
- const catalog = await this.loadVaultOptions(asset).catch(() => []);
11011
+ const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
10695
11012
  const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && (0, import_viem17.isAddress)(o.address));
10696
11013
  if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
10697
11014
  for (const option of eligible) {
@@ -10767,7 +11084,8 @@ var YieldseekerAgent = class {
10767
11084
  const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
10768
11085
  const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
10769
11086
  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()));
10770
- for (const option of this.vaultOptions.get(context.asset)?.value ?? []) {
11087
+ const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
11088
+ for (const option of cachedOptions?.value ?? []) {
10771
11089
  if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !(0, import_viem17.isAddress)(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
10772
11090
  hints.set(option.address.toLowerCase(), {
10773
11091
  vaultOption: option,
@@ -10980,7 +11298,7 @@ var YieldseekerAgent = class {
10980
11298
  assertReadCurrent();
10981
11299
  return proof(true);
10982
11300
  }
10983
- const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
11301
+ const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
10984
11302
  assertReadCurrent();
10985
11303
  const eligible = /* @__PURE__ */ new Map();
10986
11304
  for (const option of catalog ?? []) {
@@ -11123,8 +11441,37 @@ var YieldseekerAgent = class {
11123
11441
  }
11124
11442
  return false;
11125
11443
  }
11444
+ /**
11445
+ * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
11446
+ * it now instead of on its next 30-minute check. Yieldseeker decides whether
11447
+ * anything moves (the funding minimum, a deployed agent, no manual
11448
+ * withdrawal in the last hour). Uses the agent this session already knows
11449
+ * for the asset and the saved sign-in only: never prompts, never retries,
11450
+ * never throws.
11451
+ */
11452
+ async depositConfirmed(state, chainId, evidence) {
11453
+ try {
11454
+ const asset = String(evidence.token).toUpperCase();
11455
+ if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
11456
+ return { notified: false, reason: "UNSUPPORTED" };
11457
+ const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11458
+ if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
11459
+ return { notified: false, reason: "NO_AGENT" };
11460
+ if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11461
+ await this.walletRequest(
11462
+ state,
11463
+ chainId,
11464
+ this.agentPath(context, "deposit-made"),
11465
+ { method: "POST", body: {}, promptless: true }
11466
+ );
11467
+ return { notified: true };
11468
+ } catch (error) {
11469
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
11470
+ }
11471
+ }
11126
11472
  async getFundingWallet(state, chainId, asset) {
11127
11473
  this.assertAsset(asset);
11474
+ this.throwIfSlotUnavailable(state, chainId, asset);
11128
11475
  const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11129
11476
  if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
11130
11477
  return context.wallet.walletAddress;
@@ -11185,7 +11532,7 @@ var YieldseekerAgent = class {
11185
11532
  });
11186
11533
  const catalog = await Promise.all(
11187
11534
  [...new Set(contexts.map((context) => context.asset))].map(
11188
- (contextAsset) => this.loadVaultOptions(contextAsset)
11535
+ (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
11189
11536
  )
11190
11537
  );
11191
11538
  const vaultAddresses = new Set(
@@ -11210,11 +11557,11 @@ var YieldseekerAgent = class {
11210
11557
  );
11211
11558
  }
11212
11559
  async getAgentApy(days, options) {
11213
- if (!this.supportsAgentApyPeriod(days)) {
11560
+ if (days === "14D") {
11214
11561
  throw new OwneyError(
11215
11562
  "AGENT_APY_PERIOD_UNSUPPORTED",
11216
11563
  `Yieldseeker does not provide a representative ${days} strategy APY.`,
11217
- { days, supportedDays: ["7D"] },
11564
+ { days, supportedDays: ["7D", "30D"] },
11218
11565
  this.id
11219
11566
  );
11220
11567
  }
@@ -11227,10 +11574,10 @@ var YieldseekerAgent = class {
11227
11574
  return { asset, stats: await this.loadAssetApyStats(asset) };
11228
11575
  })
11229
11576
  );
11230
- return mapYieldseekerAgentApy(values);
11577
+ return mapYieldseekerAgentApy(values, days);
11231
11578
  }
11232
11579
  supportsAgentApyPeriod(days) {
11233
- return days === "7D";
11580
+ return days === "7D" || days === "30D";
11234
11581
  }
11235
11582
  async loadAssetApyStats(asset) {
11236
11583
  const cached = this.assetApyStats.get(asset);
@@ -11242,7 +11589,7 @@ var YieldseekerAgent = class {
11242
11589
  `/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
11243
11590
  ).then((response) => {
11244
11591
  const stats = response?.assetApyStats;
11245
- 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)) {
11592
+ 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)) {
11246
11593
  throw this.invalidResponse("asset APY statistics");
11247
11594
  }
11248
11595
  this.assetApyStats.set(asset, {
@@ -11254,27 +11601,321 @@ var YieldseekerAgent = class {
11254
11601
  this.pendingAssetApyStats.set(asset, request2);
11255
11602
  return request2;
11256
11603
  }
11257
- async loadVaultOptions(asset) {
11258
- const cached = this.vaultOptions.get(asset);
11604
+ /**
11605
+ * The deposit-time Pools step's catalogue: every vault Yieldseeker lists
11606
+ * for a new agent on `asset` on Base, grouped by provider (the provider is
11607
+ * both `protocolId` and `name`). Nothing is filtered on our side, on
11608
+ * liquidity, size or provider. `strategy` is accepted for the IAgent
11609
+ * contract and ignored.
11610
+ */
11611
+ async getPoolCatalog(params) {
11612
+ const asset = params.asset.toUpperCase();
11613
+ this.assertAsset(asset);
11614
+ const byProvider = /* @__PURE__ */ new Map();
11615
+ for (const vault of await this.loadVaultOptions(asset)) {
11616
+ const pools = byProvider.get(vault.provider) ?? [];
11617
+ pools.push({
11618
+ chainId: 8453,
11619
+ token: asset,
11620
+ name: vault.name,
11621
+ apy: apyAsPercent(vault.totalApy),
11622
+ tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
11623
+ link: null,
11624
+ address: vault.address
11625
+ });
11626
+ byProvider.set(vault.provider, pools);
11627
+ }
11628
+ return [...byProvider].map(([provider, pools]) => ({
11629
+ protocolId: provider,
11630
+ name: provider,
11631
+ logo: null,
11632
+ pools
11633
+ }));
11634
+ }
11635
+ /**
11636
+ * The asset's vaults on Base. By default only those a new agent can use:
11637
+ * Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
11638
+ * among them), gated or can't use, so the picker follows its list
11639
+ * (2026-11-04). `includeUnavailable` adds those back, for anything about
11640
+ * money an agent may still hold in one: withdrawals and activity.
11641
+ */
11642
+ async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
11643
+ const key2 = vaultOptionsKey(asset, includeUnavailable);
11644
+ const cached = this.vaultOptions.get(key2);
11259
11645
  if (cached && cached.expiresAt > Date.now()) return cached.value;
11260
- const pending2 = this.pendingVaultOptions.get(asset);
11646
+ const pending2 = this.pendingVaultOptions.get(key2);
11261
11647
  if (pending2) return pending2;
11262
11648
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
11263
11649
  const request2 = this.api.request(
11264
- `/chains/8453/assets/${metadata.address}/vault-options`
11650
+ `/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
11265
11651
  ).then((response) => {
11266
11652
  if (!Array.isArray(response?.vaultOptions)) {
11267
11653
  throw this.invalidResponse("vault options");
11268
11654
  }
11269
- this.vaultOptions.set(asset, {
11655
+ this.vaultOptions.set(key2, {
11270
11656
  expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
11271
11657
  value: response.vaultOptions
11272
11658
  });
11273
11659
  return response.vaultOptions;
11274
- }).finally(() => this.pendingVaultOptions.delete(asset));
11275
- this.pendingVaultOptions.set(asset, request2);
11660
+ }).finally(() => this.pendingVaultOptions.delete(key2));
11661
+ this.pendingVaultOptions.set(key2, request2);
11276
11662
  return request2;
11277
11663
  }
11664
+ /**
11665
+ * Save the user's Yieldseeker picks as the agent's managed vault list, then
11666
+ * read the rules back before any money moves. Each asset has its own agent,
11667
+ * so each is saved on its own. `pools` and `availablePools` hold vault
11668
+ * addresses.
11669
+ *
11670
+ * - Only Base entries are ours. An asset with no picks whose entries showed
11671
+ * no vault is skipped and nothing is sent.
11672
+ * - Some vaults picked: the managed list names them. Saving it again
11673
+ * replaces it, so there is only ever one.
11674
+ * - None picked (vaults shown): the managed list names no vault, and the
11675
+ * rules must read back as an empty allow-list. Yieldseeker then keeps the
11676
+ * agent's money out of every vault, as Zyfai does with an empty pool list,
11677
+ * and the next Pools step reads "none". Only an agent that already exists
11678
+ * is written: one is never created just to hold "none".
11679
+ * - Every vault picked: the managed list is deleted, and no allow-list may
11680
+ * remain, so vaults Yieldseeker adds later are allowed too.
11681
+ * - A free-text allow-list we saved before the managed list existed is
11682
+ * deleted once the new state is written. A failed delete does not fail the
11683
+ * save; it is debug-logged, and the read-back decides.
11684
+ * - A read-back that differs puts the previous managed list back (or deletes
11685
+ * the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
11686
+ * it back fails too, that is still the error thrown. An old free-text list
11687
+ * already deleted is not put back.
11688
+ * - An agent already holding the most active memories, none of them ours,
11689
+ * throws POOL_SELECTION_RULE_LIMIT before anything is written.
11690
+ *
11691
+ * Always Base, whichever chain the wallet is connected on.
11692
+ */
11693
+ async setPoolSelection(selection, state) {
11694
+ if (!state) {
11695
+ throw new OwneyError(
11696
+ "NOT_CONNECTED",
11697
+ "Connect a wallet before saving Yieldseeker pool picks.",
11698
+ void 0,
11699
+ this.id
11700
+ );
11701
+ }
11702
+ const byAsset = /* @__PURE__ */ new Map();
11703
+ for (const entry of selection.selections) {
11704
+ if (entry.chainId !== 8453) continue;
11705
+ this.assertAsset(entry.asset);
11706
+ const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
11707
+ group.picked.push(...entry.pools);
11708
+ group.shown.push(...entry.availablePools);
11709
+ byAsset.set(entry.asset, group);
11710
+ }
11711
+ for (const [asset, group] of byAsset) {
11712
+ const picks = uniqueAddresses(group.picked);
11713
+ const shown = uniqueAddresses(group.shown);
11714
+ if (picks.length === 0 && shown.length === 0) continue;
11715
+ const picked = new Set(picks.map((address) => address.toLowerCase()));
11716
+ const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11717
+ await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11718
+ }
11719
+ }
11720
+ async savePoolPicks(state, asset, picks, everyVaultPicked) {
11721
+ const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11722
+ if (!context) {
11723
+ debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11724
+ return;
11725
+ }
11726
+ const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11727
+ const managed = active.find(isManagedVaultList);
11728
+ const legacy = active.filter(isLegacyPoolSelectionMemory);
11729
+ const writing = !everyVaultPicked;
11730
+ if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
11731
+ throw new OwneyError(
11732
+ "POOL_SELECTION_RULE_LIMIT",
11733
+ `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.`,
11734
+ { asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
11735
+ this.id
11736
+ );
11737
+ }
11738
+ const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
11739
+ const change = { previous: managed, written: false };
11740
+ if (content === void 0) {
11741
+ if (managed) {
11742
+ await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
11743
+ method: "POST"
11744
+ });
11745
+ change.written = true;
11746
+ }
11747
+ } else {
11748
+ const answer = await this.memoryRequest(state, context, "memories", {
11749
+ method: "POST",
11750
+ body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11751
+ });
11752
+ change.written = true;
11753
+ if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
11754
+ }
11755
+ await this.deleteLegacyPoolMemories(state, context, asset, legacy);
11756
+ let failure;
11757
+ try {
11758
+ const allowed = await this.readAllowList(state, context);
11759
+ const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
11760
+ if (!applied) failure = "ALLOW_LIST_MISMATCH";
11761
+ } catch {
11762
+ failure = "READ_BACK_FAILED";
11763
+ }
11764
+ if (!failure) return;
11765
+ const restored = await this.restorePoolMemory(state, context, change);
11766
+ throw new OwneyError(
11767
+ "POOL_SELECTION_NOT_APPLIED",
11768
+ `Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
11769
+ { asset, reason: failure, restored },
11770
+ this.id
11771
+ );
11772
+ }
11773
+ /**
11774
+ * Delete the free-text allow-lists we saved before the managed list existed.
11775
+ * Never throws: a list left behind is caught by the read-back. Logs no
11776
+ * sign-in token.
11777
+ */
11778
+ async deleteLegacyPoolMemories(state, context, asset, memories) {
11779
+ for (const memory2 of memories) {
11780
+ try {
11781
+ await this.memoryRequest(state, context, `memories/${memory2.agentMemoryId}/delete`, {
11782
+ method: "POST"
11783
+ });
11784
+ } catch (error) {
11785
+ debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
11786
+ memoryId: memory2.agentMemoryId,
11787
+ code: error instanceof OwneyError ? error.code : void 0,
11788
+ message: error instanceof Error ? error.message : void 0
11789
+ });
11790
+ }
11791
+ }
11792
+ }
11793
+ /**
11794
+ * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11795
+ * has no brackets. No picks names no vault.
11796
+ */
11797
+ async poolMemoryContent(asset, picks) {
11798
+ if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11799
+ const vaults = new Map(
11800
+ (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11801
+ );
11802
+ const entries = picks.map((pick) => {
11803
+ const vault = vaults.get(pick.toLowerCase());
11804
+ const address = vault?.address ?? pick;
11805
+ return vault?.name ? `${address} (${vault.name})` : address;
11806
+ });
11807
+ return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
11808
+ }
11809
+ /** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
11810
+ async restorePoolMemory(state, context, change) {
11811
+ if (!change.written) return true;
11812
+ try {
11813
+ if (change.previous) {
11814
+ await this.memoryRequest(state, context, "memories", {
11815
+ method: "POST",
11816
+ body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11817
+ });
11818
+ return true;
11819
+ }
11820
+ const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory2) => isActiveMemory(memory2) && isManagedVaultList(memory2)).map((memory2) => memory2.agentMemoryId);
11821
+ for (const id of ids) {
11822
+ await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
11823
+ }
11824
+ return true;
11825
+ } catch {
11826
+ return false;
11827
+ }
11828
+ }
11829
+ /**
11830
+ * What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
11831
+ * pairs: the allowed vault addresses under the provider each belongs to, for
11832
+ * the vaults a new agent can use. An agent with no allow-list adds nothing,
11833
+ * and no pairs at all means every shown vault is on. Reads never create an
11834
+ * agent, and always read Base. A read that fails throws, because "no
11835
+ * allow-list" would wrongly mean "everything".
11836
+ *
11837
+ * An allow-list naming none of the listed vaults (the saved "none", or vaults
11838
+ * Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
11839
+ * it reports none chosen for its asset: a pair with empty `pools` for every
11840
+ * provider listing vaults for it. With no vault listed at all there is
11841
+ * nothing to name that by, and it throws: the rules still restrict the agent.
11842
+ *
11843
+ * `pairs` is accepted for the contract but does not trim the answer: cutting
11844
+ * a real allow-list down to the pairs asked about could leave none, and none
11845
+ * reads as every vault on.
11846
+ */
11847
+ async getPoolSelection(state, _chainId, params) {
11848
+ const byProvider = /* @__PURE__ */ new Map();
11849
+ for (const asset of new Set(params.assets)) {
11850
+ this.assertAsset(asset);
11851
+ const context = await this.findAgent(state, 8453, asset);
11852
+ if (!context) continue;
11853
+ const allowed = await this.readAllowList(state, context);
11854
+ if (allowed === void 0) continue;
11855
+ const options = await this.loadVaultOptions(asset);
11856
+ if (options.length === 0) {
11857
+ throw this.invalidResponse("pool selection", {
11858
+ reason: "vault-options lists no vault while an allow-list restricts the agent.",
11859
+ asset
11860
+ });
11861
+ }
11862
+ const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
11863
+ const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
11864
+ if (known.length === 0) {
11865
+ for (const vault of options) {
11866
+ if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
11867
+ }
11868
+ continue;
11869
+ }
11870
+ for (const vault of known) {
11871
+ const pools = byProvider.get(vault.provider) ?? [];
11872
+ byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
11873
+ }
11874
+ }
11875
+ return {
11876
+ strategies: [],
11877
+ pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
11878
+ };
11879
+ }
11880
+ /**
11881
+ * The allow-list in the agent's rules: every `allowedVaultAddresses` on an
11882
+ * `ignored_vault` user rule. Undefined when no rule has one, which allows
11883
+ * every vault; an empty list allows none. A response that does not have the
11884
+ * expected shape throws rather than reading as no allow-list.
11885
+ */
11886
+ async readAllowList(state, context) {
11887
+ const rules = await this.memoryRequest(
11888
+ state,
11889
+ context,
11890
+ "memories/effective-rules"
11891
+ );
11892
+ if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
11893
+ let allowed;
11894
+ for (const rule of rules.userRules) {
11895
+ if (rule?.ruleType !== "ignored_vault") continue;
11896
+ const list = rule.ruleConfig?.allowedVaultAddresses;
11897
+ if (list === void 0 || list === null) continue;
11898
+ if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
11899
+ throw this.invalidResponse("effective rules");
11900
+ }
11901
+ allowed = [...allowed ?? [], ...list];
11902
+ }
11903
+ return allowed;
11904
+ }
11905
+ async listMemories(state, context) {
11906
+ const response = await this.memoryRequest(state, context, "memories");
11907
+ if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
11908
+ return response.memories;
11909
+ }
11910
+ /** A memory call for an agent, on Base whichever chain the wallet is on. */
11911
+ async memoryRequest(state, context, suffix, options = {}) {
11912
+ try {
11913
+ return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
11914
+ } catch (error) {
11915
+ if (error instanceof OwneyError) throw error;
11916
+ throw this.mapRequestFailure(error);
11917
+ }
11918
+ }
11278
11919
  userKey(state, chainId) {
11279
11920
  return `${state.walletAddress.toLowerCase()}:${chainId}`;
11280
11921
  }
@@ -11327,6 +11968,7 @@ var YieldseekerAgent = class {
11327
11968
  this.agentContexts.set(slot, context);
11328
11969
  this.pendingSlotInvalidations.delete(slot);
11329
11970
  this.missingSlots.delete(slot);
11971
+ this.closedSlots.delete(slot);
11330
11972
  }
11331
11973
  assertSession(generation, chainId, asset) {
11332
11974
  if (this.readGeneration !== generation) {
@@ -11438,8 +12080,10 @@ var YieldseekerAgent = class {
11438
12080
  * highest-priority set of `priorities` (index 0 first). Hinted agentIds are
11439
12081
  * resolved first and a hinted top-priority match ends the search; then other
11440
12082
  * listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
12083
+ * A candidate whose wallet shows it closed (deactivated) never ranks, and its
12084
+ * agentId is added to `closed`.
11441
12085
  */
11442
- async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
12086
+ async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
11443
12087
  const fitting = /* @__PURE__ */ new Map();
11444
12088
  for (const agent of agents) {
11445
12089
  if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
@@ -11461,6 +12105,10 @@ var YieldseekerAgent = class {
11461
12105
  failure ??= { error: result.reason };
11462
12106
  continue;
11463
12107
  }
12108
+ if (result.value.wallet.deactivatedDate) {
12109
+ closed?.add(result.value.agent.agentId);
12110
+ continue;
12111
+ }
11464
12112
  const wallet = result.value.wallet.walletAddress.toLowerCase();
11465
12113
  const rank = priorities.findIndex((wallets) => wallets.has(wallet));
11466
12114
  if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
@@ -11475,32 +12123,213 @@ var YieldseekerAgent = class {
11475
12123
  }
11476
12124
  /**
11477
12125
  * chooseAgent, re-reading a cached list once (bypassing its cache) when the
11478
- * verified agent is missing. A slot still missing after that re-read is
11479
- * remembered for the list cache window, so later reads fail from the cached
11480
- * list without another re-read.
12126
+ * verified agent is missing. Still missing, Yieldseeker may have closed
12127
+ * (deactivated) it: the verified record's agent is reactivated and selected
12128
+ * from a fresh list, by the verified wallet only (never created). A slot
12129
+ * that still fails is remembered with its error for the list cache window,
12130
+ * so later reads fail without another re-read or reactivate. A slot
12131
+ * Yieldseeker will not reopen because of its active-agent limit throws
12132
+ * YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
12133
+ * no request.
11481
12134
  */
11482
12135
  async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
12136
+ this.throwIfSlotUnavailable(state, chainId, asset);
11483
12137
  try {
11484
12138
  return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
11485
12139
  } catch (error) {
11486
12140
  if (!this.isAgentMissing(error)) throw error;
11487
12141
  const slot = this.slotKey(state, chainId, asset);
11488
- if (this.isSlotMissing(slot)) throw error;
12142
+ this.throwIfSlotMissing(slot);
11489
12143
  const generation = this.readGeneration;
11490
12144
  const fresh = await this.listAgents(state, chainId, user, true);
11491
12145
  this.assertSession(generation, chainId, asset);
12146
+ let missing;
11492
12147
  try {
11493
12148
  return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
11494
12149
  } catch (retryError) {
11495
- if (this.isAgentMissing(retryError) && this.readGeneration === generation) {
11496
- this.missingSlots.set(slot, Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS);
12150
+ if (!this.isAgentMissing(retryError)) throw retryError;
12151
+ missing = retryError;
12152
+ }
12153
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
12154
+ const agentId = verified?.providerAgentId;
12155
+ if (!verified || !agentId) {
12156
+ this.rememberMissingSlot(slot, generation, missing);
12157
+ throw missing;
12158
+ }
12159
+ this.throwIfSlotMissing(slot);
12160
+ let reopened;
12161
+ try {
12162
+ reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
12163
+ this.assertSession(generation, chainId, asset);
12164
+ } catch (reopenError) {
12165
+ this.rememberMissingSlot(slot, generation, reopenError);
12166
+ throw reopenError;
12167
+ }
12168
+ try {
12169
+ const agent = await this.agentWithWallet(
12170
+ state,
12171
+ chainId,
12172
+ user,
12173
+ reopened,
12174
+ asset,
12175
+ [/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
12176
+ [agentId]
12177
+ );
12178
+ if (agent) return agent;
12179
+ throw this.agentMissing(chainId, asset, agentId);
12180
+ } catch (reopenedError) {
12181
+ if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
12182
+ throw reopenedError;
12183
+ }
12184
+ }
12185
+ }
12186
+ throwIfSlotUnavailable(state, chainId, asset) {
12187
+ const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
12188
+ if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
12189
+ }
12190
+ /**
12191
+ * Rethrow the error a slot's lookup failed with while the slot is still
12192
+ * marked, or for the session when Yieldseeker will never reopen its agent.
12193
+ * A remembered rate limit is rethrown with the time left on its marker as
12194
+ * its retry delay (`retryAfterSeconds`): no new attempt is made before then,
12195
+ * so a caller that waits it out retries once instead of every few seconds.
12196
+ */
12197
+ throwIfSlotMissing(slot) {
12198
+ const closed = this.closedSlots.get(slot);
12199
+ if (closed) throw closed;
12200
+ const missing = this.missingSlots.get(slot);
12201
+ if (!missing || missing.until <= Date.now()) return;
12202
+ const { error } = missing;
12203
+ if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
12204
+ const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
12205
+ const rethrown = new OwneyError(
12206
+ error.code,
12207
+ error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
12208
+ { ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
12209
+ error.agentId
12210
+ );
12211
+ this.rethrownSlotFailures.set(rethrown, error);
12212
+ throw rethrown;
12213
+ }
12214
+ /**
12215
+ * Remember a slot's failed lookup or reactivate for the list-cache window.
12216
+ * A sign-in failure is not remembered (the wallet's rejection,
12217
+ * AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
12218
+ * remembered it would refuse the next sign-in, even one the user starts,
12219
+ * with no request for the whole window.
12220
+ */
12221
+ rememberMissingSlot(slot, generation, error) {
12222
+ if (this.readGeneration !== generation) return;
12223
+ if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
12224
+ this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
12225
+ }
12226
+ /**
12227
+ * Reactivate the slot's verified agent, then read the list bypassing its
12228
+ * cache, with a read sent after the reactivate answered. Concurrent lookups
12229
+ * of one slot share one reopen. Resolves to the fresh list. At the
12230
+ * active-agent limit the slot is recorded unavailable and this throws
12231
+ * YIELDSEEKER_SLOT_UNAVAILABLE.
12232
+ */
12233
+ reopenAgent(state, chainId, user, asset, agentId) {
12234
+ const slot = this.slotKey(state, chainId, asset);
12235
+ const pending2 = this.pendingReopens.get(slot);
12236
+ if (pending2) return pending2;
12237
+ const generation = this.readGeneration;
12238
+ const request2 = (async () => {
12239
+ const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
12240
+ this.assertSession(generation, chainId, asset);
12241
+ if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
12242
+ this.forgetAgentWallet(agentId);
12243
+ this.missingSlots.delete(slot);
12244
+ await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
12245
+ this.assertSession(generation, chainId, asset);
12246
+ const fresh = await this.listAgents(state, chainId, user, true);
12247
+ this.assertSession(generation, chainId, asset);
12248
+ return fresh;
12249
+ })().finally(() => {
12250
+ if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
12251
+ });
12252
+ this.pendingReopens.set(slot, request2);
12253
+ return request2;
12254
+ }
12255
+ /**
12256
+ * The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
12257
+ * and the pre-deposit check (assertAgentOpen), so a slot costs at most one
12258
+ * reactivate per list-cache window:
12259
+ * - a slot recorded unavailable (the limit) answers "limit" with no request;
12260
+ * - concurrent callers share one request;
12261
+ * - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
12262
+ * remembered as the slot's failure for the list-cache window (missingSlots)
12263
+ * and rethrown to later callers with no request; a closed code
12264
+ * (closedSlots) for the session; a sign-in failure is not remembered;
12265
+ * - the limit is recorded in unavailableSlots only while the session is
12266
+ * unchanged, so a disconnect during the request is not undone by its late
12267
+ * answer.
12268
+ */
12269
+ async reactivateSlot(state, chainId, user, asset, agentId) {
12270
+ const slot = this.slotKey(state, chainId, asset);
12271
+ const limit = this.unavailableSlots.get(slot);
12272
+ if (limit !== void 0) return { outcome: "limit", providerCode: limit };
12273
+ const key2 = `${slot}:${agentId}`;
12274
+ const pending2 = this.pendingReactivates.get(key2);
12275
+ if (pending2) return pending2;
12276
+ this.throwIfSlotMissing(slot);
12277
+ const generation = this.readGeneration;
12278
+ const request2 = (async () => {
12279
+ try {
12280
+ const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
12281
+ if (result.outcome === "limit" && this.readGeneration === generation) {
12282
+ this.unavailableSlots.set(slot, result.providerCode);
11497
12283
  }
11498
- throw retryError;
12284
+ return result;
12285
+ } catch (error) {
12286
+ 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)) {
12287
+ this.closedSlots.set(slot, error);
12288
+ }
12289
+ this.rememberMissingSlot(slot, generation, error);
12290
+ throw error;
12291
+ }
12292
+ })().finally(() => {
12293
+ if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
12294
+ });
12295
+ this.pendingReactivates.set(key2, request2);
12296
+ return request2;
12297
+ }
12298
+ /**
12299
+ * Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
12300
+ * Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
12301
+ * by another tab) counts as reopened; the active-agent limit is an outcome,
12302
+ * not an error. An agent that cannot come back throws
12303
+ * YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
12304
+ * 5xx, an unknown code) throws the mapped API error.
12305
+ */
12306
+ async reactivateAgent(state, chainId, user, asset, agentId) {
12307
+ try {
12308
+ await this.providerRequest(
12309
+ state,
12310
+ chainId,
12311
+ `/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
12312
+ { method: "POST", body: {} }
12313
+ );
12314
+ return { outcome: "reopened" };
12315
+ } catch (error) {
12316
+ if (error instanceof OwneyError) throw error;
12317
+ const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
12318
+ if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
12319
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
12320
+ return { outcome: "limit", providerCode };
12321
+ }
12322
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
12323
+ throw this.agentClosed(chainId, asset, agentId, providerCode);
11499
12324
  }
12325
+ throw this.mapRequestFailure(error);
11500
12326
  }
11501
12327
  }
11502
- isSlotMissing(slot) {
11503
- return (this.missingSlots.get(slot) ?? 0) > Date.now();
12328
+ /** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
12329
+ forgetAgentWallet(agentId) {
12330
+ const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
12331
+ for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
12332
+ for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
11504
12333
  }
11505
12334
  /**
11506
12335
  * The agent that serves deposits and withdrawals for a slot (Ruling 23):
@@ -11508,7 +12337,8 @@ var YieldseekerAgent = class {
11508
12337
  * whatever its name; the stored agentId is only a hint;
11509
12338
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
11510
12339
  * 3. else the fitting agent named "owney" (first use, migration, or a
11511
- * verified wallet that is not a fitting listed agent);
12340
+ * verified wallet that is not a fitting listed agent), unless step 1/2
12341
+ * read its wallet and it is closed (deactivated): that agent is not listed;
11512
12342
  * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
11513
12343
  * create); without one, undefined (the caller may create).
11514
12344
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
@@ -11519,6 +12349,7 @@ var YieldseekerAgent = class {
11519
12349
  const slot = this.slotAccounts(accounts, chainId, asset);
11520
12350
  const verified = slot.find((account) => account.status === "verified");
11521
12351
  const superseded = slot.filter((account) => account.status === "superseded");
12352
+ const closed = /* @__PURE__ */ new Set();
11522
12353
  if (verified || superseded.length) {
11523
12354
  const priorities = [];
11524
12355
  if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
@@ -11532,11 +12363,12 @@ var YieldseekerAgent = class {
11532
12363
  agents,
11533
12364
  asset,
11534
12365
  priorities,
11535
- [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
12366
+ [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
12367
+ closed
11536
12368
  );
11537
12369
  if (match) return match;
11538
12370
  }
11539
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
12371
+ const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
11540
12372
  if (named) return named;
11541
12373
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
11542
12374
  return void 0;
@@ -11552,6 +12384,39 @@ var YieldseekerAgent = class {
11552
12384
  this.id
11553
12385
  );
11554
12386
  }
12387
+ slotUnavailable(chainId, asset, providerCode) {
12388
+ return new OwneyError(
12389
+ "YIELDSEEKER_SLOT_UNAVAILABLE",
12390
+ `Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
12391
+ { rpcSource: "agent-api", chainId, asset, providerCode },
12392
+ this.id
12393
+ );
12394
+ }
12395
+ /** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
12396
+ isSlotEmpty(error) {
12397
+ return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
12398
+ }
12399
+ /**
12400
+ * The slot's lookup failed through the missing-agent / reopen path and was
12401
+ * remembered with this very error, even a transient one (429, 5xx, timeout),
12402
+ * or with the copy of it a remembered rate limit is rethrown as. Compares
12403
+ * the remembered error, not its expiry, so it holds however long the rest
12404
+ * of the read takes.
12405
+ */
12406
+ isMarkedSlotFailure(slot, error) {
12407
+ const marker = this.missingSlots.get(slot);
12408
+ if (!marker) return false;
12409
+ return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
12410
+ }
12411
+ /** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
12412
+ agentClosed(chainId, asset, agentId, providerCode, extra) {
12413
+ return new OwneyError(
12414
+ "YIELDSEEKER_AGENT_CLOSED",
12415
+ `Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
12416
+ { rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
12417
+ this.id
12418
+ );
12419
+ }
11555
12420
  /**
11556
12421
  * Fire-and-forget: record which agent serves this slot. Never awaited on the
11557
12422
  * funds path and never throws; once per agent wallet and deployment state
@@ -11641,7 +12506,7 @@ var YieldseekerAgent = class {
11641
12506
  } catch (error) {
11642
12507
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
11643
12508
  if (error instanceof OwneyError) throw error;
11644
- throw this.mapApiError(error);
12509
+ throw this.mapRequestFailure(error);
11645
12510
  }
11646
12511
  let created;
11647
12512
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
@@ -11662,7 +12527,7 @@ var YieldseekerAgent = class {
11662
12527
  } catch (createError) {
11663
12528
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
11664
12529
  if (canRetry) continue;
11665
- throw this.mapApiError(createError);
12530
+ throw this.mapRequestFailure(createError);
11666
12531
  }
11667
12532
  }
11668
12533
  user = created?.user ?? null;
@@ -11719,6 +12584,7 @@ var YieldseekerAgent = class {
11719
12584
  return context;
11720
12585
  }
11721
12586
  async resolveAgent(state, chainId, asset, createIfMissing) {
12587
+ this.throwIfSlotUnavailable(state, chainId, asset);
11722
12588
  const generation = this.readGeneration;
11723
12589
  const accountsRead = this.agentAccounts(state, chainId);
11724
12590
  const user = await this.resolveUser(state, chainId);
@@ -11761,7 +12627,7 @@ var YieldseekerAgent = class {
11761
12627
  );
11762
12628
  } catch (error) {
11763
12629
  const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
11764
- if (!conflict) throw this.mapApiError(error);
12630
+ if (!conflict) throw this.mapRequestFailure(error);
11765
12631
  this.assertSession(generation, chainId, asset);
11766
12632
  return this.adoptConflictingAgent(
11767
12633
  state,
@@ -11854,10 +12720,11 @@ var YieldseekerAgent = class {
11854
12720
  const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
11855
12721
  if (agent) selected.set(asset, agent);
11856
12722
  } catch (error) {
11857
- if (assetFilter || !this.isAgentMissing(error)) throw error;
12723
+ if (assetFilter) throw error;
12724
+ if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
11858
12725
  missing.push(error);
11859
12726
  missingAssets?.add(asset);
11860
- console.warn(`[owney-sdk] Yieldseeker ${asset} agent is missing:`, error);
12727
+ console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
11861
12728
  }
11862
12729
  }));
11863
12730
  this.assertSession(generation, chainId);
@@ -12492,6 +13359,7 @@ var YieldseekerAgent = class {
12492
13359
  try {
12493
13360
  return await this.providerRequest(state, chainId, path, options);
12494
13361
  } catch (error) {
13362
+ if (isWalletRejection(error)) throw error;
12495
13363
  const mapped = this.mapApiError(error);
12496
13364
  const delay = read2 ? rateLimitDelay(mapped) : void 0;
12497
13365
  if (delay !== void 0 && this.readGeneration === generation) {
@@ -12546,6 +13414,16 @@ var YieldseekerAgent = class {
12546
13414
  }
12547
13415
  }
12548
13416
  }
13417
+ /**
13418
+ * mapApiError for a request that may have opened the Yieldseeker sign-in
13419
+ * prompt (providerRequest signs when no sign-in is saved, and again when
13420
+ * Yieldseeker refuses one). The wallet's rejection, the user cancelling that
13421
+ * prompt, is returned unchanged: the client and the app must see the user's
13422
+ * cancel (no further prompt, no retry), never a provider failure.
13423
+ */
13424
+ mapRequestFailure(error) {
13425
+ return isWalletRejection(error) ? error : this.mapApiError(error);
13426
+ }
12549
13427
  mapApiError(error) {
12550
13428
  if (!(error instanceof YieldseekerApiError)) {
12551
13429
  return new OwneyError(
@@ -13141,6 +14019,8 @@ var FALLBACK_WRAP_GAS = 50000n;
13141
14019
  var APPROVE_GAS = 60000n;
13142
14020
  var GAS_SAFETY = 2n;
13143
14021
  var MIN_WALLET_GAS_PRICE = 3000000000n;
14022
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
14023
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
13144
14024
  async function wrapNative(deps, options) {
13145
14025
  const { chainId, wrapper, nativeSymbol, requested } = options;
13146
14026
  const balance = await deps.readNativeBalance();
@@ -13198,16 +14078,90 @@ async function wrapNative(deps, options) {
13198
14078
  }
13199
14079
  );
13200
14080
  }
14081
+ let baseline;
14082
+ if (deps.readWrappedBalance) {
14083
+ try {
14084
+ baseline = await deps.readWrappedBalance();
14085
+ } catch (error) {
14086
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
14087
+ message: error instanceof Error ? error.message : String(error)
14088
+ });
14089
+ }
14090
+ }
13201
14091
  await deps.ensureChain(chainId);
13202
14092
  debugLog("owney-sdk", "wrap: sending deposit()", {
13203
14093
  wrapper,
13204
14094
  value: wrapped.toString()
13205
14095
  });
13206
- const txHash = await deps.sendTransaction(
13207
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
13208
- options.onSubmitted
13209
- );
13210
- return { wrapped, txHash };
14096
+ let notified = false;
14097
+ const notify2 = (hash2) => {
14098
+ if (notified) return;
14099
+ notified = true;
14100
+ options.onSubmitted?.(hash2);
14101
+ };
14102
+ const outcome = await new Promise((resolve, reject) => {
14103
+ let done = false;
14104
+ let timer;
14105
+ const finish = (settle) => {
14106
+ if (done) return;
14107
+ done = true;
14108
+ clearTimeout(timer);
14109
+ settle();
14110
+ };
14111
+ timer = setTimeout(
14112
+ () => finish(
14113
+ () => reject(
14114
+ new OwneyError(
14115
+ "SWAP_WALLET_PROMPT_TIMEOUT",
14116
+ // Hedged on purpose: a wallet that never answered may still have
14117
+ // sent it, and wrapping again would wrap twice.
14118
+ `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}.`,
14119
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
14120
+ )
14121
+ )
14122
+ ),
14123
+ WRAP_PROMPT_TIMEOUT_MS
14124
+ );
14125
+ deps.sendTransaction(
14126
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
14127
+ (hash2) => {
14128
+ clearTimeout(timer);
14129
+ notify2(hash2);
14130
+ }
14131
+ ).then(
14132
+ (txHash) => finish(() => resolve({ txHash })),
14133
+ (error) => finish(() => reject(error))
14134
+ );
14135
+ if (baseline !== void 0 && deps.readWrappedBalance) {
14136
+ const read2 = deps.readWrappedBalance;
14137
+ const target = baseline + wrapped;
14138
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14139
+ void (async () => {
14140
+ while (!done) {
14141
+ await sleep4(WRAP_WATCH_INTERVAL_MS);
14142
+ if (done) return;
14143
+ try {
14144
+ if (await read2() >= target) {
14145
+ debugLog(
14146
+ "owney-sdk",
14147
+ "wrap: landed on chain before the wallet answered"
14148
+ );
14149
+ finish(() => {
14150
+ notify2();
14151
+ resolve({});
14152
+ });
14153
+ return;
14154
+ }
14155
+ } catch {
14156
+ }
14157
+ }
14158
+ })();
14159
+ }
14160
+ });
14161
+ return {
14162
+ wrapped,
14163
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
14164
+ };
13211
14165
  }
13212
14166
  function requireWrapper(quote) {
13213
14167
  const wrapper = quote.wrappedNative;
@@ -14761,9 +15715,40 @@ function aggregateApyHistory(agentApys) {
14761
15715
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
14762
15716
  if (total <= 0 || !Number.isFinite(total)) return [];
14763
15717
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
14764
- return Number.isFinite(apy) ? [{ date, apy }] : [];
15718
+ if (!Number.isFinite(apy)) return [];
15719
+ const incentives = aggregateIncentives(points, total);
15720
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
14765
15721
  });
14766
15722
  }
15723
+ function incentiveKey(incentive) {
15724
+ return JSON.stringify([
15725
+ incentive.source,
15726
+ incentive.agentId,
15727
+ incentive.opportunityId,
15728
+ [...incentive.campaignIds].sort()
15729
+ ]);
15730
+ }
15731
+ function aggregateIncentives(points, totalBalance) {
15732
+ const byProgram = /* @__PURE__ */ new Map();
15733
+ for (const point of points) {
15734
+ const weight = point.historicalBalance.amount / totalBalance;
15735
+ for (const incentive of point.incentives ?? []) {
15736
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
15737
+ const key2 = incentiveKey(incentive);
15738
+ const existing = byProgram.get(key2);
15739
+ if (existing) {
15740
+ existing.apyContribution += incentive.apyContribution * weight;
15741
+ } else {
15742
+ byProgram.set(key2, {
15743
+ ...incentive,
15744
+ campaignIds: [...incentive.campaignIds],
15745
+ apyContribution: incentive.apyContribution * weight
15746
+ });
15747
+ }
15748
+ }
15749
+ }
15750
+ return [...byProgram.values()];
15751
+ }
14767
15752
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
14768
15753
  const sums = {};
14769
15754
  const weights = {};
@@ -15568,6 +16553,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
15568
16553
  }
15569
16554
  }
15570
16555
 
16556
+ // src/lib/walletconnect-switch.ts
16557
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
16558
+ var HOLD_CHAIN_MS = 15e3;
16559
+ var MAX_RESENDS = 2;
16560
+ var holds = /* @__PURE__ */ new Map();
16561
+ function parseChainId(raw2) {
16562
+ if (typeof raw2 === "number") return raw2;
16563
+ if (typeof raw2 !== "string") return void 0;
16564
+ const ref = raw2.split(":").pop() ?? raw2;
16565
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
16566
+ return Number.isFinite(id) ? id : void 0;
16567
+ }
16568
+ function walletConnectCore(provider) {
16569
+ const p = provider;
16570
+ const core = p?.signer ?? p;
16571
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
16572
+ return null;
16573
+ }
16574
+ const peer = core.session.peer?.metadata?.name ?? "";
16575
+ if (!/metamask/i.test(peer)) return null;
16576
+ return core;
16577
+ }
16578
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
16579
+ const core = walletConnectCore(provider);
16580
+ if (!core) return false;
16581
+ holds.get(core.session.topic)?.();
16582
+ await requestSwitch(core, provider, chainId, timeoutMs);
16583
+ holdChain(core, provider, chainId);
16584
+ return true;
16585
+ }
16586
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
16587
+ const current = Number(
16588
+ await provider.request({ method: "eth_chainId" })
16589
+ );
16590
+ const hexChainId = `0x${chainId.toString(16)}`;
16591
+ let timer;
16592
+ try {
16593
+ await Promise.race([
16594
+ core.client.request({
16595
+ topic: core.session.topic,
16596
+ chainId: `eip155:${current}`,
16597
+ request: {
16598
+ method: "wallet_switchEthereumChain",
16599
+ params: [{ chainId: hexChainId }]
16600
+ }
16601
+ }),
16602
+ new Promise((_, reject) => {
16603
+ timer = setTimeout(
16604
+ () => reject(
16605
+ new Error("The wallet did not answer the network switch in time")
16606
+ ),
16607
+ timeoutMs
16608
+ );
16609
+ })
16610
+ ]);
16611
+ } finally {
16612
+ clearTimeout(timer);
16613
+ }
16614
+ try {
16615
+ core.setDefaultChain(`eip155:${chainId}`);
16616
+ } catch {
16617
+ }
16618
+ }
16619
+ function holdChain(core, provider, chainId) {
16620
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
16621
+ return;
16622
+ }
16623
+ let resends = 0;
16624
+ const listener = (raw2) => {
16625
+ const reported = parseChainId(raw2);
16626
+ debugLog("wc-switch", "wallet reported chain", {
16627
+ reported,
16628
+ holding: chainId,
16629
+ resends
16630
+ });
16631
+ if (reported === void 0 || reported === chainId) return;
16632
+ if (resends >= MAX_RESENDS) return;
16633
+ resends += 1;
16634
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
16635
+ (error) => debugLog("wc-switch", "re-switch failed", {
16636
+ error: error instanceof Error ? error.message : String(error)
16637
+ })
16638
+ );
16639
+ };
16640
+ const release = () => {
16641
+ clearTimeout(timer);
16642
+ core.removeListener?.("chainChanged", listener);
16643
+ if (holds.get(core.session.topic) === release) {
16644
+ holds.delete(core.session.topic);
16645
+ }
16646
+ };
16647
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
16648
+ core.on("chainChanged", listener);
16649
+ holds.set(core.session.topic, release);
16650
+ }
16651
+ function withWalletConnectSwitch(provider) {
16652
+ if (!walletConnectCore(provider)) return provider;
16653
+ const target = provider;
16654
+ const request2 = async (args) => {
16655
+ if (args?.method !== "wallet_switchEthereumChain") {
16656
+ return target.request(args);
16657
+ }
16658
+ const [param] = args.params ?? [];
16659
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
16660
+ if (!Number.isFinite(chainId)) return target.request(args);
16661
+ await switchWalletConnectChain(target, chainId);
16662
+ return null;
16663
+ };
16664
+ return new Proxy(target, {
16665
+ get(obj, prop) {
16666
+ if (prop === "request") return request2;
16667
+ const value = Reflect.get(obj, prop, obj);
16668
+ return typeof value === "function" ? value.bind(obj) : value;
16669
+ }
16670
+ });
16671
+ }
16672
+
15571
16673
  // src/lib/sponsored-calls-deposit.ts
15572
16674
  var import_viem24 = require("viem");
15573
16675
  init_errors();
@@ -15839,6 +16941,14 @@ var OwneySDK = class {
15839
16941
  * withdraw, but they are excluded from new deposits / activations.
15840
16942
  */
15841
16943
  disabledAgents = /* @__PURE__ */ new Set();
16944
+ /**
16945
+ * Agents whose sign-in the user cancelled this session (the wallet rejected
16946
+ * the prompt), keyed by chain. Until the app ends the session they are read
16947
+ * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
16948
+ * the user cancelled. A later successful activation of the agent removes
16949
+ * it, and `disconnect()` or a different wallet's `connect()` clears the map.
16950
+ */
16951
+ declinedSignIns = /* @__PURE__ */ new Map();
15842
16952
  state = null;
15843
16953
  connectionRevision = 0;
15844
16954
  disconnectingAgents = null;
@@ -15874,6 +16984,8 @@ var OwneySDK = class {
15874
16984
  * session started: true when it armed the refresh, false when its deadline
15875
16985
  * had passed (it only dropped the cache and forced one snapshot read). */
15876
16986
  recoveredFundingReads = /* @__PURE__ */ new Map();
16987
+ /** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
16988
+ announcedDeposits = /* @__PURE__ */ new Set();
15877
16989
  fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
15878
16990
  activationChecks = /* @__PURE__ */ new Map();
15879
16991
  // Protect the SDK entry point as well as the mini-app hook. This owns only
@@ -16129,10 +17241,15 @@ var OwneySDK = class {
16129
17241
  }
16130
17242
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
16131
17243
  this.clearConnectionState();
17244
+ if (replacingOwner) this.declinedSignIns.clear();
16132
17245
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
16133
17246
  if (revision !== this.connectionRevision)
16134
17247
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
16135
- this.state = { provider, walletAddress, chainId: null };
17248
+ this.state = {
17249
+ provider: withWalletConnectSwitch(provider),
17250
+ walletAddress,
17251
+ chainId: null
17252
+ };
16136
17253
  }
16137
17254
  /**
16138
17255
  * Disconnect from all agents and clear connection state.
@@ -16141,6 +17258,7 @@ var OwneySDK = class {
16141
17258
  async disconnect() {
16142
17259
  ++this.connectionRevision;
16143
17260
  this.clearConnectionState();
17261
+ this.declinedSignIns.clear();
16144
17262
  await this.disconnectAgents();
16145
17263
  }
16146
17264
  clearConnectionState() {
@@ -16170,6 +17288,44 @@ var OwneySDK = class {
16170
17288
  isAgentDisabled(agentId) {
16171
17289
  return this.disabledAgents.has(agentId);
16172
17290
  }
17291
+ /**
17292
+ * True when `id` takes no new deposits on this chain and asset this
17293
+ * session: its adapter reports no agent for the slot.
17294
+ */
17295
+ isAgentUnavailable(id, chainId, asset) {
17296
+ if (asset === void 0) return false;
17297
+ return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
17298
+ }
17299
+ /**
17300
+ * The agents that take no new deposits on this chain and asset this
17301
+ * session, so the app can show them as unavailable: each agent whose
17302
+ * provider has no agent for this slot. They stay withdrawable.
17303
+ */
17304
+ getUnavailableAgentIds(chainId, asset) {
17305
+ return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
17306
+ }
17307
+ /**
17308
+ * The adapter reports no agent for this chain and asset this session (see
17309
+ * `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
17310
+ * withdrawal without an explicit agent leaves it out instead of failing its
17311
+ * leg.
17312
+ */
17313
+ hasNoAgentForSlot(agent, state, chainId, asset) {
17314
+ return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
17315
+ }
17316
+ /**
17317
+ * The state an agent's reads use. An agent whose sign-in the user cancelled
17318
+ * on the connection chain this session is read from a saved sign-in only,
17319
+ * as `offChainPortfolioAgents` reads: a read that would need a wallet
17320
+ * prompt fails for that agent instead of reopening the prompt the user
17321
+ * cancelled. A later successful activation of the agent, or `disconnect()`,
17322
+ * lifts it.
17323
+ */
17324
+ readStateFor(agentId, state) {
17325
+ const chainId = state.chainId;
17326
+ if (state.promptless === true || chainId === null) return state;
17327
+ return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
17328
+ }
16173
17329
  /**
16174
17330
  * Check if the SDK has an active connection state.
16175
17331
  * @returns `true` if `connect()` has been called and `disconnect()` has not
@@ -16386,10 +17542,14 @@ var OwneySDK = class {
16386
17542
  * connection chain, then the off-chain ones on their own chain. */
16387
17543
  portfolioReads(state, chainId) {
16388
17544
  return [
16389
- ...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
16390
- ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
17545
+ ...this.activeReads(state, chainId),
17546
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
16391
17547
  ];
16392
17548
  }
17549
+ /** The active agents, each with the state its reads use (`readStateFor`). */
17550
+ activeReads(state, chainId) {
17551
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
17552
+ }
16393
17553
  /**
16394
17554
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
16395
17555
  * throws — it degrades to null — so this cannot break activation.
@@ -16513,7 +17673,7 @@ var OwneySDK = class {
16513
17673
  */
16514
17674
  async getAvailableAgents(options = {}) {
16515
17675
  await this.ensureAgentsInitialized();
16516
- const { chainId, asset, includeDisabled = false } = options;
17676
+ const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
16517
17677
  const available = [];
16518
17678
  for (const [id, agent] of this.agents) {
16519
17679
  const isEnabled = !this.isAgentDisabled(id);
@@ -16529,6 +17689,9 @@ var OwneySDK = class {
16529
17689
  continue;
16530
17690
  }
16531
17691
  }
17692
+ if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
17693
+ continue;
17694
+ }
16532
17695
  available.push({
16533
17696
  id,
16534
17697
  isEnabled,
@@ -16548,8 +17711,17 @@ var OwneySDK = class {
16548
17711
  * that support the given chainId (incompatible agents are silently skipped).
16549
17712
  * If provided, ALL specified agents must support the chainId or the call
16550
17713
  * throws before activating any agent.
17714
+ * @param options - Optional. `asset` limits setup to that asset;
17715
+ * `onAgentsSelected` fires once reads can start.
17716
+ * @throws Activation stops at the first agent that fails, and the caller
17717
+ * should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
17718
+ * earlier agent activated; `walletRejected` in its details means the user
17719
+ * rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
17720
+ * never be readied (`details.permanent`). Otherwise the agent's own error
17721
+ * is thrown as is. Until it signs in, an agent whose signature the user
17722
+ * rejected is read from a saved sign-in only and opens no prompt.
16551
17723
  */
16552
- async activateAgent(chainId, agentId, asset) {
17724
+ async activateAgent(chainId, agentId, options = {}) {
16553
17725
  const state = this.requireState();
16554
17726
  await this.ensureAgentsInitialized();
16555
17727
  this.assertActivationSession(state);
@@ -16586,7 +17758,8 @@ var OwneySDK = class {
16586
17758
  this.activeAgents.add(id);
16587
17759
  }
16588
17760
  state.chainId = chainId;
16589
- await this.activateAgentsInTurn(agents, state, chainId, asset);
17761
+ options.onAgentsSelected?.();
17762
+ await this.activateAgentsInTurn(agents, state, chainId, options.asset);
16590
17763
  return;
16591
17764
  }
16592
17765
  const compatible = [...this.agents.values()].filter(
@@ -16604,10 +17777,11 @@ var OwneySDK = class {
16604
17777
  this.activeAgents.add(agent.id);
16605
17778
  }
16606
17779
  state.chainId = chainId;
17780
+ options.onAgentsSelected?.();
16607
17781
  const enabledCompatible = compatible.filter(
16608
17782
  (agent) => !this.isAgentDisabled(agent.id)
16609
17783
  );
16610
- await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
17784
+ await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
16611
17785
  }
16612
17786
  assertActivationSession(state) {
16613
17787
  if (this.state !== state) {
@@ -16627,12 +17801,17 @@ var OwneySDK = class {
16627
17801
  * Serializing costs no real wall-clock: the user can only approve one prompt
16628
17802
  * at a time anyway.
16629
17803
  *
16630
- * Stop at the first failure so a canceled sign-in does not open another
16631
- * agent's wallet prompt. Report any earlier successes for diagnostics; the
16632
- * app discards the session when the complete sign-in does not succeed.
17804
+ * Stop at the first failure (2026-11-06): a connect needs every agent, so
17805
+ * no later agent's wallet prompt opens for a sign-in that already failed.
17806
+ * When an earlier agent activated, the partial failure reports it, and
17807
+ * `walletRejected` tells the app the user canceled; the app ends the
17808
+ * session either way. When none activated, the agent's own error is thrown.
17809
+ * A failure the provider marks `permanent` is thrown as
17810
+ * `AGENT_ACTIVATION_BLOCKED`.
16633
17811
  */
16634
17812
  async activateAgentsInTurn(agents, state, chainId, asset) {
16635
17813
  let firstError = null;
17814
+ let walletRejected = false;
16636
17815
  const activatedAgentIds = [];
16637
17816
  const failedAgents = [];
16638
17817
  for (const agent of agents) {
@@ -16643,6 +17822,7 @@ var OwneySDK = class {
16643
17822
  await this.applyOrgPolicyTo(agent, state, chainId);
16644
17823
  this.assertActivationSession(state);
16645
17824
  activatedAgentIds.push(agent.id);
17825
+ this.declinedSignIns.get(chainId)?.delete(agent.id);
16646
17826
  } catch (error) {
16647
17827
  this.assertActivationSession(state);
16648
17828
  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.";
@@ -16652,15 +17832,28 @@ var OwneySDK = class {
16652
17832
  message,
16653
17833
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
16654
17834
  });
16655
- if (firstError === null) {
16656
- firstError = error;
16657
- } else {
16658
- console.error(`activateAgent(${agent.id}) failed:`, error);
17835
+ firstError = error;
17836
+ if (this.isUserRejectedWithdrawal(error)) {
17837
+ walletRejected = true;
17838
+ const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
17839
+ declined.add(agent.id);
17840
+ this.declinedSignIns.set(chainId, declined);
16659
17841
  }
16660
17842
  break;
16661
17843
  }
16662
17844
  }
16663
17845
  if (firstError === null) return;
17846
+ if (failedAgents.some(({ details }) => details?.permanent === true)) {
17847
+ throw new OwneyError(
17848
+ "AGENT_ACTIVATION_BLOCKED",
17849
+ failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
17850
+ {
17851
+ activatedAgentIds,
17852
+ failedAgentIds: failedAgents.map(({ agentId }) => agentId),
17853
+ failures: failedAgents
17854
+ }
17855
+ );
17856
+ }
16664
17857
  if (activatedAgentIds.length === 0) throw firstError;
16665
17858
  const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
16666
17859
  const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
@@ -16670,7 +17863,7 @@ var OwneySDK = class {
16670
17863
  throw new OwneyError(
16671
17864
  "AGENT_ACTIVATION_PARTIAL_FAILURE",
16672
17865
  `${activeNames} activated. ${failureMessages}`,
16673
- { activatedAgentIds, failedAgentIds, failures: failedAgents }
17866
+ { activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
16674
17867
  );
16675
17868
  }
16676
17869
  /**
@@ -16685,6 +17878,10 @@ var OwneySDK = class {
16685
17878
  * all shares into one signature; custom callbacks still run once per agent.
16686
17879
  * @param options.agentId - Optional explicit target. Otherwise split equally,
16687
17880
  * or fund remaining agents when a recovery deposit cannot meet every minimum.
17881
+ * @param options.excludeAgentIds - Agents that must receive nothing. The rest
17882
+ * split the whole amount under their own minimums. Throws
17883
+ * `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
17884
+ * when resuming a signed batch.
16688
17885
  * @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
16689
17886
  */
16690
17887
  async deposit(options) {
@@ -16713,6 +17910,7 @@ var OwneySDK = class {
16713
17910
  const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
16714
17911
  if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
16715
17912
  if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
17913
+ this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
16716
17914
  } catch {
16717
17915
  }
16718
17916
  };
@@ -16748,6 +17946,8 @@ var OwneySDK = class {
16748
17946
  const state = this.requireState();
16749
17947
  const chainId = options.chainId ?? this.requireChainId();
16750
17948
  const activatedChain = state.chainId;
17949
+ const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
17950
+ this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
16751
17951
  let checkpointFailure;
16752
17952
  let checkpointFailedEvidence = [];
16753
17953
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
@@ -16844,11 +18044,11 @@ var OwneySDK = class {
16844
18044
  const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
16845
18045
  if (!batchTransfer2) throw invalid2();
16846
18046
  const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
16847
- if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
18047
+ if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
16848
18048
  throw new OwneyError(
16849
18049
  error.code,
16850
- "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
16851
- { ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
18050
+ 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.",
18051
+ { cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
16852
18052
  error.agentId
16853
18053
  );
16854
18054
  throw error;
@@ -16886,7 +18086,7 @@ var OwneySDK = class {
16886
18086
  this.validateChainHasAgents(chainId);
16887
18087
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
16888
18088
  excludeDisabled: true
16889
- });
18089
+ }).filter((agent) => !excludeAgentIds?.includes(agent.id));
16890
18090
  const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
16891
18091
  const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
16892
18092
  const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
@@ -17034,7 +18234,7 @@ var OwneySDK = class {
17034
18234
  }
17035
18235
  try {
17036
18236
  if (!depositCallback && appObserves && !options.resumeTxHash) {
17037
- const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
18237
+ const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
17038
18238
  for (const id of ids) {
17039
18239
  const evidence = [...prepared.values()].find((value) => value.agentId === id);
17040
18240
  const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
@@ -17134,6 +18334,29 @@ var OwneySDK = class {
17134
18334
  }
17135
18335
  }
17136
18336
  }
18337
+ /**
18338
+ * Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
18339
+ * the explicit `agentId` is listed, or every agent that can take this asset
18340
+ * on this chain (and is not disabled) is. A no-op without a list, so a deposit
18341
+ * without exclusions is exactly as it was. Reads no provider.
18342
+ */
18343
+ assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
18344
+ if (!excludeAgentIds?.length) return;
18345
+ const refuse = (message) => new OwneyError(
18346
+ "ALL_AGENTS_EXCLUDED",
18347
+ message,
18348
+ { phase: "prepare", rejectedBeforeSubmission: true }
18349
+ );
18350
+ if (agentId) {
18351
+ if (excludeAgentIds.includes(agentId))
18352
+ throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
18353
+ return;
18354
+ }
18355
+ this.validateChainHasAgents(chainId);
18356
+ const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
18357
+ if (remaining.length === 0)
18358
+ throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
18359
+ }
17137
18360
  getMinDepositAmount(agent, chainId, asset) {
17138
18361
  const chainAssets = agent.supportedAssets.find(
17139
18362
  (sa) => sa.chainId === chainId
@@ -17288,9 +18511,15 @@ var OwneySDK = class {
17288
18511
  );
17289
18512
  }
17290
18513
  }
18514
+ /**
18515
+ * The agents that support this asset on this chain. `excludeDisabled` is for
18516
+ * new deposits: it also leaves out the agents unavailable for this slot this
18517
+ * session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
18518
+ * recovery still see every agent that may hold funds.
18519
+ */
17291
18520
  getEligibleAgents(chainId, asset, opts) {
17292
18521
  const eligible = [...this.agents.values()].filter((agent) => {
17293
- if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
18522
+ if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
17294
18523
  return false;
17295
18524
  }
17296
18525
  const chainAssets = agent.supportedAssets.find(
@@ -17318,20 +18547,13 @@ var OwneySDK = class {
17318
18547
  return approvalOrder || left.index - right.index;
17319
18548
  }).map(({ agent }) => agent);
17320
18549
  }
18550
+ /**
18551
+ * The user cancelled a wallet prompt, for any agent: see isWalletRejection.
18552
+ * That includes an agent error that kept the rejection only as text in
18553
+ * `details.cause`.
18554
+ */
17321
18555
  isUserRejectedWithdrawal(error) {
17322
- let current = error;
17323
- const seen = /* @__PURE__ */ new Set();
17324
- while (current && typeof current === "object" && !seen.has(current)) {
17325
- seen.add(current);
17326
- const candidate = current;
17327
- if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
17328
- const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
17329
- if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
17330
- return true;
17331
- }
17332
- current = candidate.cause;
17333
- }
17334
- return false;
18556
+ return isWalletRejection(error);
17335
18557
  }
17336
18558
  captureReadScope(requestedChain) {
17337
18559
  const original = this.requireState();
@@ -17432,6 +18654,7 @@ var OwneySDK = class {
17432
18654
  if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
17433
18655
  verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
17434
18656
  }
18657
+ if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
17435
18658
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
17436
18659
  if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
17437
18660
  agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
@@ -17440,6 +18663,33 @@ var OwneySDK = class {
17440
18663
  }
17441
18664
  return verified;
17442
18665
  }
18666
+ /**
18667
+ * Tells the agent, once per confirmed deposit transfer, that its deposit
18668
+ * landed (`IAgent.depositConfirmed`), and records the outcome on the
18669
+ * deposit's ledger operation when there is one. In the background: never
18670
+ * throws and never delays the deposit. A missed notice only leaves the
18671
+ * provider on its own schedule.
18672
+ */
18673
+ announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18674
+ try {
18675
+ if (evidence.transfer !== "confirmed") return;
18676
+ const agent = this.agents.get(evidence.agentId);
18677
+ const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
18678
+ if (!agent?.depositConfirmed || !movement) return;
18679
+ const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
18680
+ if (this.announcedDeposits.has(key2)) return;
18681
+ this.announcedDeposits.add(key2);
18682
+ if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18683
+ const legKey = `agent:${evidence.agentId}`;
18684
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18685
+ try {
18686
+ ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18687
+ } catch {
18688
+ }
18689
+ });
18690
+ } catch {
18691
+ }
18692
+ }
17443
18693
  noteFundingRefresh(key2, armed) {
17444
18694
  this.recoveredFundingReads.delete(key2);
17445
18695
  this.recoveredFundingReads.set(key2, armed);
@@ -17928,6 +19178,14 @@ var OwneySDK = class {
17928
19178
  return hash2;
17929
19179
  },
17930
19180
  ensureChain: (id) => this.ensureSwapChain(id),
19181
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
19182
+ // page cannot also hide that it landed (ROUT-726).
19183
+ readWrappedBalance: () => publicClient.readContract({
19184
+ address: wrapper.address,
19185
+ abi: ERC20_ALLOWANCE_ABI,
19186
+ functionName: "balanceOf",
19187
+ args: [walletAddress]
19188
+ }),
17931
19189
  // Read through the same public client as every other sizing input, so
17932
19190
  // a wallet sitting on the wrong chain cannot answer for this one.
17933
19191
  readAllowance: (token, spender) => publicClient.readContract({
@@ -18373,8 +19631,17 @@ var OwneySDK = class {
18373
19631
  * second half of `swapAndDeposit` on its own. Cleared only once the deposit
18374
19632
  * has actually gone through — a failure here leaves the record in place so it
18375
19633
  * can be offered again rather than silently dropped.
19634
+ *
19635
+ * The record does not remember `excludeAgentIds`, on purpose: the caller must
19636
+ * pass the CURRENT list, because the user's choice may have changed since the
19637
+ * swap (a deposit reads it fresh each time). Without it, a record with no
19638
+ * `agentId` splits across every eligible agent. When the list leaves nobody to
19639
+ * fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
19640
+ * before the wallet is touched and keeps the record.
19641
+ *
19642
+ * @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
18376
19643
  */
18377
- async completePendingDeposit(id) {
19644
+ async completePendingDeposit(id, options = {}) {
18378
19645
  const entry = listPendingDeposits().find((p) => p.id === id);
18379
19646
  if (!entry) {
18380
19647
  throw new OwneyError(
@@ -18383,6 +19650,12 @@ var OwneySDK = class {
18383
19650
  { id }
18384
19651
  );
18385
19652
  }
19653
+ this.assertDepositAgentsRemain(
19654
+ entry.chainId,
19655
+ entry.symbol,
19656
+ entry.agentId,
19657
+ options.excludeAgentIds
19658
+ );
18386
19659
  await this.ensureSwapChain(entry.chainId);
18387
19660
  const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
18388
19661
  const amount = token ? await this.settleSwapDepositAmount(
@@ -18395,6 +19668,7 @@ var OwneySDK = class {
18395
19668
  amount,
18396
19669
  asset: entry.symbol,
18397
19670
  ...entry.agentId ? { agentId: entry.agentId } : {},
19671
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18398
19672
  // The swap's own funding-ledger operation; older records have none.
18399
19673
  ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
18400
19674
  ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
@@ -18623,6 +19897,7 @@ var OwneySDK = class {
18623
19897
  async swapAndDeposit(options) {
18624
19898
  const state = this.requireState();
18625
19899
  options.assertCurrent?.();
19900
+ this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
18626
19901
  if (options.agentId) {
18627
19902
  this.validateAssetSupport(
18628
19903
  this.getAgent(options.agentId),
@@ -18724,6 +19999,7 @@ var OwneySDK = class {
18724
19999
  amount,
18725
20000
  asset: options.to.symbol,
18726
20001
  ...options.agentId ? { agentId: options.agentId } : {},
20002
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18727
20003
  ...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
18728
20004
  ...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
18729
20005
  ...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
@@ -19263,7 +20539,7 @@ var OwneySDK = class {
19263
20539
  "A withdrawal request is already running.",
19264
20540
  { chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
19265
20541
  );
19266
- const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
20542
+ const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
19267
20543
  const attempted = /* @__PURE__ */ new Set();
19268
20544
  this.withdrawalSubmissions.add(submissionKey);
19269
20545
  let ledgerOp;
@@ -19734,6 +21010,8 @@ var OwneySDK = class {
19734
21010
  progress({ ...evidence, transfer: "failed", delivery: "failed" });
19735
21011
  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)
19736
21012
  ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
21013
+ 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"))
21014
+ ledgerLeg?.(evidence, error.code);
19737
21015
  settled2({ settled: "threw", evidence });
19738
21016
  throw error;
19739
21017
  }
@@ -19841,7 +21119,7 @@ var OwneySDK = class {
19841
21119
  serverLegs.set(planned.agentId, leg);
19842
21120
  }
19843
21121
  };
19844
- const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
21122
+ const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
19845
21123
  const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
19846
21124
  if (!amount) {
19847
21125
  const results2 = {};
@@ -20241,9 +21519,10 @@ var OwneySDK = class {
20241
21519
  }
20242
21520
  async getBalances(agentId, options) {
20243
21521
  if (agentId) {
20244
- const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
21522
+ const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20245
21523
  const asset = options?.asset;
20246
21524
  const agent = this.getAgent(agentId);
21525
+ const state = this.readStateFor(agentId, scope);
20247
21526
  const result = await this.readAgent(
20248
21527
  agent,
20249
21528
  "balances",
@@ -20274,10 +21553,10 @@ var OwneySDK = class {
20274
21553
  async readAggregatedBalances(options, portfolio = false) {
20275
21554
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20276
21555
  const asset = options?.asset;
20277
- const readBalance = (read2) => read2.state === state ? this.readAgent(
21556
+ const readBalance = (read2) => !read2.offChain ? this.readAgent(
20278
21557
  read2.agent,
20279
21558
  "balances",
20280
- () => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
21559
+ () => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
20281
21560
  asset ? { asset } : null
20282
21561
  ) : this.readAgent(
20283
21562
  read2.agent,
@@ -20287,7 +21566,7 @@ var OwneySDK = class {
20287
21566
  );
20288
21567
  let totalBalance = 0;
20289
21568
  const results = {};
20290
- const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
21569
+ const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
20291
21570
  const balanceResults = await Promise.allSettled(
20292
21571
  entries.map(async ([id, read2]) => {
20293
21572
  const { agent } = read2;
@@ -20342,10 +21621,11 @@ var OwneySDK = class {
20342
21621
  const chainId = this.requireChainId();
20343
21622
  if (agentId) {
20344
21623
  const agent = this.getAgent(agentId);
21624
+ const readState = this.readStateFor(agentId, state);
20345
21625
  return this.readAgent(
20346
21626
  agent,
20347
21627
  "earnings",
20348
- () => agent.getEarnings(state, chainId)
21628
+ () => agent.getEarnings(readState, chainId)
20349
21629
  );
20350
21630
  }
20351
21631
  return this.aggregateEarnings(
@@ -20354,7 +21634,7 @@ var OwneySDK = class {
20354
21634
  read2.agent,
20355
21635
  "earnings",
20356
21636
  () => read2.agent.getEarnings(read2.state, read2.chainId),
20357
- read2.state === state ? null : { chainId: read2.chainId }
21637
+ read2.offChain ? { chainId: read2.chainId } : null
20358
21638
  )
20359
21639
  );
20360
21640
  }
@@ -20365,13 +21645,13 @@ var OwneySDK = class {
20365
21645
  async refreshEarnings(agentId) {
20366
21646
  const state = this.requireState();
20367
21647
  const chainId = this.requireChainId();
20368
- const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
21648
+ const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
20369
21649
  agent,
20370
21650
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
20371
21651
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
20372
- readState === state ? null : { chainId: readChain }
21652
+ offChain ? { chainId: readChain } : null
20373
21653
  );
20374
- if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
21654
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
20375
21655
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
20376
21656
  }
20377
21657
  async aggregateEarnings(entries, read2) {
@@ -20439,7 +21719,7 @@ var OwneySDK = class {
20439
21719
  for (const agent of agents) {
20440
21720
  for (const legChainId of chainIds) {
20441
21721
  if (agentRunsOn(agent, legChainId))
20442
- legs.push({ agent, legChainId, legState: state });
21722
+ legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
20443
21723
  }
20444
21724
  }
20445
21725
  if (!agentId) {
@@ -20479,22 +21759,21 @@ var OwneySDK = class {
20479
21759
  assets: []
20480
21760
  };
20481
21761
  }
21762
+ const readState = this.readStateFor(agentId, state);
20482
21763
  return this.readAgent(
20483
21764
  agent,
20484
21765
  "dailyEarnings",
20485
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21766
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
20486
21767
  { days, tokenSymbol }
20487
21768
  );
20488
21769
  }
20489
- const entries = [...this.getActiveAgents().entries()].filter(
20490
- ([, agent]) => agent.getDailyEarnings
20491
- );
21770
+ const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
20492
21771
  const settled2 = await Promise.allSettled(
20493
21772
  entries.map(
20494
- ([, agent]) => this.readAgent(
21773
+ ({ agent, state: readState }) => this.readAgent(
20495
21774
  agent,
20496
21775
  "dailyEarnings",
20497
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21776
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
20498
21777
  { days, tokenSymbol }
20499
21778
  )
20500
21779
  )
@@ -20543,7 +21822,7 @@ var OwneySDK = class {
20543
21822
  `Agent ${agent.id} does not support pool customization`
20544
21823
  );
20545
21824
  }
20546
- await agent.setPoolSelection(params.selection);
21825
+ await agent.setPoolSelection(params.selection, this.state ?? void 0);
20547
21826
  }
20548
21827
  /**
20549
21828
  * The pool selection saved on the user's account (ROUT-650), so the Pools
@@ -20566,6 +21845,15 @@ var OwneySDK = class {
20566
21845
  assets: params.assets
20567
21846
  });
20568
21847
  }
21848
+ /**
21849
+ * The agents a person can customize pools for: registered, enabled, and
21850
+ * able to list a pool catalogue. Waits for agent initialization, so an agent
21851
+ * the organization disabled is known and left out.
21852
+ */
21853
+ async getPoolCustomizationAgents() {
21854
+ await this.ensureAgentsInitialized();
21855
+ return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
21856
+ }
20569
21857
  async getAccountApy({
20570
21858
  agentId,
20571
21859
  days,
@@ -20577,17 +21865,23 @@ var OwneySDK = class {
20577
21865
  const scopeChainId = scope === "all" ? null : scope;
20578
21866
  if (agentId) {
20579
21867
  const agent = this.getAgent(agentId);
20580
- return this.readAgent(
21868
+ const readState = this.readStateFor(agentId, state);
21869
+ const accountApy = await this.readAgent(
20581
21870
  agent,
20582
21871
  "accountApy",
20583
- () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
21872
+ () => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
20584
21873
  { days, tokenSymbol, scopeChainId }
20585
21874
  );
21875
+ return this.enrichApyHistory(
21876
+ accountApy,
21877
+ agentId,
21878
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21879
+ tokenSymbol
21880
+ );
20586
21881
  }
20587
- const entries = scopeChainId === void 0 ? [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })) : this.portfolioReads(state, chainId).filter((read2) => read2.state === state || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
21882
+ const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
20588
21883
  const reads = await Promise.all(
20589
- entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
20590
- const offChain = readState !== state;
21884
+ entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
20591
21885
  const pair = Promise.all([
20592
21886
  this.readAgent(
20593
21887
  agent,
@@ -20619,7 +21913,12 @@ var OwneySDK = class {
20619
21913
  const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
20620
21914
  const results = {};
20621
21915
  for (const [id, apy] of apyResults) {
20622
- results[id] = apy;
21916
+ results[id] = await this.enrichApyHistory(
21917
+ apy,
21918
+ id,
21919
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21920
+ tokenSymbol
21921
+ );
20623
21922
  }
20624
21923
  const balances = {};
20625
21924
  for (const [id, bal] of balanceResults) {
@@ -20649,6 +21948,36 @@ var OwneySDK = class {
20649
21948
  history
20650
21949
  };
20651
21950
  }
21951
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
21952
+ const history = accountApy.history;
21953
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
21954
+ const incentives = await fetchApyIncentives(
21955
+ this.apiKey,
21956
+ {
21957
+ walletAddress: accountApy.walletAddress,
21958
+ agentId,
21959
+ chainId,
21960
+ asset: tokenSymbol,
21961
+ from: history[0].date,
21962
+ to: history[history.length - 1].date
21963
+ },
21964
+ this.routingApiBaseUrl
21965
+ );
21966
+ if (incentives.length === 0) return accountApy;
21967
+ const byDate = /* @__PURE__ */ new Map();
21968
+ for (const { date, ...incentive } of incentives) {
21969
+ const entries = byDate.get(date) ?? [];
21970
+ entries.push(incentive);
21971
+ byDate.set(date, entries);
21972
+ }
21973
+ return {
21974
+ ...accountApy,
21975
+ history: history.map((point) => {
21976
+ const pointIncentives = byDate.get(point.date);
21977
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
21978
+ })
21979
+ };
21980
+ }
20652
21981
  /**
20653
21982
  * Get transaction history for a specific agent, or all agents.
20654
21983
  *
@@ -20676,7 +22005,7 @@ var OwneySDK = class {
20676
22005
  for (const agent of agents) {
20677
22006
  for (const legChainId of chainIds) {
20678
22007
  if (agentRunsOn(agent, legChainId))
20679
- legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
22008
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
20680
22009
  }
20681
22010
  }
20682
22011
  if (!agentId) {
@@ -20720,7 +22049,8 @@ var OwneySDK = class {
20720
22049
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20721
22050
  if (agentId) {
20722
22051
  const agent = this.getAgent(agentId);
20723
- const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
22052
+ const readState = this.readStateFor(agentId, state);
22053
+ const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
20724
22054
  assertCurrent();
20725
22055
  return page;
20726
22056
  }
@@ -20734,10 +22064,11 @@ var OwneySDK = class {
20734
22064
  }
20735
22065
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
20736
22066
  try {
22067
+ const readState = this.readStateFor(agent.id, state);
20737
22068
  const page = await this.readAgent(
20738
22069
  agent,
20739
22070
  "history",
20740
- () => agent.getHistory(state, chainId, agentFilters),
22071
+ () => agent.getHistory(readState, chainId, agentFilters),
20741
22072
  agentFilters
20742
22073
  );
20743
22074
  return { agentId: agent.id, page };
@@ -20795,20 +22126,20 @@ var OwneySDK = class {
20795
22126
  const chainId = this.requireChainId();
20796
22127
  if (agentId) {
20797
22128
  const agent = this.getAgent(agentId);
22129
+ const readState = this.readStateFor(agentId, state);
20798
22130
  return this.readAgent(
20799
22131
  agent,
20800
22132
  "profile",
20801
- () => agent.getUserProfile(state, chainId)
22133
+ () => agent.getUserProfile(readState, chainId)
20802
22134
  );
20803
22135
  }
20804
22136
  const results = {};
20805
- const entries = [...this.getActiveAgents().entries()];
20806
22137
  const profileResults = await Promise.all(
20807
- entries.map(async ([id, agent]) => {
22138
+ this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
20808
22139
  const p = await this.readAgent(
20809
22140
  agent,
20810
22141
  "profile",
20811
- () => agent.getUserProfile(state, chainId)
22142
+ () => agent.getUserProfile(readState, chainId)
20812
22143
  );
20813
22144
  return [id, p];
20814
22145
  })
@@ -21018,10 +22349,11 @@ var OwneySDK = class {
21018
22349
  const entries = [...activeAgents.entries()];
21019
22350
  const balanceResults = await Promise.allSettled(
21020
22351
  entries.map(async ([id, agent]) => {
22352
+ const readState = this.readStateFor(id, state);
21021
22353
  const b = await this.readAgent(
21022
22354
  agent,
21023
22355
  "balances",
21024
- () => agent.getBalances(state, chainId)
22356
+ () => agent.getBalances(readState, chainId)
21025
22357
  );
21026
22358
  return [id, b.positions ?? []];
21027
22359
  })
@@ -21307,5 +22639,6 @@ function createOwneySIWX(config) {
21307
22639
  saveWithdrawSwap,
21308
22640
  setOwneyDebug,
21309
22641
  subscribeWithdrawSwaps,
22642
+ switchWalletConnectChain,
21310
22643
  updateWithdrawSwap
21311
22644
  });