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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -452,6 +452,35 @@ function debugLog(scope, message, data) {
452
452
  // src/lib/routing-api.ts
453
453
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
454
454
  var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
455
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
456
+ const query2 = new URLSearchParams({
457
+ walletAddress: input.walletAddress,
458
+ agentId: input.agentId,
459
+ chainId: String(input.chainId),
460
+ asset: input.asset.toUpperCase(),
461
+ from: input.from,
462
+ to: input.to
463
+ });
464
+ try {
465
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
466
+ headers: {
467
+ Accept: "application/json",
468
+ "x-owney-api-key": apiKey
469
+ }
470
+ });
471
+ if (!response.ok) return [];
472
+ const body = await response.json();
473
+ if (!body.success || !Array.isArray(body.data)) return [];
474
+ return body.data.filter(
475
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
476
+ );
477
+ } catch (error) {
478
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
479
+ error: error instanceof Error ? error.message : String(error)
480
+ });
481
+ return [];
482
+ }
483
+ }
455
484
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
456
485
  const url = `${baseUrl}/api/v1/agent/org-config`;
457
486
  try {
@@ -982,7 +1011,7 @@ var SnapshotHistory = class {
982
1011
  };
983
1012
 
984
1013
  // src/lib/funding-ledger.ts
985
- var SDK_VERSION = "0.7.32-beta.5";
1014
+ var SDK_VERSION = "0.7.32-beta.7";
986
1015
  var SCOPE2 = "funding-ledger";
987
1016
  var REQUEST_TIMEOUT_MS2 = 5e3;
988
1017
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -2292,7 +2321,7 @@ var CHAIN_NAMES = {
2292
2321
  function chainName(chainId) {
2293
2322
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2294
2323
  }
2295
- var SETTLE_TIMEOUT_MS = 8e3;
2324
+ var SETTLE_TIMEOUT_MS = 15e3;
2296
2325
  var POLL_INTERVAL_MS = 200;
2297
2326
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2298
2327
  async function readChainId(pub) {
@@ -3831,19 +3860,31 @@ function mapAvailablePools(raw2) {
3831
3860
  for (const [token, entry] of Object.entries(byToken ?? {})) {
3832
3861
  for (const pool of entry?.pools ?? []) {
3833
3862
  if (!pool?.name) continue;
3863
+ const link = pool.info?.url || pool.info?.link || null;
3864
+ const address = vaultAddressFromLink(link);
3834
3865
  result.push({
3835
3866
  chainId,
3836
3867
  token,
3837
3868
  name: pool.name,
3838
3869
  apy: pool.info?.combined_apy ?? null,
3839
3870
  tvlUsd: pool.info?.tvlUsd ?? null,
3840
- link: pool.info?.link ?? null
3871
+ link,
3872
+ ...address !== void 0 && { address }
3841
3873
  });
3842
3874
  }
3843
3875
  }
3844
3876
  }
3845
3877
  return result;
3846
3878
  }
3879
+ var VAULT_IN_PATH = /\/(?:vault|lend)\/(0x[0-9a-fA-F]{40})(?=\/|$)/;
3880
+ function vaultAddressFromLink(link) {
3881
+ if (!link) return void 0;
3882
+ try {
3883
+ return new URL(link).pathname.match(VAULT_IN_PATH)?.[1];
3884
+ } catch {
3885
+ return void 0;
3886
+ }
3887
+ }
3847
3888
  function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
3848
3889
  const wanted = asset.toUpperCase();
3849
3890
  const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
@@ -4432,11 +4473,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
4432
4473
  if (typeof window === "undefined") return;
4433
4474
  const internals = sdk;
4434
4475
  const original = internals.authenticateUser.bind(internals);
4435
- internals.authenticateUser = async () => {
4476
+ let inFlight2 = null;
4477
+ const authenticate = async () => {
4436
4478
  if (internals.authenticatedUserId !== null) return;
4437
4479
  const address = internals.walletClient?.account?.address;
4438
- const chainId = internals.currentChainId;
4439
- if (address && chainId) {
4480
+ const chainId = internals.currentChainId ?? 0;
4481
+ if (address) {
4440
4482
  const cached = readSession(address, chainId);
4441
4483
  if (cached) {
4442
4484
  internals.httpClient.setAuthToken(cached.token);
@@ -4448,9 +4490,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
4448
4490
  }
4449
4491
  await original();
4450
4492
  const newAddress = internals.walletClient?.account?.address;
4451
- const newChainId = internals.currentChainId;
4493
+ const newChainId = internals.currentChainId ?? 0;
4452
4494
  const newToken = internals.httpClient.authToken;
4453
- if (newAddress && newChainId && newToken) {
4495
+ if (newAddress && newToken) {
4454
4496
  writeSession(newAddress, newChainId, {
4455
4497
  token: newToken,
4456
4498
  userId: internals.authenticatedUserId,
@@ -4459,6 +4501,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
4459
4501
  });
4460
4502
  }
4461
4503
  };
4504
+ internals.authenticateUser = () => {
4505
+ const address = internals.walletClient?.account?.address?.toLowerCase();
4506
+ if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
4507
+ const promise = authenticate().finally(() => {
4508
+ if (inFlight2?.promise === promise) inFlight2 = null;
4509
+ });
4510
+ inFlight2 = { address, promise };
4511
+ return promise;
4512
+ };
4462
4513
  }
4463
4514
  // --- Private helpers ---
4464
4515
  getAddress() {
@@ -4691,12 +4742,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
4691
4742
  }
4692
4743
  // --- IAgent: Account lifecycle ---
4693
4744
  async activateAgent(state, chainId) {
4745
+ const startedAt = Date.now();
4694
4746
  try {
4695
4747
  debugLog("zyfai:activation", "starting", {
4696
4748
  walletAddress: state.walletAddress,
4697
4749
  chainId
4698
4750
  });
4699
4751
  await this.connectAuth(state, chainId);
4752
+ debugLog("zyfai:activation", "signed in", {
4753
+ ms: Date.now() - startedAt
4754
+ });
4700
4755
  const validChainId = isValidChainId(chainId);
4701
4756
  await Promise.all([
4702
4757
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -4707,7 +4762,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
4707
4762
  // validator, so pool-wallet users see no prompt. Non-fatal.
4708
4763
  this.ensureSessionKeyIfDeployed(validChainId)
4709
4764
  ]);
4710
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
4765
+ debugLog("zyfai:activation", "completed", {
4766
+ chainId: validChainId,
4767
+ ms: Date.now() - startedAt
4768
+ });
4711
4769
  } catch (error) {
4712
4770
  throw error;
4713
4771
  }
@@ -6403,6 +6461,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6403
6461
  const generation = this.earningsGeneration;
6404
6462
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
6405
6463
  const raw2 = await this.sdk.getPortfolio(this.getAddress());
6464
+ debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
6406
6465
  const balance = mapBalances(raw2, validChainId, smartWallet);
6407
6466
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
6408
6467
  for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
@@ -6817,6 +6876,27 @@ import {
6817
6876
  } from "viem";
6818
6877
  import { base as base4 } from "viem/chains";
6819
6878
 
6879
+ // src/lib/wallet-rejection.ts
6880
+ var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
6881
+ function isWalletRejection(error) {
6882
+ let current = error;
6883
+ const seen = /* @__PURE__ */ new Set();
6884
+ while (current && typeof current === "object" && !seen.has(current)) {
6885
+ seen.add(current);
6886
+ const candidate = current;
6887
+ if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
6888
+ const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
6889
+ if (REJECTION_MESSAGE.test(message)) return true;
6890
+ const details = candidate.details;
6891
+ if (details && typeof details === "object") {
6892
+ const cause = details.cause;
6893
+ if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
6894
+ }
6895
+ current = candidate.cause;
6896
+ }
6897
+ return false;
6898
+ }
6899
+
6820
6900
  // src/agents/yieldseeker/yieldseeker.auth.ts
6821
6901
  import { SiweMessage, generateNonce } from "siwe";
6822
6902
  import {
@@ -7863,11 +7943,13 @@ function mapYieldseekerProfile(address, contexts) {
7863
7943
  protocols: [...protocols]
7864
7944
  };
7865
7945
  }
7866
- function mapYieldseekerAgentApy(stats) {
7946
+ function mapYieldseekerAgentApy(stats, days) {
7867
7947
  const perAsset = {};
7868
7948
  const all = [];
7869
7949
  for (const entry of stats) {
7870
- const expected = percent(entry.stats.expectedApy7d);
7950
+ const expected = percent(
7951
+ days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
7952
+ );
7871
7953
  if (!Number.isFinite(expected)) continue;
7872
7954
  perAsset[entry.asset] = expected;
7873
7955
  all.push(expected);
@@ -8046,6 +8128,15 @@ function sponsorError(message, safeToFallback, details = {}) {
8046
8128
  "yieldseeker"
8047
8129
  );
8048
8130
  }
8131
+ function cannotSignRawHash(error) {
8132
+ for (let current = error, depth = 0; current && depth < 5; depth++) {
8133
+ const code = current.code;
8134
+ if (code === -32602 || code === -32601 || code === 4200) return true;
8135
+ if (code === 4001) return false;
8136
+ current = current.cause;
8137
+ }
8138
+ return false;
8139
+ }
8049
8140
  function assertIntentFresh(expiresAt) {
8050
8141
  if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
8051
8142
  throw sponsorError(
@@ -8407,7 +8498,18 @@ async function submitEoa(input) {
8407
8498
  transport: custom3(input.state.provider)
8408
8499
  });
8409
8500
  input.assertCurrent?.();
8410
- const signature = await wallet.signMessage({ message: { raw: userOpHash } });
8501
+ let signature;
8502
+ try {
8503
+ signature = await wallet.signMessage({ message: { raw: userOpHash } });
8504
+ } catch (error) {
8505
+ if (cannotSignRawHash(error))
8506
+ throw sponsorError(
8507
+ "This wallet cannot sign the gas-free withdrawal.",
8508
+ true,
8509
+ { failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
8510
+ );
8511
+ throw error;
8512
+ }
8411
8513
  operation = { ...operation, signature };
8412
8514
  await assertOwnerSession(input.state, input.owner);
8413
8515
  assertIntentFresh(input.expiresAt);
@@ -8679,11 +8781,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
8679
8781
  var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
8680
8782
  var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
8681
8783
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
8784
+ var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
8785
+ var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
8786
+ var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
8787
+ var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
8682
8788
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
8683
8789
  var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
8684
8790
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
8685
8791
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
8686
8792
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
8793
+ function apyAsPercent(fraction) {
8794
+ if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
8795
+ return Number((fraction * 100).toPrecision(12));
8796
+ }
8797
+ function isActiveMemory(memory) {
8798
+ return !!memory && memory.isActive !== false && memory.isDeleted !== true;
8799
+ }
8800
+ function vaultOptionsKey(asset, includeUnavailable) {
8801
+ return `${asset}:${includeUnavailable ? "all" : "usable"}`;
8802
+ }
8803
+ function isManagedVaultList(memory) {
8804
+ return memory.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
8805
+ }
8806
+ function isLegacyPoolSelectionMemory(memory) {
8807
+ if (isManagedVaultList(memory) || typeof memory.content !== "string") return false;
8808
+ const content = memory.content.trim();
8809
+ return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
8810
+ }
8811
+ function uniqueAddresses(addresses) {
8812
+ const seen = /* @__PURE__ */ new Set();
8813
+ return addresses.filter((address) => {
8814
+ const key2 = address.toLowerCase();
8815
+ if (seen.has(key2)) return false;
8816
+ seen.add(key2);
8817
+ return true;
8818
+ });
8819
+ }
8820
+ function sameVaults(actual, expected) {
8821
+ const want = new Set(expected.map((address) => address.toLowerCase()));
8822
+ const got = new Set(actual.map((address) => address.toLowerCase()));
8823
+ return got.size === want.size && [...want].every((address) => got.has(address));
8824
+ }
8687
8825
  function isYieldseekerWalletCodeMissing(error) {
8688
8826
  for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
8689
8827
  const { name, message } = current;
@@ -8693,6 +8831,8 @@ function isYieldseekerWalletCodeMissing(error) {
8693
8831
  return false;
8694
8832
  }
8695
8833
  var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
8834
+ var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
8835
+ var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
8696
8836
  var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
8697
8837
  var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
8698
8838
  var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
@@ -8712,6 +8852,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
8712
8852
  var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
8713
8853
  var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
8714
8854
  var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
8855
+ var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
8715
8856
  var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
8716
8857
  var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
8717
8858
  function generateYieldseekerUsername() {
@@ -8804,9 +8945,31 @@ var YieldseekerAgent = class {
8804
8945
  walletContexts = /* @__PURE__ */ new Map();
8805
8946
  agentAccountReads = /* @__PURE__ */ new Map();
8806
8947
  reportedAccounts = /* @__PURE__ */ new Set();
8807
- // Slots whose verified agent is missing even from a re-read list, until the
8808
- // list cache window ends. Stops a re-read on every portfolio poll.
8948
+ // Slots whose verified agent is missing even from a re-read list (and could
8949
+ // not be reopened), with the error the lookup failed with, until the list
8950
+ // cache window ends. Stops a re-read and a reactivate on every portfolio poll.
8809
8951
  missingSlots = /* @__PURE__ */ new Map();
8952
+ // A remembered rate limit rethrown with the time left on its marker
8953
+ // (throwIfSlotMissing), mapped to the remembered error it copies, so
8954
+ // isMarkedSlotFailure still recognises it.
8955
+ rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
8956
+ // Slots whose verified agent Yieldseeker will never reopen (a reactivate
8957
+ // answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
8958
+ // slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
8959
+ // it is kept for the session, like unavailableSlots: reads and deposits get
8960
+ // it with no request until disconnect, or until a lookup selects an agent
8961
+ // for the slot.
8962
+ closedSlots = /* @__PURE__ */ new Map();
8963
+ // In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
8964
+ // shared by concurrent lookups of one slot.
8965
+ pendingReopens = /* @__PURE__ */ new Map();
8966
+ // Slots Yieldseeker will not give an agent this session (a reactivate answered
8967
+ // an active-agent limit), keyed by slotKey, with the provider's limit code.
8968
+ // Never expires: it answers without a request until disconnect.
8969
+ unavailableSlots = /* @__PURE__ */ new Map();
8970
+ // In-flight reactivates keyed by slotKey + agentId, shared by every caller
8971
+ // (a read-time reopen, deposits): one request however many ask.
8972
+ pendingReactivates = /* @__PURE__ */ new Map();
8810
8973
  // In-flight cache-bypassing list reads, shared by concurrent callers.
8811
8974
  freshListReads = /* @__PURE__ */ new Map();
8812
8975
  // Every contextKey computed this session; asset-only calls fall back to them.
@@ -8859,6 +9022,7 @@ var YieldseekerAgent = class {
8859
9022
  ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
8860
9023
  /** slotKey -> the last successful ledger rows and when they arrived. */
8861
9024
  lastLedgerRows = /* @__PURE__ */ new Map();
9025
+ /** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
8862
9026
  vaultOptions = /* @__PURE__ */ new Map();
8863
9027
  pendingVaultOptions = /* @__PURE__ */ new Map();
8864
9028
  assetApyStats = /* @__PURE__ */ new Map();
@@ -8915,6 +9079,121 @@ var YieldseekerAgent = class {
8915
9079
  this.pendingWalletStatus.set(key2, pending);
8916
9080
  return { ...await pending };
8917
9081
  }
9082
+ /**
9083
+ * Deposits go only to an agent Yieldseeker still has open. The session caches
9084
+ * the selected agent, so a tab left open can hold one Yieldseeker has since
9085
+ * closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
9086
+ * bypassing the cached wallet contexts, and:
9087
+ * - open, same wallet address: returns the context to deposit with;
9088
+ * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9089
+ * continues only when it is now open with the same address. Only the
9090
+ * verified record's agent is reopened: any other closed agent (a
9091
+ * superseded-wallet match, or a named agent with no verified record, also
9092
+ * when the accounts could not be read) refuses without a request;
9093
+ * - anything else refuses with nothing sent, before any progress event,
9094
+ * signature or callback. Every refusal carries `notSubmitted` and
9095
+ * `safeToFallback: false`, so no paid fallback runs.
9096
+ * A slot recorded unavailable (the active-agent limit) refuses at once with
9097
+ * no request. The reactivate goes through reactivateSlot, which shares one
9098
+ * request per slot and remembers a failure for the list-cache window, so
9099
+ * repeated deposits do not repeat it. A failed wallet read fails closed
9100
+ * (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
9101
+ * gate. A reactivate that fails keeps its error code
9102
+ * (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
9103
+ * failure). At the limit the slot is also recorded unavailable for the
9104
+ * session (see isSlotUnavailable). Session changes keep their own
9105
+ * NOT_CONNECTED error.
9106
+ */
9107
+ async assertAgentOpen(state, chainId, asset, context) {
9108
+ const generation = this.readGeneration;
9109
+ const agentId = context.agent.agentId;
9110
+ const agentWallet = context.wallet.walletAddress;
9111
+ const refusal = { notSubmitted: true, safeToFallback: false };
9112
+ const slot = this.slotKey(state, chainId, asset);
9113
+ const unavailable = this.unavailableSlots.get(slot);
9114
+ if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
9115
+ const readWallet = async () => {
9116
+ let fresh2;
9117
+ try {
9118
+ const answer = await this.walletRequest(
9119
+ state,
9120
+ chainId,
9121
+ this.agentPath(context, "wallet")
9122
+ );
9123
+ if (!answer?.agentWallet || !isAddress4(answer.agentWallet.walletAddress)) {
9124
+ throw this.invalidResponse("agent wallet");
9125
+ }
9126
+ fresh2 = answer.agentWallet;
9127
+ } catch (error) {
9128
+ this.assertSession(generation, chainId, asset);
9129
+ throw new OwneyError(
9130
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9131
+ "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
9132
+ {
9133
+ ...refusal,
9134
+ reason: "UNAVAILABLE",
9135
+ agentWallet,
9136
+ asset,
9137
+ cause: error instanceof Error ? error.message : String(error)
9138
+ },
9139
+ this.id
9140
+ );
9141
+ }
9142
+ this.assertSession(generation, chainId, asset);
9143
+ return fresh2;
9144
+ };
9145
+ let fresh = await readWallet();
9146
+ let reopened = false;
9147
+ if (fresh.deactivatedDate) {
9148
+ this.forgetAgentWallet(agentId);
9149
+ const accounts = await this.agentAccounts(state, chainId);
9150
+ this.assertSession(generation, chainId, asset);
9151
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
9152
+ if (!verified || verified.providerAgentId !== agentId) {
9153
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
9154
+ }
9155
+ let result;
9156
+ try {
9157
+ result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
9158
+ } catch (error) {
9159
+ this.assertSession(generation, chainId, asset);
9160
+ const failure = error instanceof OwneyError ? error : this.mapApiError(error);
9161
+ if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
9162
+ const { providerCode, reason } = failure.details ?? {};
9163
+ throw this.agentClosed(
9164
+ chainId,
9165
+ asset,
9166
+ agentId,
9167
+ typeof providerCode === "string" ? providerCode : void 0,
9168
+ { ...refusal, ...typeof reason === "string" ? { reason } : {} }
9169
+ );
9170
+ }
9171
+ throw new OwneyError(
9172
+ failure.code,
9173
+ `Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
9174
+ { ...failure.details, ...refusal, cause: failure.message },
9175
+ failure.agentId
9176
+ );
9177
+ }
9178
+ this.assertSession(generation, chainId, asset);
9179
+ if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
9180
+ this.forgetAgentWallet(agentId);
9181
+ fresh = await readWallet();
9182
+ if (fresh.deactivatedDate) {
9183
+ this.rememberMissingSlot(
9184
+ slot,
9185
+ generation,
9186
+ this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
9187
+ );
9188
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
9189
+ }
9190
+ reopened = true;
9191
+ }
9192
+ if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
9193
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
9194
+ }
9195
+ return reopened ? { ...context, wallet: fresh } : context;
9196
+ }
8918
9197
  /**
8919
9198
  * Deposits go only to a wallet whose identity is verified on chain (factory
8920
9199
  * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
@@ -9224,6 +9503,10 @@ var YieldseekerAgent = class {
9224
9503
  this.pendingSlotInvalidations.clear();
9225
9504
  this.knownContextKeys.clear();
9226
9505
  this.missingSlots.clear();
9506
+ this.closedSlots.clear();
9507
+ this.pendingReopens.clear();
9508
+ this.pendingReactivates.clear();
9509
+ this.unavailableSlots.clear();
9227
9510
  this.freshListReads.clear();
9228
9511
  this.balanceVaults.clear();
9229
9512
  this.pendingAgents.clear();
@@ -9251,11 +9534,43 @@ var YieldseekerAgent = class {
9251
9534
  this.planHistoryKeys.clear();
9252
9535
  this.lastLedgerRows.clear();
9253
9536
  }
9537
+ /**
9538
+ * Ready every asset's agent, `asset` first: a missing one is created and a
9539
+ * closed one reopened (2026-11-06). A slot Yieldseeker will never let the
9540
+ * user have (the agent limit, closed for good, missing with no way to
9541
+ * reopen) is rethrown with `details.permanent`, which refuses the connect.
9542
+ * A temporary failure (an API error or timeout) on another asset does not:
9543
+ * that slot answers again where it is needed. On the selected asset every
9544
+ * failure is thrown as before, without readying the rest, so a failed
9545
+ * sign-in never opens a second prompt.
9546
+ */
9254
9547
  async activateAgent(state, chainId, asset) {
9255
9548
  this.assertChain(chainId);
9256
9549
  const targetAsset = asset ?? "USDC";
9257
9550
  this.assertAsset(targetAsset);
9258
- await this.ensureAgent(state, chainId, targetAsset);
9551
+ const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
9552
+ for (const each of [targetAsset, ...others]) {
9553
+ try {
9554
+ await this.ensureAgent(state, chainId, each);
9555
+ } catch (error) {
9556
+ if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
9557
+ const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
9558
+ if (each === targetAsset || !temporary) throw error;
9559
+ debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
9560
+ code: error.code,
9561
+ statusCode: error.details?.statusCode
9562
+ });
9563
+ }
9564
+ }
9565
+ }
9566
+ /** The same failure, marked as one that will not go away this session. */
9567
+ permanentFailure(error) {
9568
+ const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
9569
+ return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
9570
+ }
9571
+ isSlotUnavailable(state, chainId, asset) {
9572
+ if (asset !== "USDC" && asset !== "WETH") return false;
9573
+ return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
9259
9574
  }
9260
9575
  async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
9261
9576
  this.assertChain(chainId);
@@ -9268,7 +9583,20 @@ var YieldseekerAgent = class {
9268
9583
  this.id
9269
9584
  );
9270
9585
  }
9271
- const context = await this.ensureAgent(state, chainId, asset);
9586
+ const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
9587
+ if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
9588
+ const { agentId, providerCode, reason } = error.details ?? {};
9589
+ throw this.agentClosed(
9590
+ chainId,
9591
+ asset,
9592
+ typeof agentId === "string" ? agentId : "",
9593
+ typeof providerCode === "string" ? providerCode : void 0,
9594
+ { notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
9595
+ );
9596
+ }
9597
+ throw error;
9598
+ });
9599
+ const context = await this.assertAgentOpen(state, chainId, asset, selected);
9272
9600
  await this.assertDepositWalletVerified(state, chainId, asset, context);
9273
9601
  const generation = this.readGeneration;
9274
9602
  const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
@@ -9458,15 +9786,14 @@ var YieldseekerAgent = class {
9458
9786
  if (timer) clearTimeout(timer);
9459
9787
  }
9460
9788
  };
9461
- const feeRateRead = amount === void 0 ? Promise.resolve(0) : boundedVerification(
9462
- (() => {
9463
- try {
9464
- return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9465
- } catch (error) {
9466
- return Promise.reject(error);
9467
- }
9468
- })().catch(() => void 0)
9469
- );
9789
+ const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
9790
+ try {
9791
+ return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9792
+ } catch (error) {
9793
+ return Promise.reject(error);
9794
+ }
9795
+ })().catch(() => void 0);
9796
+ const feeRateRead = boundedVerification(feeRateAnswer);
9470
9797
  const positionsRead = this.readWithdrawalPositions(state, chainId, context);
9471
9798
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
9472
9799
  const agentWallet = getAddress6(context.wallet.walletAddress);
@@ -9776,9 +10103,10 @@ var YieldseekerAgent = class {
9776
10103
  }
9777
10104
  const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
9778
10105
  const availableForOwner = ownerFunds.available;
9779
- const feeRate = feeRateBps ?? 0;
9780
- const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9781
10106
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10107
+ const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
10108
+ this.assertSession(generation, chainId, asset);
10109
+ const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9782
10110
  if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
9783
10111
  this.invalidateFundingRead(state, chainId, asset);
9784
10112
  if (amount === void 0 && positionsStatus !== "empty")
@@ -10032,7 +10360,7 @@ var YieldseekerAgent = class {
10032
10360
  positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
10033
10361
  const needsInventory = !proof.inventoryComplete;
10034
10362
  if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
10035
- const catalog = await this.loadVaultOptions(asset).catch(() => []);
10363
+ const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
10036
10364
  const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && isAddress4(o.address));
10037
10365
  if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
10038
10366
  for (const option of eligible) {
@@ -10108,7 +10436,8 @@ var YieldseekerAgent = class {
10108
10436
  const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
10109
10437
  const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
10110
10438
  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()));
10111
- for (const option of this.vaultOptions.get(context.asset)?.value ?? []) {
10439
+ const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
10440
+ for (const option of cachedOptions?.value ?? []) {
10112
10441
  if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !isAddress4(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
10113
10442
  hints.set(option.address.toLowerCase(), {
10114
10443
  vaultOption: option,
@@ -10321,7 +10650,7 @@ var YieldseekerAgent = class {
10321
10650
  assertReadCurrent();
10322
10651
  return proof(true);
10323
10652
  }
10324
- const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
10653
+ const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
10325
10654
  assertReadCurrent();
10326
10655
  const eligible = /* @__PURE__ */ new Map();
10327
10656
  for (const option of catalog ?? []) {
@@ -10464,8 +10793,37 @@ var YieldseekerAgent = class {
10464
10793
  }
10465
10794
  return false;
10466
10795
  }
10796
+ /**
10797
+ * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10798
+ * it now instead of on its next 30-minute check. Yieldseeker decides whether
10799
+ * anything moves (the funding minimum, a deployed agent, no manual
10800
+ * withdrawal in the last hour). Uses the agent this session already knows
10801
+ * for the asset and the saved sign-in only: never prompts, never retries,
10802
+ * never throws.
10803
+ */
10804
+ async depositConfirmed(state, chainId, evidence) {
10805
+ try {
10806
+ const asset = String(evidence.token).toUpperCase();
10807
+ if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10808
+ return { notified: false, reason: "UNSUPPORTED" };
10809
+ const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10810
+ if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10811
+ return { notified: false, reason: "NO_AGENT" };
10812
+ if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
10813
+ await this.walletRequest(
10814
+ state,
10815
+ chainId,
10816
+ this.agentPath(context, "deposit-made"),
10817
+ { method: "POST", body: {}, promptless: true }
10818
+ );
10819
+ return { notified: true };
10820
+ } catch (error) {
10821
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
10822
+ }
10823
+ }
10467
10824
  async getFundingWallet(state, chainId, asset) {
10468
10825
  this.assertAsset(asset);
10826
+ this.throwIfSlotUnavailable(state, chainId, asset);
10469
10827
  const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10470
10828
  if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
10471
10829
  return context.wallet.walletAddress;
@@ -10526,7 +10884,7 @@ var YieldseekerAgent = class {
10526
10884
  });
10527
10885
  const catalog = await Promise.all(
10528
10886
  [...new Set(contexts.map((context) => context.asset))].map(
10529
- (contextAsset) => this.loadVaultOptions(contextAsset)
10887
+ (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
10530
10888
  )
10531
10889
  );
10532
10890
  const vaultAddresses = new Set(
@@ -10551,11 +10909,11 @@ var YieldseekerAgent = class {
10551
10909
  );
10552
10910
  }
10553
10911
  async getAgentApy(days, options) {
10554
- if (!this.supportsAgentApyPeriod(days)) {
10912
+ if (days === "14D") {
10555
10913
  throw new OwneyError(
10556
10914
  "AGENT_APY_PERIOD_UNSUPPORTED",
10557
10915
  `Yieldseeker does not provide a representative ${days} strategy APY.`,
10558
- { days, supportedDays: ["7D"] },
10916
+ { days, supportedDays: ["7D", "30D"] },
10559
10917
  this.id
10560
10918
  );
10561
10919
  }
@@ -10568,10 +10926,10 @@ var YieldseekerAgent = class {
10568
10926
  return { asset, stats: await this.loadAssetApyStats(asset) };
10569
10927
  })
10570
10928
  );
10571
- return mapYieldseekerAgentApy(values);
10929
+ return mapYieldseekerAgentApy(values, days);
10572
10930
  }
10573
10931
  supportsAgentApyPeriod(days) {
10574
- return days === "7D";
10932
+ return days === "7D" || days === "30D";
10575
10933
  }
10576
10934
  async loadAssetApyStats(asset) {
10577
10935
  const cached = this.assetApyStats.get(asset);
@@ -10583,7 +10941,7 @@ var YieldseekerAgent = class {
10583
10941
  `/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
10584
10942
  ).then((response) => {
10585
10943
  const stats = response?.assetApyStats;
10586
- 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)) {
10944
+ 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)) {
10587
10945
  throw this.invalidResponse("asset APY statistics");
10588
10946
  }
10589
10947
  this.assetApyStats.set(asset, {
@@ -10595,27 +10953,321 @@ var YieldseekerAgent = class {
10595
10953
  this.pendingAssetApyStats.set(asset, request2);
10596
10954
  return request2;
10597
10955
  }
10598
- async loadVaultOptions(asset) {
10599
- const cached = this.vaultOptions.get(asset);
10956
+ /**
10957
+ * The deposit-time Pools step's catalogue: every vault Yieldseeker lists
10958
+ * for a new agent on `asset` on Base, grouped by provider (the provider is
10959
+ * both `protocolId` and `name`). Nothing is filtered on our side, on
10960
+ * liquidity, size or provider. `strategy` is accepted for the IAgent
10961
+ * contract and ignored.
10962
+ */
10963
+ async getPoolCatalog(params) {
10964
+ const asset = params.asset.toUpperCase();
10965
+ this.assertAsset(asset);
10966
+ const byProvider = /* @__PURE__ */ new Map();
10967
+ for (const vault of await this.loadVaultOptions(asset)) {
10968
+ const pools = byProvider.get(vault.provider) ?? [];
10969
+ pools.push({
10970
+ chainId: 8453,
10971
+ token: asset,
10972
+ name: vault.name,
10973
+ apy: apyAsPercent(vault.totalApy),
10974
+ tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
10975
+ link: null,
10976
+ address: vault.address
10977
+ });
10978
+ byProvider.set(vault.provider, pools);
10979
+ }
10980
+ return [...byProvider].map(([provider, pools]) => ({
10981
+ protocolId: provider,
10982
+ name: provider,
10983
+ logo: null,
10984
+ pools
10985
+ }));
10986
+ }
10987
+ /**
10988
+ * The asset's vaults on Base. By default only those a new agent can use:
10989
+ * Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
10990
+ * among them), gated or can't use, so the picker follows its list
10991
+ * (2026-11-04). `includeUnavailable` adds those back, for anything about
10992
+ * money an agent may still hold in one: withdrawals and activity.
10993
+ */
10994
+ async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
10995
+ const key2 = vaultOptionsKey(asset, includeUnavailable);
10996
+ const cached = this.vaultOptions.get(key2);
10600
10997
  if (cached && cached.expiresAt > Date.now()) return cached.value;
10601
- const pending = this.pendingVaultOptions.get(asset);
10998
+ const pending = this.pendingVaultOptions.get(key2);
10602
10999
  if (pending) return pending;
10603
11000
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
10604
11001
  const request2 = this.api.request(
10605
- `/chains/8453/assets/${metadata.address}/vault-options`
11002
+ `/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
10606
11003
  ).then((response) => {
10607
11004
  if (!Array.isArray(response?.vaultOptions)) {
10608
11005
  throw this.invalidResponse("vault options");
10609
11006
  }
10610
- this.vaultOptions.set(asset, {
11007
+ this.vaultOptions.set(key2, {
10611
11008
  expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
10612
11009
  value: response.vaultOptions
10613
11010
  });
10614
11011
  return response.vaultOptions;
10615
- }).finally(() => this.pendingVaultOptions.delete(asset));
10616
- this.pendingVaultOptions.set(asset, request2);
11012
+ }).finally(() => this.pendingVaultOptions.delete(key2));
11013
+ this.pendingVaultOptions.set(key2, request2);
10617
11014
  return request2;
10618
11015
  }
11016
+ /**
11017
+ * Save the user's Yieldseeker picks as the agent's managed vault list, then
11018
+ * read the rules back before any money moves. Each asset has its own agent,
11019
+ * so each is saved on its own. `pools` and `availablePools` hold vault
11020
+ * addresses.
11021
+ *
11022
+ * - Only Base entries are ours. An asset with no picks whose entries showed
11023
+ * no vault is skipped and nothing is sent.
11024
+ * - Some vaults picked: the managed list names them. Saving it again
11025
+ * replaces it, so there is only ever one.
11026
+ * - None picked (vaults shown): the managed list names no vault, and the
11027
+ * rules must read back as an empty allow-list. Yieldseeker then keeps the
11028
+ * agent's money out of every vault, as Zyfai does with an empty pool list,
11029
+ * and the next Pools step reads "none". Only an agent that already exists
11030
+ * is written: one is never created just to hold "none".
11031
+ * - Every vault picked: the managed list is deleted, and no allow-list may
11032
+ * remain, so vaults Yieldseeker adds later are allowed too.
11033
+ * - A free-text allow-list we saved before the managed list existed is
11034
+ * deleted once the new state is written. A failed delete does not fail the
11035
+ * save; it is debug-logged, and the read-back decides.
11036
+ * - A read-back that differs puts the previous managed list back (or deletes
11037
+ * the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
11038
+ * it back fails too, that is still the error thrown. An old free-text list
11039
+ * already deleted is not put back.
11040
+ * - An agent already holding the most active memories, none of them ours,
11041
+ * throws POOL_SELECTION_RULE_LIMIT before anything is written.
11042
+ *
11043
+ * Always Base, whichever chain the wallet is connected on.
11044
+ */
11045
+ async setPoolSelection(selection, state) {
11046
+ if (!state) {
11047
+ throw new OwneyError(
11048
+ "NOT_CONNECTED",
11049
+ "Connect a wallet before saving Yieldseeker pool picks.",
11050
+ void 0,
11051
+ this.id
11052
+ );
11053
+ }
11054
+ const byAsset = /* @__PURE__ */ new Map();
11055
+ for (const entry of selection.selections) {
11056
+ if (entry.chainId !== 8453) continue;
11057
+ this.assertAsset(entry.asset);
11058
+ const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
11059
+ group.picked.push(...entry.pools);
11060
+ group.shown.push(...entry.availablePools);
11061
+ byAsset.set(entry.asset, group);
11062
+ }
11063
+ for (const [asset, group] of byAsset) {
11064
+ const picks = uniqueAddresses(group.picked);
11065
+ const shown = uniqueAddresses(group.shown);
11066
+ if (picks.length === 0 && shown.length === 0) continue;
11067
+ const picked = new Set(picks.map((address) => address.toLowerCase()));
11068
+ const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11069
+ await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11070
+ }
11071
+ }
11072
+ async savePoolPicks(state, asset, picks, everyVaultPicked) {
11073
+ const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11074
+ if (!context) {
11075
+ debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11076
+ return;
11077
+ }
11078
+ const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11079
+ const managed = active.find(isManagedVaultList);
11080
+ const legacy = active.filter(isLegacyPoolSelectionMemory);
11081
+ const writing = !everyVaultPicked;
11082
+ if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
11083
+ throw new OwneyError(
11084
+ "POOL_SELECTION_RULE_LIMIT",
11085
+ `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.`,
11086
+ { asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
11087
+ this.id
11088
+ );
11089
+ }
11090
+ const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
11091
+ const change = { previous: managed, written: false };
11092
+ if (content === void 0) {
11093
+ if (managed) {
11094
+ await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
11095
+ method: "POST"
11096
+ });
11097
+ change.written = true;
11098
+ }
11099
+ } else {
11100
+ const answer = await this.memoryRequest(state, context, "memories", {
11101
+ method: "POST",
11102
+ body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11103
+ });
11104
+ change.written = true;
11105
+ if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
11106
+ }
11107
+ await this.deleteLegacyPoolMemories(state, context, asset, legacy);
11108
+ let failure;
11109
+ try {
11110
+ const allowed = await this.readAllowList(state, context);
11111
+ const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
11112
+ if (!applied) failure = "ALLOW_LIST_MISMATCH";
11113
+ } catch {
11114
+ failure = "READ_BACK_FAILED";
11115
+ }
11116
+ if (!failure) return;
11117
+ const restored = await this.restorePoolMemory(state, context, change);
11118
+ throw new OwneyError(
11119
+ "POOL_SELECTION_NOT_APPLIED",
11120
+ `Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
11121
+ { asset, reason: failure, restored },
11122
+ this.id
11123
+ );
11124
+ }
11125
+ /**
11126
+ * Delete the free-text allow-lists we saved before the managed list existed.
11127
+ * Never throws: a list left behind is caught by the read-back. Logs no
11128
+ * sign-in token.
11129
+ */
11130
+ async deleteLegacyPoolMemories(state, context, asset, memories) {
11131
+ for (const memory of memories) {
11132
+ try {
11133
+ await this.memoryRequest(state, context, `memories/${memory.agentMemoryId}/delete`, {
11134
+ method: "POST"
11135
+ });
11136
+ } catch (error) {
11137
+ debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
11138
+ memoryId: memory.agentMemoryId,
11139
+ code: error instanceof OwneyError ? error.code : void 0,
11140
+ message: error instanceof Error ? error.message : void 0
11141
+ });
11142
+ }
11143
+ }
11144
+ }
11145
+ /**
11146
+ * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11147
+ * has no brackets. No picks names no vault.
11148
+ */
11149
+ async poolMemoryContent(asset, picks) {
11150
+ if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11151
+ const vaults = new Map(
11152
+ (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11153
+ );
11154
+ const entries = picks.map((pick) => {
11155
+ const vault = vaults.get(pick.toLowerCase());
11156
+ const address = vault?.address ?? pick;
11157
+ return vault?.name ? `${address} (${vault.name})` : address;
11158
+ });
11159
+ return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
11160
+ }
11161
+ /** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
11162
+ async restorePoolMemory(state, context, change) {
11163
+ if (!change.written) return true;
11164
+ try {
11165
+ if (change.previous) {
11166
+ await this.memoryRequest(state, context, "memories", {
11167
+ method: "POST",
11168
+ body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11169
+ });
11170
+ return true;
11171
+ }
11172
+ const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory) => isActiveMemory(memory) && isManagedVaultList(memory)).map((memory) => memory.agentMemoryId);
11173
+ for (const id of ids) {
11174
+ await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
11175
+ }
11176
+ return true;
11177
+ } catch {
11178
+ return false;
11179
+ }
11180
+ }
11181
+ /**
11182
+ * What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
11183
+ * pairs: the allowed vault addresses under the provider each belongs to, for
11184
+ * the vaults a new agent can use. An agent with no allow-list adds nothing,
11185
+ * and no pairs at all means every shown vault is on. Reads never create an
11186
+ * agent, and always read Base. A read that fails throws, because "no
11187
+ * allow-list" would wrongly mean "everything".
11188
+ *
11189
+ * An allow-list naming none of the listed vaults (the saved "none", or vaults
11190
+ * Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
11191
+ * it reports none chosen for its asset: a pair with empty `pools` for every
11192
+ * provider listing vaults for it. With no vault listed at all there is
11193
+ * nothing to name that by, and it throws: the rules still restrict the agent.
11194
+ *
11195
+ * `pairs` is accepted for the contract but does not trim the answer: cutting
11196
+ * a real allow-list down to the pairs asked about could leave none, and none
11197
+ * reads as every vault on.
11198
+ */
11199
+ async getPoolSelection(state, _chainId, params) {
11200
+ const byProvider = /* @__PURE__ */ new Map();
11201
+ for (const asset of new Set(params.assets)) {
11202
+ this.assertAsset(asset);
11203
+ const context = await this.findAgent(state, 8453, asset);
11204
+ if (!context) continue;
11205
+ const allowed = await this.readAllowList(state, context);
11206
+ if (allowed === void 0) continue;
11207
+ const options = await this.loadVaultOptions(asset);
11208
+ if (options.length === 0) {
11209
+ throw this.invalidResponse("pool selection", {
11210
+ reason: "vault-options lists no vault while an allow-list restricts the agent.",
11211
+ asset
11212
+ });
11213
+ }
11214
+ const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
11215
+ const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
11216
+ if (known.length === 0) {
11217
+ for (const vault of options) {
11218
+ if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
11219
+ }
11220
+ continue;
11221
+ }
11222
+ for (const vault of known) {
11223
+ const pools = byProvider.get(vault.provider) ?? [];
11224
+ byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
11225
+ }
11226
+ }
11227
+ return {
11228
+ strategies: [],
11229
+ pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
11230
+ };
11231
+ }
11232
+ /**
11233
+ * The allow-list in the agent's rules: every `allowedVaultAddresses` on an
11234
+ * `ignored_vault` user rule. Undefined when no rule has one, which allows
11235
+ * every vault; an empty list allows none. A response that does not have the
11236
+ * expected shape throws rather than reading as no allow-list.
11237
+ */
11238
+ async readAllowList(state, context) {
11239
+ const rules = await this.memoryRequest(
11240
+ state,
11241
+ context,
11242
+ "memories/effective-rules"
11243
+ );
11244
+ if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
11245
+ let allowed;
11246
+ for (const rule of rules.userRules) {
11247
+ if (rule?.ruleType !== "ignored_vault") continue;
11248
+ const list = rule.ruleConfig?.allowedVaultAddresses;
11249
+ if (list === void 0 || list === null) continue;
11250
+ if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
11251
+ throw this.invalidResponse("effective rules");
11252
+ }
11253
+ allowed = [...allowed ?? [], ...list];
11254
+ }
11255
+ return allowed;
11256
+ }
11257
+ async listMemories(state, context) {
11258
+ const response = await this.memoryRequest(state, context, "memories");
11259
+ if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
11260
+ return response.memories;
11261
+ }
11262
+ /** A memory call for an agent, on Base whichever chain the wallet is on. */
11263
+ async memoryRequest(state, context, suffix, options = {}) {
11264
+ try {
11265
+ return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
11266
+ } catch (error) {
11267
+ if (error instanceof OwneyError) throw error;
11268
+ throw this.mapRequestFailure(error);
11269
+ }
11270
+ }
10619
11271
  userKey(state, chainId) {
10620
11272
  return `${state.walletAddress.toLowerCase()}:${chainId}`;
10621
11273
  }
@@ -10668,6 +11320,7 @@ var YieldseekerAgent = class {
10668
11320
  this.agentContexts.set(slot, context);
10669
11321
  this.pendingSlotInvalidations.delete(slot);
10670
11322
  this.missingSlots.delete(slot);
11323
+ this.closedSlots.delete(slot);
10671
11324
  }
10672
11325
  assertSession(generation, chainId, asset) {
10673
11326
  if (this.readGeneration !== generation) {
@@ -10779,8 +11432,10 @@ var YieldseekerAgent = class {
10779
11432
  * highest-priority set of `priorities` (index 0 first). Hinted agentIds are
10780
11433
  * resolved first and a hinted top-priority match ends the search; then other
10781
11434
  * listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
11435
+ * A candidate whose wallet shows it closed (deactivated) never ranks, and its
11436
+ * agentId is added to `closed`.
10782
11437
  */
10783
- async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
11438
+ async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
10784
11439
  const fitting = /* @__PURE__ */ new Map();
10785
11440
  for (const agent of agents) {
10786
11441
  if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
@@ -10802,6 +11457,10 @@ var YieldseekerAgent = class {
10802
11457
  failure ??= { error: result.reason };
10803
11458
  continue;
10804
11459
  }
11460
+ if (result.value.wallet.deactivatedDate) {
11461
+ closed?.add(result.value.agent.agentId);
11462
+ continue;
11463
+ }
10805
11464
  const wallet = result.value.wallet.walletAddress.toLowerCase();
10806
11465
  const rank = priorities.findIndex((wallets) => wallets.has(wallet));
10807
11466
  if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
@@ -10816,32 +11475,213 @@ var YieldseekerAgent = class {
10816
11475
  }
10817
11476
  /**
10818
11477
  * chooseAgent, re-reading a cached list once (bypassing its cache) when the
10819
- * verified agent is missing. A slot still missing after that re-read is
10820
- * remembered for the list cache window, so later reads fail from the cached
10821
- * list without another re-read.
11478
+ * verified agent is missing. Still missing, Yieldseeker may have closed
11479
+ * (deactivated) it: the verified record's agent is reactivated and selected
11480
+ * from a fresh list, by the verified wallet only (never created). A slot
11481
+ * that still fails is remembered with its error for the list cache window,
11482
+ * so later reads fail without another re-read or reactivate. A slot
11483
+ * Yieldseeker will not reopen because of its active-agent limit throws
11484
+ * YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
11485
+ * no request.
10822
11486
  */
10823
11487
  async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
11488
+ this.throwIfSlotUnavailable(state, chainId, asset);
10824
11489
  try {
10825
11490
  return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
10826
11491
  } catch (error) {
10827
11492
  if (!this.isAgentMissing(error)) throw error;
10828
11493
  const slot = this.slotKey(state, chainId, asset);
10829
- if (this.isSlotMissing(slot)) throw error;
11494
+ this.throwIfSlotMissing(slot);
10830
11495
  const generation = this.readGeneration;
10831
11496
  const fresh = await this.listAgents(state, chainId, user, true);
10832
11497
  this.assertSession(generation, chainId, asset);
11498
+ let missing;
10833
11499
  try {
10834
11500
  return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
10835
11501
  } catch (retryError) {
10836
- if (this.isAgentMissing(retryError) && this.readGeneration === generation) {
10837
- this.missingSlots.set(slot, Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS);
11502
+ if (!this.isAgentMissing(retryError)) throw retryError;
11503
+ missing = retryError;
11504
+ }
11505
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
11506
+ const agentId = verified?.providerAgentId;
11507
+ if (!verified || !agentId) {
11508
+ this.rememberMissingSlot(slot, generation, missing);
11509
+ throw missing;
11510
+ }
11511
+ this.throwIfSlotMissing(slot);
11512
+ let reopened;
11513
+ try {
11514
+ reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
11515
+ this.assertSession(generation, chainId, asset);
11516
+ } catch (reopenError) {
11517
+ this.rememberMissingSlot(slot, generation, reopenError);
11518
+ throw reopenError;
11519
+ }
11520
+ try {
11521
+ const agent = await this.agentWithWallet(
11522
+ state,
11523
+ chainId,
11524
+ user,
11525
+ reopened,
11526
+ asset,
11527
+ [/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
11528
+ [agentId]
11529
+ );
11530
+ if (agent) return agent;
11531
+ throw this.agentMissing(chainId, asset, agentId);
11532
+ } catch (reopenedError) {
11533
+ if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
11534
+ throw reopenedError;
11535
+ }
11536
+ }
11537
+ }
11538
+ throwIfSlotUnavailable(state, chainId, asset) {
11539
+ const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
11540
+ if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
11541
+ }
11542
+ /**
11543
+ * Rethrow the error a slot's lookup failed with while the slot is still
11544
+ * marked, or for the session when Yieldseeker will never reopen its agent.
11545
+ * A remembered rate limit is rethrown with the time left on its marker as
11546
+ * its retry delay (`retryAfterSeconds`): no new attempt is made before then,
11547
+ * so a caller that waits it out retries once instead of every few seconds.
11548
+ */
11549
+ throwIfSlotMissing(slot) {
11550
+ const closed = this.closedSlots.get(slot);
11551
+ if (closed) throw closed;
11552
+ const missing = this.missingSlots.get(slot);
11553
+ if (!missing || missing.until <= Date.now()) return;
11554
+ const { error } = missing;
11555
+ if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
11556
+ const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
11557
+ const rethrown = new OwneyError(
11558
+ error.code,
11559
+ error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
11560
+ { ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
11561
+ error.agentId
11562
+ );
11563
+ this.rethrownSlotFailures.set(rethrown, error);
11564
+ throw rethrown;
11565
+ }
11566
+ /**
11567
+ * Remember a slot's failed lookup or reactivate for the list-cache window.
11568
+ * A sign-in failure is not remembered (the wallet's rejection,
11569
+ * AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
11570
+ * remembered it would refuse the next sign-in, even one the user starts,
11571
+ * with no request for the whole window.
11572
+ */
11573
+ rememberMissingSlot(slot, generation, error) {
11574
+ if (this.readGeneration !== generation) return;
11575
+ if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
11576
+ this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
11577
+ }
11578
+ /**
11579
+ * Reactivate the slot's verified agent, then read the list bypassing its
11580
+ * cache, with a read sent after the reactivate answered. Concurrent lookups
11581
+ * of one slot share one reopen. Resolves to the fresh list. At the
11582
+ * active-agent limit the slot is recorded unavailable and this throws
11583
+ * YIELDSEEKER_SLOT_UNAVAILABLE.
11584
+ */
11585
+ reopenAgent(state, chainId, user, asset, agentId) {
11586
+ const slot = this.slotKey(state, chainId, asset);
11587
+ const pending = this.pendingReopens.get(slot);
11588
+ if (pending) return pending;
11589
+ const generation = this.readGeneration;
11590
+ const request2 = (async () => {
11591
+ const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
11592
+ this.assertSession(generation, chainId, asset);
11593
+ if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
11594
+ this.forgetAgentWallet(agentId);
11595
+ this.missingSlots.delete(slot);
11596
+ await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
11597
+ this.assertSession(generation, chainId, asset);
11598
+ const fresh = await this.listAgents(state, chainId, user, true);
11599
+ this.assertSession(generation, chainId, asset);
11600
+ return fresh;
11601
+ })().finally(() => {
11602
+ if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
11603
+ });
11604
+ this.pendingReopens.set(slot, request2);
11605
+ return request2;
11606
+ }
11607
+ /**
11608
+ * The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
11609
+ * and the pre-deposit check (assertAgentOpen), so a slot costs at most one
11610
+ * reactivate per list-cache window:
11611
+ * - a slot recorded unavailable (the limit) answers "limit" with no request;
11612
+ * - concurrent callers share one request;
11613
+ * - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
11614
+ * remembered as the slot's failure for the list-cache window (missingSlots)
11615
+ * and rethrown to later callers with no request; a closed code
11616
+ * (closedSlots) for the session; a sign-in failure is not remembered;
11617
+ * - the limit is recorded in unavailableSlots only while the session is
11618
+ * unchanged, so a disconnect during the request is not undone by its late
11619
+ * answer.
11620
+ */
11621
+ async reactivateSlot(state, chainId, user, asset, agentId) {
11622
+ const slot = this.slotKey(state, chainId, asset);
11623
+ const limit = this.unavailableSlots.get(slot);
11624
+ if (limit !== void 0) return { outcome: "limit", providerCode: limit };
11625
+ const key2 = `${slot}:${agentId}`;
11626
+ const pending = this.pendingReactivates.get(key2);
11627
+ if (pending) return pending;
11628
+ this.throwIfSlotMissing(slot);
11629
+ const generation = this.readGeneration;
11630
+ const request2 = (async () => {
11631
+ try {
11632
+ const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
11633
+ if (result.outcome === "limit" && this.readGeneration === generation) {
11634
+ this.unavailableSlots.set(slot, result.providerCode);
10838
11635
  }
10839
- throw retryError;
11636
+ return result;
11637
+ } catch (error) {
11638
+ 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)) {
11639
+ this.closedSlots.set(slot, error);
11640
+ }
11641
+ this.rememberMissingSlot(slot, generation, error);
11642
+ throw error;
10840
11643
  }
11644
+ })().finally(() => {
11645
+ if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
11646
+ });
11647
+ this.pendingReactivates.set(key2, request2);
11648
+ return request2;
11649
+ }
11650
+ /**
11651
+ * Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
11652
+ * Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
11653
+ * by another tab) counts as reopened; the active-agent limit is an outcome,
11654
+ * not an error. An agent that cannot come back throws
11655
+ * YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
11656
+ * 5xx, an unknown code) throws the mapped API error.
11657
+ */
11658
+ async reactivateAgent(state, chainId, user, asset, agentId) {
11659
+ try {
11660
+ await this.providerRequest(
11661
+ state,
11662
+ chainId,
11663
+ `/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
11664
+ { method: "POST", body: {} }
11665
+ );
11666
+ return { outcome: "reopened" };
11667
+ } catch (error) {
11668
+ if (error instanceof OwneyError) throw error;
11669
+ const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
11670
+ if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
11671
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
11672
+ return { outcome: "limit", providerCode };
11673
+ }
11674
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
11675
+ throw this.agentClosed(chainId, asset, agentId, providerCode);
11676
+ }
11677
+ throw this.mapRequestFailure(error);
10841
11678
  }
10842
11679
  }
10843
- isSlotMissing(slot) {
10844
- return (this.missingSlots.get(slot) ?? 0) > Date.now();
11680
+ /** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
11681
+ forgetAgentWallet(agentId) {
11682
+ const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
11683
+ for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
11684
+ for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
10845
11685
  }
10846
11686
  /**
10847
11687
  * The agent that serves deposits and withdrawals for a slot (Ruling 23):
@@ -10849,7 +11689,8 @@ var YieldseekerAgent = class {
10849
11689
  * whatever its name; the stored agentId is only a hint;
10850
11690
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
10851
11691
  * 3. else the fitting agent named "owney" (first use, migration, or a
10852
- * verified wallet that is not a fitting listed agent);
11692
+ * verified wallet that is not a fitting listed agent), unless step 1/2
11693
+ * read its wallet and it is closed (deactivated): that agent is not listed;
10853
11694
  * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
10854
11695
  * create); without one, undefined (the caller may create).
10855
11696
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
@@ -10860,6 +11701,7 @@ var YieldseekerAgent = class {
10860
11701
  const slot = this.slotAccounts(accounts, chainId, asset);
10861
11702
  const verified = slot.find((account) => account.status === "verified");
10862
11703
  const superseded = slot.filter((account) => account.status === "superseded");
11704
+ const closed = /* @__PURE__ */ new Set();
10863
11705
  if (verified || superseded.length) {
10864
11706
  const priorities = [];
10865
11707
  if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
@@ -10873,11 +11715,12 @@ var YieldseekerAgent = class {
10873
11715
  agents,
10874
11716
  asset,
10875
11717
  priorities,
10876
- [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
11718
+ [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
11719
+ closed
10877
11720
  );
10878
11721
  if (match) return match;
10879
11722
  }
10880
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
11723
+ const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
10881
11724
  if (named) return named;
10882
11725
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
10883
11726
  return void 0;
@@ -10893,6 +11736,39 @@ var YieldseekerAgent = class {
10893
11736
  this.id
10894
11737
  );
10895
11738
  }
11739
+ slotUnavailable(chainId, asset, providerCode) {
11740
+ return new OwneyError(
11741
+ "YIELDSEEKER_SLOT_UNAVAILABLE",
11742
+ `Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
11743
+ { rpcSource: "agent-api", chainId, asset, providerCode },
11744
+ this.id
11745
+ );
11746
+ }
11747
+ /** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
11748
+ isSlotEmpty(error) {
11749
+ return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
11750
+ }
11751
+ /**
11752
+ * The slot's lookup failed through the missing-agent / reopen path and was
11753
+ * remembered with this very error, even a transient one (429, 5xx, timeout),
11754
+ * or with the copy of it a remembered rate limit is rethrown as. Compares
11755
+ * the remembered error, not its expiry, so it holds however long the rest
11756
+ * of the read takes.
11757
+ */
11758
+ isMarkedSlotFailure(slot, error) {
11759
+ const marker = this.missingSlots.get(slot);
11760
+ if (!marker) return false;
11761
+ return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
11762
+ }
11763
+ /** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
11764
+ agentClosed(chainId, asset, agentId, providerCode, extra) {
11765
+ return new OwneyError(
11766
+ "YIELDSEEKER_AGENT_CLOSED",
11767
+ `Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
11768
+ { rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
11769
+ this.id
11770
+ );
11771
+ }
10896
11772
  /**
10897
11773
  * Fire-and-forget: record which agent serves this slot. Never awaited on the
10898
11774
  * funds path and never throws; once per agent wallet and deployment state
@@ -10982,7 +11858,7 @@ var YieldseekerAgent = class {
10982
11858
  } catch (error) {
10983
11859
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
10984
11860
  if (error instanceof OwneyError) throw error;
10985
- throw this.mapApiError(error);
11861
+ throw this.mapRequestFailure(error);
10986
11862
  }
10987
11863
  let created;
10988
11864
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
@@ -11003,7 +11879,7 @@ var YieldseekerAgent = class {
11003
11879
  } catch (createError) {
11004
11880
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
11005
11881
  if (canRetry) continue;
11006
- throw this.mapApiError(createError);
11882
+ throw this.mapRequestFailure(createError);
11007
11883
  }
11008
11884
  }
11009
11885
  user = created?.user ?? null;
@@ -11060,6 +11936,7 @@ var YieldseekerAgent = class {
11060
11936
  return context;
11061
11937
  }
11062
11938
  async resolveAgent(state, chainId, asset, createIfMissing) {
11939
+ this.throwIfSlotUnavailable(state, chainId, asset);
11063
11940
  const generation = this.readGeneration;
11064
11941
  const accountsRead = this.agentAccounts(state, chainId);
11065
11942
  const user = await this.resolveUser(state, chainId);
@@ -11102,7 +11979,7 @@ var YieldseekerAgent = class {
11102
11979
  );
11103
11980
  } catch (error) {
11104
11981
  const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
11105
- if (!conflict) throw this.mapApiError(error);
11982
+ if (!conflict) throw this.mapRequestFailure(error);
11106
11983
  this.assertSession(generation, chainId, asset);
11107
11984
  return this.adoptConflictingAgent(
11108
11985
  state,
@@ -11195,10 +12072,11 @@ var YieldseekerAgent = class {
11195
12072
  const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
11196
12073
  if (agent) selected.set(asset, agent);
11197
12074
  } catch (error) {
11198
- if (assetFilter || !this.isAgentMissing(error)) throw error;
12075
+ if (assetFilter) throw error;
12076
+ if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
11199
12077
  missing.push(error);
11200
12078
  missingAssets?.add(asset);
11201
- console.warn(`[owney-sdk] Yieldseeker ${asset} agent is missing:`, error);
12079
+ console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
11202
12080
  }
11203
12081
  }));
11204
12082
  this.assertSession(generation, chainId);
@@ -11833,6 +12711,7 @@ var YieldseekerAgent = class {
11833
12711
  try {
11834
12712
  return await this.providerRequest(state, chainId, path, options);
11835
12713
  } catch (error) {
12714
+ if (isWalletRejection(error)) throw error;
11836
12715
  const mapped = this.mapApiError(error);
11837
12716
  const delay = read2 ? rateLimitDelay(mapped) : void 0;
11838
12717
  if (delay !== void 0 && this.readGeneration === generation) {
@@ -11887,6 +12766,16 @@ var YieldseekerAgent = class {
11887
12766
  }
11888
12767
  }
11889
12768
  }
12769
+ /**
12770
+ * mapApiError for a request that may have opened the Yieldseeker sign-in
12771
+ * prompt (providerRequest signs when no sign-in is saved, and again when
12772
+ * Yieldseeker refuses one). The wallet's rejection, the user cancelling that
12773
+ * prompt, is returned unchanged: the client and the app must see the user's
12774
+ * cancel (no further prompt, no retry), never a provider failure.
12775
+ */
12776
+ mapRequestFailure(error) {
12777
+ return isWalletRejection(error) ? error : this.mapApiError(error);
12778
+ }
11890
12779
  mapApiError(error) {
11891
12780
  if (!(error instanceof YieldseekerApiError)) {
11892
12781
  return new OwneyError(
@@ -12477,6 +13366,8 @@ var FALLBACK_WRAP_GAS = 50000n;
12477
13366
  var APPROVE_GAS = 60000n;
12478
13367
  var GAS_SAFETY = 2n;
12479
13368
  var MIN_WALLET_GAS_PRICE = 3000000000n;
13369
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
13370
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
12480
13371
  async function wrapNative(deps, options) {
12481
13372
  const { chainId, wrapper, nativeSymbol, requested } = options;
12482
13373
  const balance = await deps.readNativeBalance();
@@ -12534,16 +13425,90 @@ async function wrapNative(deps, options) {
12534
13425
  }
12535
13426
  );
12536
13427
  }
13428
+ let baseline;
13429
+ if (deps.readWrappedBalance) {
13430
+ try {
13431
+ baseline = await deps.readWrappedBalance();
13432
+ } catch (error) {
13433
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
13434
+ message: error instanceof Error ? error.message : String(error)
13435
+ });
13436
+ }
13437
+ }
12537
13438
  await deps.ensureChain(chainId);
12538
13439
  debugLog("owney-sdk", "wrap: sending deposit()", {
12539
13440
  wrapper,
12540
13441
  value: wrapped.toString()
12541
13442
  });
12542
- const txHash = await deps.sendTransaction(
12543
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
12544
- options.onSubmitted
12545
- );
12546
- return { wrapped, txHash };
13443
+ let notified = false;
13444
+ const notify2 = (hash2) => {
13445
+ if (notified) return;
13446
+ notified = true;
13447
+ options.onSubmitted?.(hash2);
13448
+ };
13449
+ const outcome = await new Promise((resolve, reject) => {
13450
+ let done = false;
13451
+ let timer;
13452
+ const finish = (settle) => {
13453
+ if (done) return;
13454
+ done = true;
13455
+ clearTimeout(timer);
13456
+ settle();
13457
+ };
13458
+ timer = setTimeout(
13459
+ () => finish(
13460
+ () => reject(
13461
+ new OwneyError(
13462
+ "SWAP_WALLET_PROMPT_TIMEOUT",
13463
+ // Hedged on purpose: a wallet that never answered may still have
13464
+ // sent it, and wrapping again would wrap twice.
13465
+ `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}.`,
13466
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
13467
+ )
13468
+ )
13469
+ ),
13470
+ WRAP_PROMPT_TIMEOUT_MS
13471
+ );
13472
+ deps.sendTransaction(
13473
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
13474
+ (hash2) => {
13475
+ clearTimeout(timer);
13476
+ notify2(hash2);
13477
+ }
13478
+ ).then(
13479
+ (txHash) => finish(() => resolve({ txHash })),
13480
+ (error) => finish(() => reject(error))
13481
+ );
13482
+ if (baseline !== void 0 && deps.readWrappedBalance) {
13483
+ const read2 = deps.readWrappedBalance;
13484
+ const target = baseline + wrapped;
13485
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13486
+ void (async () => {
13487
+ while (!done) {
13488
+ await sleep4(WRAP_WATCH_INTERVAL_MS);
13489
+ if (done) return;
13490
+ try {
13491
+ if (await read2() >= target) {
13492
+ debugLog(
13493
+ "owney-sdk",
13494
+ "wrap: landed on chain before the wallet answered"
13495
+ );
13496
+ finish(() => {
13497
+ notify2();
13498
+ resolve({});
13499
+ });
13500
+ return;
13501
+ }
13502
+ } catch {
13503
+ }
13504
+ }
13505
+ })();
13506
+ }
13507
+ });
13508
+ return {
13509
+ wrapped,
13510
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
13511
+ };
12547
13512
  }
12548
13513
  function requireWrapper(quote) {
12549
13514
  const wrapper = quote.wrappedNative;
@@ -14101,9 +15066,40 @@ function aggregateApyHistory(agentApys) {
14101
15066
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
14102
15067
  if (total <= 0 || !Number.isFinite(total)) return [];
14103
15068
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
14104
- return Number.isFinite(apy) ? [{ date, apy }] : [];
15069
+ if (!Number.isFinite(apy)) return [];
15070
+ const incentives = aggregateIncentives(points, total);
15071
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
14105
15072
  });
14106
15073
  }
15074
+ function incentiveKey(incentive) {
15075
+ return JSON.stringify([
15076
+ incentive.source,
15077
+ incentive.agentId,
15078
+ incentive.opportunityId,
15079
+ [...incentive.campaignIds].sort()
15080
+ ]);
15081
+ }
15082
+ function aggregateIncentives(points, totalBalance) {
15083
+ const byProgram = /* @__PURE__ */ new Map();
15084
+ for (const point of points) {
15085
+ const weight = point.historicalBalance.amount / totalBalance;
15086
+ for (const incentive of point.incentives ?? []) {
15087
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
15088
+ const key2 = incentiveKey(incentive);
15089
+ const existing = byProgram.get(key2);
15090
+ if (existing) {
15091
+ existing.apyContribution += incentive.apyContribution * weight;
15092
+ } else {
15093
+ byProgram.set(key2, {
15094
+ ...incentive,
15095
+ campaignIds: [...incentive.campaignIds],
15096
+ apyContribution: incentive.apyContribution * weight
15097
+ });
15098
+ }
15099
+ }
15100
+ }
15101
+ return [...byProgram.values()];
15102
+ }
14107
15103
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
14108
15104
  const sums = {};
14109
15105
  const weights = {};
@@ -14915,6 +15911,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
14915
15911
  }
14916
15912
  }
14917
15913
 
15914
+ // src/lib/walletconnect-switch.ts
15915
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
15916
+ var HOLD_CHAIN_MS = 15e3;
15917
+ var MAX_RESENDS = 2;
15918
+ var holds = /* @__PURE__ */ new Map();
15919
+ function parseChainId(raw2) {
15920
+ if (typeof raw2 === "number") return raw2;
15921
+ if (typeof raw2 !== "string") return void 0;
15922
+ const ref = raw2.split(":").pop() ?? raw2;
15923
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
15924
+ return Number.isFinite(id) ? id : void 0;
15925
+ }
15926
+ function walletConnectCore(provider) {
15927
+ const p = provider;
15928
+ const core = p?.signer ?? p;
15929
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
15930
+ return null;
15931
+ }
15932
+ const peer = core.session.peer?.metadata?.name ?? "";
15933
+ if (!/metamask/i.test(peer)) return null;
15934
+ return core;
15935
+ }
15936
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
15937
+ const core = walletConnectCore(provider);
15938
+ if (!core) return false;
15939
+ holds.get(core.session.topic)?.();
15940
+ await requestSwitch(core, provider, chainId, timeoutMs);
15941
+ holdChain(core, provider, chainId);
15942
+ return true;
15943
+ }
15944
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
15945
+ const current = Number(
15946
+ await provider.request({ method: "eth_chainId" })
15947
+ );
15948
+ const hexChainId = `0x${chainId.toString(16)}`;
15949
+ let timer;
15950
+ try {
15951
+ await Promise.race([
15952
+ core.client.request({
15953
+ topic: core.session.topic,
15954
+ chainId: `eip155:${current}`,
15955
+ request: {
15956
+ method: "wallet_switchEthereumChain",
15957
+ params: [{ chainId: hexChainId }]
15958
+ }
15959
+ }),
15960
+ new Promise((_, reject) => {
15961
+ timer = setTimeout(
15962
+ () => reject(
15963
+ new Error("The wallet did not answer the network switch in time")
15964
+ ),
15965
+ timeoutMs
15966
+ );
15967
+ })
15968
+ ]);
15969
+ } finally {
15970
+ clearTimeout(timer);
15971
+ }
15972
+ try {
15973
+ core.setDefaultChain(`eip155:${chainId}`);
15974
+ } catch {
15975
+ }
15976
+ }
15977
+ function holdChain(core, provider, chainId) {
15978
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
15979
+ return;
15980
+ }
15981
+ let resends = 0;
15982
+ const listener = (raw2) => {
15983
+ const reported = parseChainId(raw2);
15984
+ debugLog("wc-switch", "wallet reported chain", {
15985
+ reported,
15986
+ holding: chainId,
15987
+ resends
15988
+ });
15989
+ if (reported === void 0 || reported === chainId) return;
15990
+ if (resends >= MAX_RESENDS) return;
15991
+ resends += 1;
15992
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
15993
+ (error) => debugLog("wc-switch", "re-switch failed", {
15994
+ error: error instanceof Error ? error.message : String(error)
15995
+ })
15996
+ );
15997
+ };
15998
+ const release = () => {
15999
+ clearTimeout(timer);
16000
+ core.removeListener?.("chainChanged", listener);
16001
+ if (holds.get(core.session.topic) === release) {
16002
+ holds.delete(core.session.topic);
16003
+ }
16004
+ };
16005
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
16006
+ core.on("chainChanged", listener);
16007
+ holds.set(core.session.topic, release);
16008
+ }
16009
+ function withWalletConnectSwitch(provider) {
16010
+ if (!walletConnectCore(provider)) return provider;
16011
+ const target = provider;
16012
+ const request2 = async (args) => {
16013
+ if (args?.method !== "wallet_switchEthereumChain") {
16014
+ return target.request(args);
16015
+ }
16016
+ const [param] = args.params ?? [];
16017
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
16018
+ if (!Number.isFinite(chainId)) return target.request(args);
16019
+ await switchWalletConnectChain(target, chainId);
16020
+ return null;
16021
+ };
16022
+ return new Proxy(target, {
16023
+ get(obj, prop) {
16024
+ if (prop === "request") return request2;
16025
+ const value = Reflect.get(obj, prop, obj);
16026
+ return typeof value === "function" ? value.bind(obj) : value;
16027
+ }
16028
+ });
16029
+ }
16030
+
14918
16031
  // src/lib/sponsored-calls-deposit.ts
14919
16032
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
14920
16033
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -15185,6 +16298,14 @@ var OwneySDK = class {
15185
16298
  * withdraw, but they are excluded from new deposits / activations.
15186
16299
  */
15187
16300
  disabledAgents = /* @__PURE__ */ new Set();
16301
+ /**
16302
+ * Agents whose sign-in the user cancelled this session (the wallet rejected
16303
+ * the prompt), keyed by chain. Until the app ends the session they are read
16304
+ * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
16305
+ * the user cancelled. A later successful activation of the agent removes
16306
+ * it, and `disconnect()` or a different wallet's `connect()` clears the map.
16307
+ */
16308
+ declinedSignIns = /* @__PURE__ */ new Map();
15188
16309
  state = null;
15189
16310
  connectionRevision = 0;
15190
16311
  disconnectingAgents = null;
@@ -15220,6 +16341,8 @@ var OwneySDK = class {
15220
16341
  * session started: true when it armed the refresh, false when its deadline
15221
16342
  * had passed (it only dropped the cache and forced one snapshot read). */
15222
16343
  recoveredFundingReads = /* @__PURE__ */ new Map();
16344
+ /** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
16345
+ announcedDeposits = /* @__PURE__ */ new Set();
15223
16346
  fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
15224
16347
  activationChecks = /* @__PURE__ */ new Map();
15225
16348
  // Protect the SDK entry point as well as the mini-app hook. This owns only
@@ -15475,10 +16598,15 @@ var OwneySDK = class {
15475
16598
  }
15476
16599
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
15477
16600
  this.clearConnectionState();
16601
+ if (replacingOwner) this.declinedSignIns.clear();
15478
16602
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
15479
16603
  if (revision !== this.connectionRevision)
15480
16604
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
15481
- this.state = { provider, walletAddress, chainId: null };
16605
+ this.state = {
16606
+ provider: withWalletConnectSwitch(provider),
16607
+ walletAddress,
16608
+ chainId: null
16609
+ };
15482
16610
  }
15483
16611
  /**
15484
16612
  * Disconnect from all agents and clear connection state.
@@ -15487,6 +16615,7 @@ var OwneySDK = class {
15487
16615
  async disconnect() {
15488
16616
  ++this.connectionRevision;
15489
16617
  this.clearConnectionState();
16618
+ this.declinedSignIns.clear();
15490
16619
  await this.disconnectAgents();
15491
16620
  }
15492
16621
  clearConnectionState() {
@@ -15516,6 +16645,44 @@ var OwneySDK = class {
15516
16645
  isAgentDisabled(agentId) {
15517
16646
  return this.disabledAgents.has(agentId);
15518
16647
  }
16648
+ /**
16649
+ * True when `id` takes no new deposits on this chain and asset this
16650
+ * session: its adapter reports no agent for the slot.
16651
+ */
16652
+ isAgentUnavailable(id, chainId, asset) {
16653
+ if (asset === void 0) return false;
16654
+ return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
16655
+ }
16656
+ /**
16657
+ * The agents that take no new deposits on this chain and asset this
16658
+ * session, so the app can show them as unavailable: each agent whose
16659
+ * provider has no agent for this slot. They stay withdrawable.
16660
+ */
16661
+ getUnavailableAgentIds(chainId, asset) {
16662
+ return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
16663
+ }
16664
+ /**
16665
+ * The adapter reports no agent for this chain and asset this session (see
16666
+ * `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
16667
+ * withdrawal without an explicit agent leaves it out instead of failing its
16668
+ * leg.
16669
+ */
16670
+ hasNoAgentForSlot(agent, state, chainId, asset) {
16671
+ return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
16672
+ }
16673
+ /**
16674
+ * The state an agent's reads use. An agent whose sign-in the user cancelled
16675
+ * on the connection chain this session is read from a saved sign-in only,
16676
+ * as `offChainPortfolioAgents` reads: a read that would need a wallet
16677
+ * prompt fails for that agent instead of reopening the prompt the user
16678
+ * cancelled. A later successful activation of the agent, or `disconnect()`,
16679
+ * lifts it.
16680
+ */
16681
+ readStateFor(agentId, state) {
16682
+ const chainId = state.chainId;
16683
+ if (state.promptless === true || chainId === null) return state;
16684
+ return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
16685
+ }
15519
16686
  /**
15520
16687
  * Check if the SDK has an active connection state.
15521
16688
  * @returns `true` if `connect()` has been called and `disconnect()` has not
@@ -15732,10 +16899,14 @@ var OwneySDK = class {
15732
16899
  * connection chain, then the off-chain ones on their own chain. */
15733
16900
  portfolioReads(state, chainId) {
15734
16901
  return [
15735
- ...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
15736
- ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
16902
+ ...this.activeReads(state, chainId),
16903
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
15737
16904
  ];
15738
16905
  }
16906
+ /** The active agents, each with the state its reads use (`readStateFor`). */
16907
+ activeReads(state, chainId) {
16908
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
16909
+ }
15739
16910
  /**
15740
16911
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
15741
16912
  * throws — it degrades to null — so this cannot break activation.
@@ -15859,7 +17030,7 @@ var OwneySDK = class {
15859
17030
  */
15860
17031
  async getAvailableAgents(options = {}) {
15861
17032
  await this.ensureAgentsInitialized();
15862
- const { chainId, asset, includeDisabled = false } = options;
17033
+ const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
15863
17034
  const available = [];
15864
17035
  for (const [id, agent] of this.agents) {
15865
17036
  const isEnabled = !this.isAgentDisabled(id);
@@ -15875,6 +17046,9 @@ var OwneySDK = class {
15875
17046
  continue;
15876
17047
  }
15877
17048
  }
17049
+ if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
17050
+ continue;
17051
+ }
15878
17052
  available.push({
15879
17053
  id,
15880
17054
  isEnabled,
@@ -15894,8 +17068,17 @@ var OwneySDK = class {
15894
17068
  * that support the given chainId (incompatible agents are silently skipped).
15895
17069
  * If provided, ALL specified agents must support the chainId or the call
15896
17070
  * throws before activating any agent.
17071
+ * @param options - Optional. `asset` limits setup to that asset;
17072
+ * `onAgentsSelected` fires once reads can start.
17073
+ * @throws Activation stops at the first agent that fails, and the caller
17074
+ * should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
17075
+ * earlier agent activated; `walletRejected` in its details means the user
17076
+ * rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
17077
+ * never be readied (`details.permanent`). Otherwise the agent's own error
17078
+ * is thrown as is. Until it signs in, an agent whose signature the user
17079
+ * rejected is read from a saved sign-in only and opens no prompt.
15897
17080
  */
15898
- async activateAgent(chainId, agentId, asset) {
17081
+ async activateAgent(chainId, agentId, options = {}) {
15899
17082
  const state = this.requireState();
15900
17083
  await this.ensureAgentsInitialized();
15901
17084
  this.assertActivationSession(state);
@@ -15932,7 +17115,8 @@ var OwneySDK = class {
15932
17115
  this.activeAgents.add(id);
15933
17116
  }
15934
17117
  state.chainId = chainId;
15935
- await this.activateAgentsInTurn(agents, state, chainId, asset);
17118
+ options.onAgentsSelected?.();
17119
+ await this.activateAgentsInTurn(agents, state, chainId, options.asset);
15936
17120
  return;
15937
17121
  }
15938
17122
  const compatible = [...this.agents.values()].filter(
@@ -15950,10 +17134,11 @@ var OwneySDK = class {
15950
17134
  this.activeAgents.add(agent.id);
15951
17135
  }
15952
17136
  state.chainId = chainId;
17137
+ options.onAgentsSelected?.();
15953
17138
  const enabledCompatible = compatible.filter(
15954
17139
  (agent) => !this.isAgentDisabled(agent.id)
15955
17140
  );
15956
- await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
17141
+ await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
15957
17142
  }
15958
17143
  assertActivationSession(state) {
15959
17144
  if (this.state !== state) {
@@ -15973,12 +17158,17 @@ var OwneySDK = class {
15973
17158
  * Serializing costs no real wall-clock: the user can only approve one prompt
15974
17159
  * at a time anyway.
15975
17160
  *
15976
- * Stop at the first failure so a canceled sign-in does not open another
15977
- * agent's wallet prompt. Report any earlier successes for diagnostics; the
15978
- * app discards the session when the complete sign-in does not succeed.
17161
+ * Stop at the first failure (2026-11-06): a connect needs every agent, so
17162
+ * no later agent's wallet prompt opens for a sign-in that already failed.
17163
+ * When an earlier agent activated, the partial failure reports it, and
17164
+ * `walletRejected` tells the app the user canceled; the app ends the
17165
+ * session either way. When none activated, the agent's own error is thrown.
17166
+ * A failure the provider marks `permanent` is thrown as
17167
+ * `AGENT_ACTIVATION_BLOCKED`.
15979
17168
  */
15980
17169
  async activateAgentsInTurn(agents, state, chainId, asset) {
15981
17170
  let firstError = null;
17171
+ let walletRejected = false;
15982
17172
  const activatedAgentIds = [];
15983
17173
  const failedAgents = [];
15984
17174
  for (const agent of agents) {
@@ -15989,6 +17179,7 @@ var OwneySDK = class {
15989
17179
  await this.applyOrgPolicyTo(agent, state, chainId);
15990
17180
  this.assertActivationSession(state);
15991
17181
  activatedAgentIds.push(agent.id);
17182
+ this.declinedSignIns.get(chainId)?.delete(agent.id);
15992
17183
  } catch (error) {
15993
17184
  this.assertActivationSession(state);
15994
17185
  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.";
@@ -15998,15 +17189,28 @@ var OwneySDK = class {
15998
17189
  message,
15999
17190
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
16000
17191
  });
16001
- if (firstError === null) {
16002
- firstError = error;
16003
- } else {
16004
- console.error(`activateAgent(${agent.id}) failed:`, error);
17192
+ firstError = error;
17193
+ if (this.isUserRejectedWithdrawal(error)) {
17194
+ walletRejected = true;
17195
+ const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
17196
+ declined.add(agent.id);
17197
+ this.declinedSignIns.set(chainId, declined);
16005
17198
  }
16006
17199
  break;
16007
17200
  }
16008
17201
  }
16009
17202
  if (firstError === null) return;
17203
+ if (failedAgents.some(({ details }) => details?.permanent === true)) {
17204
+ throw new OwneyError(
17205
+ "AGENT_ACTIVATION_BLOCKED",
17206
+ failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
17207
+ {
17208
+ activatedAgentIds,
17209
+ failedAgentIds: failedAgents.map(({ agentId }) => agentId),
17210
+ failures: failedAgents
17211
+ }
17212
+ );
17213
+ }
16010
17214
  if (activatedAgentIds.length === 0) throw firstError;
16011
17215
  const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
16012
17216
  const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
@@ -16016,7 +17220,7 @@ var OwneySDK = class {
16016
17220
  throw new OwneyError(
16017
17221
  "AGENT_ACTIVATION_PARTIAL_FAILURE",
16018
17222
  `${activeNames} activated. ${failureMessages}`,
16019
- { activatedAgentIds, failedAgentIds, failures: failedAgents }
17223
+ { activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
16020
17224
  );
16021
17225
  }
16022
17226
  /**
@@ -16031,6 +17235,10 @@ var OwneySDK = class {
16031
17235
  * all shares into one signature; custom callbacks still run once per agent.
16032
17236
  * @param options.agentId - Optional explicit target. Otherwise split equally,
16033
17237
  * or fund remaining agents when a recovery deposit cannot meet every minimum.
17238
+ * @param options.excludeAgentIds - Agents that must receive nothing. The rest
17239
+ * split the whole amount under their own minimums. Throws
17240
+ * `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
17241
+ * when resuming a signed batch.
16034
17242
  * @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
16035
17243
  */
16036
17244
  async deposit(options) {
@@ -16059,6 +17267,7 @@ var OwneySDK = class {
16059
17267
  const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
16060
17268
  if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
16061
17269
  if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
17270
+ this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
16062
17271
  } catch {
16063
17272
  }
16064
17273
  };
@@ -16094,6 +17303,8 @@ var OwneySDK = class {
16094
17303
  const state = this.requireState();
16095
17304
  const chainId = options.chainId ?? this.requireChainId();
16096
17305
  const activatedChain = state.chainId;
17306
+ const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
17307
+ this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
16097
17308
  let checkpointFailure;
16098
17309
  let checkpointFailedEvidence = [];
16099
17310
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
@@ -16190,11 +17401,11 @@ var OwneySDK = class {
16190
17401
  const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
16191
17402
  if (!batchTransfer2) throw invalid2();
16192
17403
  const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
16193
- if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
17404
+ if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
16194
17405
  throw new OwneyError(
16195
17406
  error.code,
16196
- "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
16197
- { ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
17407
+ 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.",
17408
+ { cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
16198
17409
  error.agentId
16199
17410
  );
16200
17411
  throw error;
@@ -16232,7 +17443,7 @@ var OwneySDK = class {
16232
17443
  this.validateChainHasAgents(chainId);
16233
17444
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
16234
17445
  excludeDisabled: true
16235
- });
17446
+ }).filter((agent) => !excludeAgentIds?.includes(agent.id));
16236
17447
  const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
16237
17448
  const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
16238
17449
  const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
@@ -16380,7 +17591,7 @@ var OwneySDK = class {
16380
17591
  }
16381
17592
  try {
16382
17593
  if (!depositCallback && appObserves && !options.resumeTxHash) {
16383
- const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
17594
+ const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
16384
17595
  for (const id of ids) {
16385
17596
  const evidence = [...prepared.values()].find((value) => value.agentId === id);
16386
17597
  const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
@@ -16480,6 +17691,29 @@ var OwneySDK = class {
16480
17691
  }
16481
17692
  }
16482
17693
  }
17694
+ /**
17695
+ * Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
17696
+ * the explicit `agentId` is listed, or every agent that can take this asset
17697
+ * on this chain (and is not disabled) is. A no-op without a list, so a deposit
17698
+ * without exclusions is exactly as it was. Reads no provider.
17699
+ */
17700
+ assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
17701
+ if (!excludeAgentIds?.length) return;
17702
+ const refuse = (message) => new OwneyError(
17703
+ "ALL_AGENTS_EXCLUDED",
17704
+ message,
17705
+ { phase: "prepare", rejectedBeforeSubmission: true }
17706
+ );
17707
+ if (agentId) {
17708
+ if (excludeAgentIds.includes(agentId))
17709
+ throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
17710
+ return;
17711
+ }
17712
+ this.validateChainHasAgents(chainId);
17713
+ const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
17714
+ if (remaining.length === 0)
17715
+ throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
17716
+ }
16483
17717
  getMinDepositAmount(agent, chainId, asset) {
16484
17718
  const chainAssets = agent.supportedAssets.find(
16485
17719
  (sa) => sa.chainId === chainId
@@ -16634,9 +17868,15 @@ var OwneySDK = class {
16634
17868
  );
16635
17869
  }
16636
17870
  }
17871
+ /**
17872
+ * The agents that support this asset on this chain. `excludeDisabled` is for
17873
+ * new deposits: it also leaves out the agents unavailable for this slot this
17874
+ * session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
17875
+ * recovery still see every agent that may hold funds.
17876
+ */
16637
17877
  getEligibleAgents(chainId, asset, opts) {
16638
17878
  const eligible = [...this.agents.values()].filter((agent) => {
16639
- if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
17879
+ if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
16640
17880
  return false;
16641
17881
  }
16642
17882
  const chainAssets = agent.supportedAssets.find(
@@ -16664,20 +17904,13 @@ var OwneySDK = class {
16664
17904
  return approvalOrder || left.index - right.index;
16665
17905
  }).map(({ agent }) => agent);
16666
17906
  }
17907
+ /**
17908
+ * The user cancelled a wallet prompt, for any agent: see isWalletRejection.
17909
+ * That includes an agent error that kept the rejection only as text in
17910
+ * `details.cause`.
17911
+ */
16667
17912
  isUserRejectedWithdrawal(error) {
16668
- let current = error;
16669
- const seen = /* @__PURE__ */ new Set();
16670
- while (current && typeof current === "object" && !seen.has(current)) {
16671
- seen.add(current);
16672
- const candidate = current;
16673
- if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
16674
- const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
16675
- if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
16676
- return true;
16677
- }
16678
- current = candidate.cause;
16679
- }
16680
- return false;
17913
+ return isWalletRejection(error);
16681
17914
  }
16682
17915
  captureReadScope(requestedChain) {
16683
17916
  const original = this.requireState();
@@ -16778,6 +18011,7 @@ var OwneySDK = class {
16778
18011
  if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
16779
18012
  verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
16780
18013
  }
18014
+ if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
16781
18015
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
16782
18016
  if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
16783
18017
  agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
@@ -16786,6 +18020,33 @@ var OwneySDK = class {
16786
18020
  }
16787
18021
  return verified;
16788
18022
  }
18023
+ /**
18024
+ * Tells the agent, once per confirmed deposit transfer, that its deposit
18025
+ * landed (`IAgent.depositConfirmed`), and records the outcome on the
18026
+ * deposit's ledger operation when there is one. In the background: never
18027
+ * throws and never delays the deposit. A missed notice only leaves the
18028
+ * provider on its own schedule.
18029
+ */
18030
+ announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18031
+ try {
18032
+ if (evidence.transfer !== "confirmed") return;
18033
+ const agent = this.agents.get(evidence.agentId);
18034
+ const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
18035
+ if (!agent?.depositConfirmed || !movement) return;
18036
+ const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
18037
+ if (this.announcedDeposits.has(key2)) return;
18038
+ this.announcedDeposits.add(key2);
18039
+ if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18040
+ const legKey = `agent:${evidence.agentId}`;
18041
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18042
+ try {
18043
+ ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18044
+ } catch {
18045
+ }
18046
+ });
18047
+ } catch {
18048
+ }
18049
+ }
16789
18050
  noteFundingRefresh(key2, armed) {
16790
18051
  this.recoveredFundingReads.delete(key2);
16791
18052
  this.recoveredFundingReads.set(key2, armed);
@@ -17274,6 +18535,14 @@ var OwneySDK = class {
17274
18535
  return hash2;
17275
18536
  },
17276
18537
  ensureChain: (id) => this.ensureSwapChain(id),
18538
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
18539
+ // page cannot also hide that it landed (ROUT-726).
18540
+ readWrappedBalance: () => publicClient.readContract({
18541
+ address: wrapper.address,
18542
+ abi: ERC20_ALLOWANCE_ABI,
18543
+ functionName: "balanceOf",
18544
+ args: [walletAddress]
18545
+ }),
17277
18546
  // Read through the same public client as every other sizing input, so
17278
18547
  // a wallet sitting on the wrong chain cannot answer for this one.
17279
18548
  readAllowance: (token, spender) => publicClient.readContract({
@@ -17719,8 +18988,17 @@ var OwneySDK = class {
17719
18988
  * second half of `swapAndDeposit` on its own. Cleared only once the deposit
17720
18989
  * has actually gone through — a failure here leaves the record in place so it
17721
18990
  * can be offered again rather than silently dropped.
18991
+ *
18992
+ * The record does not remember `excludeAgentIds`, on purpose: the caller must
18993
+ * pass the CURRENT list, because the user's choice may have changed since the
18994
+ * swap (a deposit reads it fresh each time). Without it, a record with no
18995
+ * `agentId` splits across every eligible agent. When the list leaves nobody to
18996
+ * fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
18997
+ * before the wallet is touched and keeps the record.
18998
+ *
18999
+ * @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
17722
19000
  */
17723
- async completePendingDeposit(id) {
19001
+ async completePendingDeposit(id, options = {}) {
17724
19002
  const entry = listPendingDeposits().find((p) => p.id === id);
17725
19003
  if (!entry) {
17726
19004
  throw new OwneyError(
@@ -17729,6 +19007,12 @@ var OwneySDK = class {
17729
19007
  { id }
17730
19008
  );
17731
19009
  }
19010
+ this.assertDepositAgentsRemain(
19011
+ entry.chainId,
19012
+ entry.symbol,
19013
+ entry.agentId,
19014
+ options.excludeAgentIds
19015
+ );
17732
19016
  await this.ensureSwapChain(entry.chainId);
17733
19017
  const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
17734
19018
  const amount = token ? await this.settleSwapDepositAmount(
@@ -17741,6 +19025,7 @@ var OwneySDK = class {
17741
19025
  amount,
17742
19026
  asset: entry.symbol,
17743
19027
  ...entry.agentId ? { agentId: entry.agentId } : {},
19028
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
17744
19029
  // The swap's own funding-ledger operation; older records have none.
17745
19030
  ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
17746
19031
  ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
@@ -17969,6 +19254,7 @@ var OwneySDK = class {
17969
19254
  async swapAndDeposit(options) {
17970
19255
  const state = this.requireState();
17971
19256
  options.assertCurrent?.();
19257
+ this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
17972
19258
  if (options.agentId) {
17973
19259
  this.validateAssetSupport(
17974
19260
  this.getAgent(options.agentId),
@@ -18070,6 +19356,7 @@ var OwneySDK = class {
18070
19356
  amount,
18071
19357
  asset: options.to.symbol,
18072
19358
  ...options.agentId ? { agentId: options.agentId } : {},
19359
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18073
19360
  ...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
18074
19361
  ...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
18075
19362
  ...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
@@ -18609,7 +19896,7 @@ var OwneySDK = class {
18609
19896
  "A withdrawal request is already running.",
18610
19897
  { chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
18611
19898
  );
18612
- const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
19899
+ const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
18613
19900
  const attempted = /* @__PURE__ */ new Set();
18614
19901
  this.withdrawalSubmissions.add(submissionKey);
18615
19902
  let ledgerOp;
@@ -19080,6 +20367,8 @@ var OwneySDK = class {
19080
20367
  progress({ ...evidence, transfer: "failed", delivery: "failed" });
19081
20368
  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)
19082
20369
  ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
20370
+ 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"))
20371
+ ledgerLeg?.(evidence, error.code);
19083
20372
  settled({ settled: "threw", evidence });
19084
20373
  throw error;
19085
20374
  }
@@ -19187,7 +20476,7 @@ var OwneySDK = class {
19187
20476
  serverLegs.set(planned.agentId, leg);
19188
20477
  }
19189
20478
  };
19190
- const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
20479
+ const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
19191
20480
  const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
19192
20481
  if (!amount) {
19193
20482
  const results2 = {};
@@ -19587,9 +20876,10 @@ var OwneySDK = class {
19587
20876
  }
19588
20877
  async getBalances(agentId, options) {
19589
20878
  if (agentId) {
19590
- const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20879
+ const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19591
20880
  const asset = options?.asset;
19592
20881
  const agent = this.getAgent(agentId);
20882
+ const state = this.readStateFor(agentId, scope);
19593
20883
  const result = await this.readAgent(
19594
20884
  agent,
19595
20885
  "balances",
@@ -19620,10 +20910,10 @@ var OwneySDK = class {
19620
20910
  async readAggregatedBalances(options, portfolio = false) {
19621
20911
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19622
20912
  const asset = options?.asset;
19623
- const readBalance = (read2) => read2.state === state ? this.readAgent(
20913
+ const readBalance = (read2) => !read2.offChain ? this.readAgent(
19624
20914
  read2.agent,
19625
20915
  "balances",
19626
- () => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
20916
+ () => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
19627
20917
  asset ? { asset } : null
19628
20918
  ) : this.readAgent(
19629
20919
  read2.agent,
@@ -19633,7 +20923,7 @@ var OwneySDK = class {
19633
20923
  );
19634
20924
  let totalBalance = 0;
19635
20925
  const results = {};
19636
- const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
20926
+ const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
19637
20927
  const balanceResults = await Promise.allSettled(
19638
20928
  entries.map(async ([id, read2]) => {
19639
20929
  const { agent } = read2;
@@ -19688,10 +20978,11 @@ var OwneySDK = class {
19688
20978
  const chainId = this.requireChainId();
19689
20979
  if (agentId) {
19690
20980
  const agent = this.getAgent(agentId);
20981
+ const readState = this.readStateFor(agentId, state);
19691
20982
  return this.readAgent(
19692
20983
  agent,
19693
20984
  "earnings",
19694
- () => agent.getEarnings(state, chainId)
20985
+ () => agent.getEarnings(readState, chainId)
19695
20986
  );
19696
20987
  }
19697
20988
  return this.aggregateEarnings(
@@ -19700,7 +20991,7 @@ var OwneySDK = class {
19700
20991
  read2.agent,
19701
20992
  "earnings",
19702
20993
  () => read2.agent.getEarnings(read2.state, read2.chainId),
19703
- read2.state === state ? null : { chainId: read2.chainId }
20994
+ read2.offChain ? { chainId: read2.chainId } : null
19704
20995
  )
19705
20996
  );
19706
20997
  }
@@ -19711,13 +21002,13 @@ var OwneySDK = class {
19711
21002
  async refreshEarnings(agentId) {
19712
21003
  const state = this.requireState();
19713
21004
  const chainId = this.requireChainId();
19714
- const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
21005
+ const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
19715
21006
  agent,
19716
21007
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
19717
21008
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
19718
- readState === state ? null : { chainId: readChain }
21009
+ offChain ? { chainId: readChain } : null
19719
21010
  );
19720
- if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
21011
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
19721
21012
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
19722
21013
  }
19723
21014
  async aggregateEarnings(entries, read2) {
@@ -19785,7 +21076,7 @@ var OwneySDK = class {
19785
21076
  for (const agent of agents) {
19786
21077
  for (const legChainId of chainIds) {
19787
21078
  if (agentRunsOn(agent, legChainId))
19788
- legs.push({ agent, legChainId, legState: state });
21079
+ legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
19789
21080
  }
19790
21081
  }
19791
21082
  if (!agentId) {
@@ -19825,22 +21116,21 @@ var OwneySDK = class {
19825
21116
  assets: []
19826
21117
  };
19827
21118
  }
21119
+ const readState = this.readStateFor(agentId, state);
19828
21120
  return this.readAgent(
19829
21121
  agent,
19830
21122
  "dailyEarnings",
19831
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21123
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
19832
21124
  { days, tokenSymbol }
19833
21125
  );
19834
21126
  }
19835
- const entries = [...this.getActiveAgents().entries()].filter(
19836
- ([, agent]) => agent.getDailyEarnings
19837
- );
21127
+ const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
19838
21128
  const settled = await Promise.allSettled(
19839
21129
  entries.map(
19840
- ([, agent]) => this.readAgent(
21130
+ ({ agent, state: readState }) => this.readAgent(
19841
21131
  agent,
19842
21132
  "dailyEarnings",
19843
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21133
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
19844
21134
  { days, tokenSymbol }
19845
21135
  )
19846
21136
  )
@@ -19889,7 +21179,7 @@ var OwneySDK = class {
19889
21179
  `Agent ${agent.id} does not support pool customization`
19890
21180
  );
19891
21181
  }
19892
- await agent.setPoolSelection(params.selection);
21182
+ await agent.setPoolSelection(params.selection, this.state ?? void 0);
19893
21183
  }
19894
21184
  /**
19895
21185
  * The pool selection saved on the user's account (ROUT-650), so the Pools
@@ -19912,6 +21202,15 @@ var OwneySDK = class {
19912
21202
  assets: params.assets
19913
21203
  });
19914
21204
  }
21205
+ /**
21206
+ * The agents a person can customize pools for: registered, enabled, and
21207
+ * able to list a pool catalogue. Waits for agent initialization, so an agent
21208
+ * the organization disabled is known and left out.
21209
+ */
21210
+ async getPoolCustomizationAgents() {
21211
+ await this.ensureAgentsInitialized();
21212
+ return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
21213
+ }
19915
21214
  async getAccountApy({
19916
21215
  agentId,
19917
21216
  days,
@@ -19923,17 +21222,23 @@ var OwneySDK = class {
19923
21222
  const scopeChainId = scope === "all" ? null : scope;
19924
21223
  if (agentId) {
19925
21224
  const agent = this.getAgent(agentId);
19926
- return this.readAgent(
21225
+ const readState = this.readStateFor(agentId, state);
21226
+ const accountApy = await this.readAgent(
19927
21227
  agent,
19928
21228
  "accountApy",
19929
- () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
21229
+ () => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
19930
21230
  { days, tokenSymbol, scopeChainId }
19931
21231
  );
21232
+ return this.enrichApyHistory(
21233
+ accountApy,
21234
+ agentId,
21235
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21236
+ tokenSymbol
21237
+ );
19932
21238
  }
19933
- 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));
21239
+ const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
19934
21240
  const reads = await Promise.all(
19935
- entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
19936
- const offChain = readState !== state;
21241
+ entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
19937
21242
  const pair = Promise.all([
19938
21243
  this.readAgent(
19939
21244
  agent,
@@ -19965,7 +21270,12 @@ var OwneySDK = class {
19965
21270
  const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
19966
21271
  const results = {};
19967
21272
  for (const [id, apy] of apyResults) {
19968
- results[id] = apy;
21273
+ results[id] = await this.enrichApyHistory(
21274
+ apy,
21275
+ id,
21276
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21277
+ tokenSymbol
21278
+ );
19969
21279
  }
19970
21280
  const balances = {};
19971
21281
  for (const [id, bal] of balanceResults) {
@@ -19995,6 +21305,36 @@ var OwneySDK = class {
19995
21305
  history
19996
21306
  };
19997
21307
  }
21308
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
21309
+ const history = accountApy.history;
21310
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
21311
+ const incentives = await fetchApyIncentives(
21312
+ this.apiKey,
21313
+ {
21314
+ walletAddress: accountApy.walletAddress,
21315
+ agentId,
21316
+ chainId,
21317
+ asset: tokenSymbol,
21318
+ from: history[0].date,
21319
+ to: history[history.length - 1].date
21320
+ },
21321
+ this.routingApiBaseUrl
21322
+ );
21323
+ if (incentives.length === 0) return accountApy;
21324
+ const byDate = /* @__PURE__ */ new Map();
21325
+ for (const { date, ...incentive } of incentives) {
21326
+ const entries = byDate.get(date) ?? [];
21327
+ entries.push(incentive);
21328
+ byDate.set(date, entries);
21329
+ }
21330
+ return {
21331
+ ...accountApy,
21332
+ history: history.map((point) => {
21333
+ const pointIncentives = byDate.get(point.date);
21334
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
21335
+ })
21336
+ };
21337
+ }
19998
21338
  /**
19999
21339
  * Get transaction history for a specific agent, or all agents.
20000
21340
  *
@@ -20022,7 +21362,7 @@ var OwneySDK = class {
20022
21362
  for (const agent of agents) {
20023
21363
  for (const legChainId of chainIds) {
20024
21364
  if (agentRunsOn(agent, legChainId))
20025
- legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
21365
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
20026
21366
  }
20027
21367
  }
20028
21368
  if (!agentId) {
@@ -20066,7 +21406,8 @@ var OwneySDK = class {
20066
21406
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20067
21407
  if (agentId) {
20068
21408
  const agent = this.getAgent(agentId);
20069
- const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
21409
+ const readState = this.readStateFor(agentId, state);
21410
+ const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
20070
21411
  assertCurrent();
20071
21412
  return page;
20072
21413
  }
@@ -20080,10 +21421,11 @@ var OwneySDK = class {
20080
21421
  }
20081
21422
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
20082
21423
  try {
21424
+ const readState = this.readStateFor(agent.id, state);
20083
21425
  const page = await this.readAgent(
20084
21426
  agent,
20085
21427
  "history",
20086
- () => agent.getHistory(state, chainId, agentFilters),
21428
+ () => agent.getHistory(readState, chainId, agentFilters),
20087
21429
  agentFilters
20088
21430
  );
20089
21431
  return { agentId: agent.id, page };
@@ -20141,20 +21483,20 @@ var OwneySDK = class {
20141
21483
  const chainId = this.requireChainId();
20142
21484
  if (agentId) {
20143
21485
  const agent = this.getAgent(agentId);
21486
+ const readState = this.readStateFor(agentId, state);
20144
21487
  return this.readAgent(
20145
21488
  agent,
20146
21489
  "profile",
20147
- () => agent.getUserProfile(state, chainId)
21490
+ () => agent.getUserProfile(readState, chainId)
20148
21491
  );
20149
21492
  }
20150
21493
  const results = {};
20151
- const entries = [...this.getActiveAgents().entries()];
20152
21494
  const profileResults = await Promise.all(
20153
- entries.map(async ([id, agent]) => {
21495
+ this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
20154
21496
  const p = await this.readAgent(
20155
21497
  agent,
20156
21498
  "profile",
20157
- () => agent.getUserProfile(state, chainId)
21499
+ () => agent.getUserProfile(readState, chainId)
20158
21500
  );
20159
21501
  return [id, p];
20160
21502
  })
@@ -20364,10 +21706,11 @@ var OwneySDK = class {
20364
21706
  const entries = [...activeAgents.entries()];
20365
21707
  const balanceResults = await Promise.allSettled(
20366
21708
  entries.map(async ([id, agent]) => {
21709
+ const readState = this.readStateFor(id, state);
20367
21710
  const b = await this.readAgent(
20368
21711
  agent,
20369
21712
  "balances",
20370
- () => agent.getBalances(state, chainId)
21713
+ () => agent.getBalances(readState, chainId)
20371
21714
  );
20372
21715
  return [id, b.positions ?? []];
20373
21716
  })
@@ -20649,5 +21992,6 @@ export {
20649
21992
  saveWithdrawSwap,
20650
21993
  setOwneyDebug,
20651
21994
  subscribeWithdrawSwaps,
21995
+ switchWalletConnectChain,
20652
21996
  updateWithdrawSwap
20653
21997
  };