@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.cjs CHANGED
@@ -679,6 +679,7 @@ __export(index_exports, {
679
679
  saveWithdrawSwap: () => saveWithdrawSwap,
680
680
  setOwneyDebug: () => setOwneyDebug,
681
681
  subscribeWithdrawSwaps: () => subscribeWithdrawSwaps,
682
+ switchWalletConnectChain: () => switchWalletConnectChain,
682
683
  updateWithdrawSwap: () => updateWithdrawSwap
683
684
  });
684
685
  module.exports = __toCommonJS(index_exports);
@@ -1123,6 +1124,35 @@ function debugLog(scope, message, data) {
1123
1124
  init_errors();
1124
1125
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
1125
1126
  var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
1127
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
1128
+ const query2 = new URLSearchParams({
1129
+ walletAddress: input.walletAddress,
1130
+ agentId: input.agentId,
1131
+ chainId: String(input.chainId),
1132
+ asset: input.asset.toUpperCase(),
1133
+ from: input.from,
1134
+ to: input.to
1135
+ });
1136
+ try {
1137
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
1138
+ headers: {
1139
+ Accept: "application/json",
1140
+ "x-owney-api-key": apiKey
1141
+ }
1142
+ });
1143
+ if (!response.ok) return [];
1144
+ const body = await response.json();
1145
+ if (!body.success || !Array.isArray(body.data)) return [];
1146
+ return body.data.filter(
1147
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
1148
+ );
1149
+ } catch (error) {
1150
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
1151
+ error: error instanceof Error ? error.message : String(error)
1152
+ });
1153
+ return [];
1154
+ }
1155
+ }
1126
1156
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
1127
1157
  const url = `${baseUrl}/api/v1/agent/org-config`;
1128
1158
  try {
@@ -1653,7 +1683,7 @@ var SnapshotHistory = class {
1653
1683
  };
1654
1684
 
1655
1685
  // src/lib/funding-ledger.ts
1656
- var SDK_VERSION = "0.7.32-beta.5";
1686
+ var SDK_VERSION = "0.7.32-beta.7";
1657
1687
  var SCOPE2 = "funding-ledger";
1658
1688
  var REQUEST_TIMEOUT_MS2 = 5e3;
1659
1689
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -2968,7 +2998,7 @@ var CHAIN_NAMES = {
2968
2998
  function chainName(chainId) {
2969
2999
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2970
3000
  }
2971
- var SETTLE_TIMEOUT_MS = 8e3;
3001
+ var SETTLE_TIMEOUT_MS = 15e3;
2972
3002
  var POLL_INTERVAL_MS = 200;
2973
3003
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2974
3004
  async function readChainId(pub) {
@@ -4515,19 +4545,31 @@ function mapAvailablePools(raw2) {
4515
4545
  for (const [token, entry] of Object.entries(byToken ?? {})) {
4516
4546
  for (const pool of entry?.pools ?? []) {
4517
4547
  if (!pool?.name) continue;
4548
+ const link = pool.info?.url || pool.info?.link || null;
4549
+ const address = vaultAddressFromLink(link);
4518
4550
  result.push({
4519
4551
  chainId,
4520
4552
  token,
4521
4553
  name: pool.name,
4522
4554
  apy: pool.info?.combined_apy ?? null,
4523
4555
  tvlUsd: pool.info?.tvlUsd ?? null,
4524
- link: pool.info?.link ?? null
4556
+ link,
4557
+ ...address !== void 0 && { address }
4525
4558
  });
4526
4559
  }
4527
4560
  }
4528
4561
  }
4529
4562
  return result;
4530
4563
  }
4564
+ var VAULT_IN_PATH = /\/(?:vault|lend)\/(0x[0-9a-fA-F]{40})(?=\/|$)/;
4565
+ function vaultAddressFromLink(link) {
4566
+ if (!link) return void 0;
4567
+ try {
4568
+ return new URL(link).pathname.match(VAULT_IN_PATH)?.[1];
4569
+ } catch {
4570
+ return void 0;
4571
+ }
4572
+ }
4531
4573
  function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
4532
4574
  const wanted = asset.toUpperCase();
4533
4575
  const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
@@ -5114,11 +5156,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
5114
5156
  if (typeof window === "undefined") return;
5115
5157
  const internals = sdk;
5116
5158
  const original = internals.authenticateUser.bind(internals);
5117
- internals.authenticateUser = async () => {
5159
+ let inFlight2 = null;
5160
+ const authenticate = async () => {
5118
5161
  if (internals.authenticatedUserId !== null) return;
5119
5162
  const address = internals.walletClient?.account?.address;
5120
- const chainId = internals.currentChainId;
5121
- if (address && chainId) {
5163
+ const chainId = internals.currentChainId ?? 0;
5164
+ if (address) {
5122
5165
  const cached = readSession(address, chainId);
5123
5166
  if (cached) {
5124
5167
  internals.httpClient.setAuthToken(cached.token);
@@ -5130,9 +5173,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
5130
5173
  }
5131
5174
  await original();
5132
5175
  const newAddress = internals.walletClient?.account?.address;
5133
- const newChainId = internals.currentChainId;
5176
+ const newChainId = internals.currentChainId ?? 0;
5134
5177
  const newToken = internals.httpClient.authToken;
5135
- if (newAddress && newChainId && newToken) {
5178
+ if (newAddress && newToken) {
5136
5179
  writeSession(newAddress, newChainId, {
5137
5180
  token: newToken,
5138
5181
  userId: internals.authenticatedUserId,
@@ -5141,6 +5184,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
5141
5184
  });
5142
5185
  }
5143
5186
  };
5187
+ internals.authenticateUser = () => {
5188
+ const address = internals.walletClient?.account?.address?.toLowerCase();
5189
+ if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
5190
+ const promise = authenticate().finally(() => {
5191
+ if (inFlight2?.promise === promise) inFlight2 = null;
5192
+ });
5193
+ inFlight2 = { address, promise };
5194
+ return promise;
5195
+ };
5144
5196
  }
5145
5197
  // --- Private helpers ---
5146
5198
  getAddress() {
@@ -5373,12 +5425,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
5373
5425
  }
5374
5426
  // --- IAgent: Account lifecycle ---
5375
5427
  async activateAgent(state, chainId) {
5428
+ const startedAt = Date.now();
5376
5429
  try {
5377
5430
  debugLog("zyfai:activation", "starting", {
5378
5431
  walletAddress: state.walletAddress,
5379
5432
  chainId
5380
5433
  });
5381
5434
  await this.connectAuth(state, chainId);
5435
+ debugLog("zyfai:activation", "signed in", {
5436
+ ms: Date.now() - startedAt
5437
+ });
5382
5438
  const validChainId = isValidChainId(chainId);
5383
5439
  await Promise.all([
5384
5440
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -5389,7 +5445,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5389
5445
  // validator, so pool-wallet users see no prompt. Non-fatal.
5390
5446
  this.ensureSessionKeyIfDeployed(validChainId)
5391
5447
  ]);
5392
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
5448
+ debugLog("zyfai:activation", "completed", {
5449
+ chainId: validChainId,
5450
+ ms: Date.now() - startedAt
5451
+ });
5393
5452
  } catch (error) {
5394
5453
  throw error;
5395
5454
  }
@@ -7085,6 +7144,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7085
7144
  const generation = this.earningsGeneration;
7086
7145
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
7087
7146
  const raw2 = await this.sdk.getPortfolio(this.getAddress());
7147
+ debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
7088
7148
  const balance = mapBalances(raw2, validChainId, smartWallet);
7089
7149
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
7090
7150
  for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
@@ -7488,6 +7548,27 @@ var import_viem17 = require("viem");
7488
7548
  var import_chains4 = require("viem/chains");
7489
7549
  init_errors();
7490
7550
 
7551
+ // src/lib/wallet-rejection.ts
7552
+ var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
7553
+ function isWalletRejection(error) {
7554
+ let current = error;
7555
+ const seen = /* @__PURE__ */ new Set();
7556
+ while (current && typeof current === "object" && !seen.has(current)) {
7557
+ seen.add(current);
7558
+ const candidate = current;
7559
+ if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
7560
+ const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
7561
+ if (REJECTION_MESSAGE.test(message)) return true;
7562
+ const details = candidate.details;
7563
+ if (details && typeof details === "object") {
7564
+ const cause = details.cause;
7565
+ if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
7566
+ }
7567
+ current = candidate.cause;
7568
+ }
7569
+ return false;
7570
+ }
7571
+
7491
7572
  // src/agents/yieldseeker/yieldseeker.auth.ts
7492
7573
  var import_siwe = require("siwe");
7493
7574
  var import_viem11 = require("viem");
@@ -8530,11 +8611,13 @@ function mapYieldseekerProfile(address, contexts) {
8530
8611
  protocols: [...protocols]
8531
8612
  };
8532
8613
  }
8533
- function mapYieldseekerAgentApy(stats) {
8614
+ function mapYieldseekerAgentApy(stats, days) {
8534
8615
  const perAsset = {};
8535
8616
  const all = [];
8536
8617
  for (const entry of stats) {
8537
- const expected = percent(entry.stats.expectedApy7d);
8618
+ const expected = percent(
8619
+ days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
8620
+ );
8538
8621
  if (!Number.isFinite(expected)) continue;
8539
8622
  perAsset[entry.asset] = expected;
8540
8623
  all.push(expected);
@@ -8705,6 +8788,15 @@ function sponsorError(message, safeToFallback, details = {}) {
8705
8788
  "yieldseeker"
8706
8789
  );
8707
8790
  }
8791
+ function cannotSignRawHash(error) {
8792
+ for (let current = error, depth = 0; current && depth < 5; depth++) {
8793
+ const code = current.code;
8794
+ if (code === -32602 || code === -32601 || code === 4200) return true;
8795
+ if (code === 4001) return false;
8796
+ current = current.cause;
8797
+ }
8798
+ return false;
8799
+ }
8708
8800
  function assertIntentFresh(expiresAt) {
8709
8801
  if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
8710
8802
  throw sponsorError(
@@ -9066,7 +9158,18 @@ async function submitEoa(input) {
9066
9158
  transport: (0, import_viem15.custom)(input.state.provider)
9067
9159
  });
9068
9160
  input.assertCurrent?.();
9069
- const signature = await wallet.signMessage({ message: { raw: userOpHash } });
9161
+ let signature;
9162
+ try {
9163
+ signature = await wallet.signMessage({ message: { raw: userOpHash } });
9164
+ } catch (error) {
9165
+ if (cannotSignRawHash(error))
9166
+ throw sponsorError(
9167
+ "This wallet cannot sign the gas-free withdrawal.",
9168
+ true,
9169
+ { failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
9170
+ );
9171
+ throw error;
9172
+ }
9070
9173
  operation = { ...operation, signature };
9071
9174
  await assertOwnerSession(input.state, input.owner);
9072
9175
  assertIntentFresh(input.expiresAt);
@@ -9338,11 +9441,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
9338
9441
  var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
9339
9442
  var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
9340
9443
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
9444
+ var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
9445
+ var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
9446
+ var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
9447
+ var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
9341
9448
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
9342
9449
  var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
9343
9450
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
9344
9451
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
9345
9452
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
9453
+ function apyAsPercent(fraction) {
9454
+ if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
9455
+ return Number((fraction * 100).toPrecision(12));
9456
+ }
9457
+ function isActiveMemory(memory2) {
9458
+ return !!memory2 && memory2.isActive !== false && memory2.isDeleted !== true;
9459
+ }
9460
+ function vaultOptionsKey(asset, includeUnavailable) {
9461
+ return `${asset}:${includeUnavailable ? "all" : "usable"}`;
9462
+ }
9463
+ function isManagedVaultList(memory2) {
9464
+ return memory2.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
9465
+ }
9466
+ function isLegacyPoolSelectionMemory(memory2) {
9467
+ if (isManagedVaultList(memory2) || typeof memory2.content !== "string") return false;
9468
+ const content = memory2.content.trim();
9469
+ return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
9470
+ }
9471
+ function uniqueAddresses(addresses) {
9472
+ const seen = /* @__PURE__ */ new Set();
9473
+ return addresses.filter((address) => {
9474
+ const key2 = address.toLowerCase();
9475
+ if (seen.has(key2)) return false;
9476
+ seen.add(key2);
9477
+ return true;
9478
+ });
9479
+ }
9480
+ function sameVaults(actual, expected) {
9481
+ const want = new Set(expected.map((address) => address.toLowerCase()));
9482
+ const got = new Set(actual.map((address) => address.toLowerCase()));
9483
+ return got.size === want.size && [...want].every((address) => got.has(address));
9484
+ }
9346
9485
  function isYieldseekerWalletCodeMissing(error) {
9347
9486
  for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
9348
9487
  const { name, message } = current;
@@ -9352,6 +9491,8 @@ function isYieldseekerWalletCodeMissing(error) {
9352
9491
  return false;
9353
9492
  }
9354
9493
  var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
9494
+ var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
9495
+ var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
9355
9496
  var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
9356
9497
  var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
9357
9498
  var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
@@ -9371,6 +9512,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
9371
9512
  var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
9372
9513
  var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
9373
9514
  var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
9515
+ var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
9374
9516
  var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
9375
9517
  var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
9376
9518
  function generateYieldseekerUsername() {
@@ -9463,9 +9605,31 @@ var YieldseekerAgent = class {
9463
9605
  walletContexts = /* @__PURE__ */ new Map();
9464
9606
  agentAccountReads = /* @__PURE__ */ new Map();
9465
9607
  reportedAccounts = /* @__PURE__ */ new Set();
9466
- // Slots whose verified agent is missing even from a re-read list, until the
9467
- // list cache window ends. Stops a re-read on every portfolio poll.
9608
+ // Slots whose verified agent is missing even from a re-read list (and could
9609
+ // not be reopened), with the error the lookup failed with, until the list
9610
+ // cache window ends. Stops a re-read and a reactivate on every portfolio poll.
9468
9611
  missingSlots = /* @__PURE__ */ new Map();
9612
+ // A remembered rate limit rethrown with the time left on its marker
9613
+ // (throwIfSlotMissing), mapped to the remembered error it copies, so
9614
+ // isMarkedSlotFailure still recognises it.
9615
+ rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
9616
+ // Slots whose verified agent Yieldseeker will never reopen (a reactivate
9617
+ // answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
9618
+ // slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
9619
+ // it is kept for the session, like unavailableSlots: reads and deposits get
9620
+ // it with no request until disconnect, or until a lookup selects an agent
9621
+ // for the slot.
9622
+ closedSlots = /* @__PURE__ */ new Map();
9623
+ // In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
9624
+ // shared by concurrent lookups of one slot.
9625
+ pendingReopens = /* @__PURE__ */ new Map();
9626
+ // Slots Yieldseeker will not give an agent this session (a reactivate answered
9627
+ // an active-agent limit), keyed by slotKey, with the provider's limit code.
9628
+ // Never expires: it answers without a request until disconnect.
9629
+ unavailableSlots = /* @__PURE__ */ new Map();
9630
+ // In-flight reactivates keyed by slotKey + agentId, shared by every caller
9631
+ // (a read-time reopen, deposits): one request however many ask.
9632
+ pendingReactivates = /* @__PURE__ */ new Map();
9469
9633
  // In-flight cache-bypassing list reads, shared by concurrent callers.
9470
9634
  freshListReads = /* @__PURE__ */ new Map();
9471
9635
  // Every contextKey computed this session; asset-only calls fall back to them.
@@ -9518,6 +9682,7 @@ var YieldseekerAgent = class {
9518
9682
  ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
9519
9683
  /** slotKey -> the last successful ledger rows and when they arrived. */
9520
9684
  lastLedgerRows = /* @__PURE__ */ new Map();
9685
+ /** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
9521
9686
  vaultOptions = /* @__PURE__ */ new Map();
9522
9687
  pendingVaultOptions = /* @__PURE__ */ new Map();
9523
9688
  assetApyStats = /* @__PURE__ */ new Map();
@@ -9574,6 +9739,121 @@ var YieldseekerAgent = class {
9574
9739
  this.pendingWalletStatus.set(key2, pending2);
9575
9740
  return { ...await pending2 };
9576
9741
  }
9742
+ /**
9743
+ * Deposits go only to an agent Yieldseeker still has open. The session caches
9744
+ * the selected agent, so a tab left open can hold one Yieldseeker has since
9745
+ * closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
9746
+ * bypassing the cached wallet contexts, and:
9747
+ * - open, same wallet address: returns the context to deposit with;
9748
+ * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9749
+ * continues only when it is now open with the same address. Only the
9750
+ * verified record's agent is reopened: any other closed agent (a
9751
+ * superseded-wallet match, or a named agent with no verified record, also
9752
+ * when the accounts could not be read) refuses without a request;
9753
+ * - anything else refuses with nothing sent, before any progress event,
9754
+ * signature or callback. Every refusal carries `notSubmitted` and
9755
+ * `safeToFallback: false`, so no paid fallback runs.
9756
+ * A slot recorded unavailable (the active-agent limit) refuses at once with
9757
+ * no request. The reactivate goes through reactivateSlot, which shares one
9758
+ * request per slot and remembers a failure for the list-cache window, so
9759
+ * repeated deposits do not repeat it. A failed wallet read fails closed
9760
+ * (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
9761
+ * gate. A reactivate that fails keeps its error code
9762
+ * (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
9763
+ * failure). At the limit the slot is also recorded unavailable for the
9764
+ * session (see isSlotUnavailable). Session changes keep their own
9765
+ * NOT_CONNECTED error.
9766
+ */
9767
+ async assertAgentOpen(state, chainId, asset, context) {
9768
+ const generation = this.readGeneration;
9769
+ const agentId = context.agent.agentId;
9770
+ const agentWallet = context.wallet.walletAddress;
9771
+ const refusal = { notSubmitted: true, safeToFallback: false };
9772
+ const slot = this.slotKey(state, chainId, asset);
9773
+ const unavailable = this.unavailableSlots.get(slot);
9774
+ if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
9775
+ const readWallet = async () => {
9776
+ let fresh2;
9777
+ try {
9778
+ const answer = await this.walletRequest(
9779
+ state,
9780
+ chainId,
9781
+ this.agentPath(context, "wallet")
9782
+ );
9783
+ if (!answer?.agentWallet || !(0, import_viem17.isAddress)(answer.agentWallet.walletAddress)) {
9784
+ throw this.invalidResponse("agent wallet");
9785
+ }
9786
+ fresh2 = answer.agentWallet;
9787
+ } catch (error) {
9788
+ this.assertSession(generation, chainId, asset);
9789
+ throw new OwneyError(
9790
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9791
+ "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
9792
+ {
9793
+ ...refusal,
9794
+ reason: "UNAVAILABLE",
9795
+ agentWallet,
9796
+ asset,
9797
+ cause: error instanceof Error ? error.message : String(error)
9798
+ },
9799
+ this.id
9800
+ );
9801
+ }
9802
+ this.assertSession(generation, chainId, asset);
9803
+ return fresh2;
9804
+ };
9805
+ let fresh = await readWallet();
9806
+ let reopened = false;
9807
+ if (fresh.deactivatedDate) {
9808
+ this.forgetAgentWallet(agentId);
9809
+ const accounts = await this.agentAccounts(state, chainId);
9810
+ this.assertSession(generation, chainId, asset);
9811
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
9812
+ if (!verified || verified.providerAgentId !== agentId) {
9813
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
9814
+ }
9815
+ let result;
9816
+ try {
9817
+ result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
9818
+ } catch (error) {
9819
+ this.assertSession(generation, chainId, asset);
9820
+ const failure = error instanceof OwneyError ? error : this.mapApiError(error);
9821
+ if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
9822
+ const { providerCode, reason } = failure.details ?? {};
9823
+ throw this.agentClosed(
9824
+ chainId,
9825
+ asset,
9826
+ agentId,
9827
+ typeof providerCode === "string" ? providerCode : void 0,
9828
+ { ...refusal, ...typeof reason === "string" ? { reason } : {} }
9829
+ );
9830
+ }
9831
+ throw new OwneyError(
9832
+ failure.code,
9833
+ `Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
9834
+ { ...failure.details, ...refusal, cause: failure.message },
9835
+ failure.agentId
9836
+ );
9837
+ }
9838
+ this.assertSession(generation, chainId, asset);
9839
+ if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
9840
+ this.forgetAgentWallet(agentId);
9841
+ fresh = await readWallet();
9842
+ if (fresh.deactivatedDate) {
9843
+ this.rememberMissingSlot(
9844
+ slot,
9845
+ generation,
9846
+ this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
9847
+ );
9848
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
9849
+ }
9850
+ reopened = true;
9851
+ }
9852
+ if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
9853
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
9854
+ }
9855
+ return reopened ? { ...context, wallet: fresh } : context;
9856
+ }
9577
9857
  /**
9578
9858
  * Deposits go only to a wallet whose identity is verified on chain (factory
9579
9859
  * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
@@ -9883,6 +10163,10 @@ var YieldseekerAgent = class {
9883
10163
  this.pendingSlotInvalidations.clear();
9884
10164
  this.knownContextKeys.clear();
9885
10165
  this.missingSlots.clear();
10166
+ this.closedSlots.clear();
10167
+ this.pendingReopens.clear();
10168
+ this.pendingReactivates.clear();
10169
+ this.unavailableSlots.clear();
9886
10170
  this.freshListReads.clear();
9887
10171
  this.balanceVaults.clear();
9888
10172
  this.pendingAgents.clear();
@@ -9910,11 +10194,43 @@ var YieldseekerAgent = class {
9910
10194
  this.planHistoryKeys.clear();
9911
10195
  this.lastLedgerRows.clear();
9912
10196
  }
10197
+ /**
10198
+ * Ready every asset's agent, `asset` first: a missing one is created and a
10199
+ * closed one reopened (2026-11-06). A slot Yieldseeker will never let the
10200
+ * user have (the agent limit, closed for good, missing with no way to
10201
+ * reopen) is rethrown with `details.permanent`, which refuses the connect.
10202
+ * A temporary failure (an API error or timeout) on another asset does not:
10203
+ * that slot answers again where it is needed. On the selected asset every
10204
+ * failure is thrown as before, without readying the rest, so a failed
10205
+ * sign-in never opens a second prompt.
10206
+ */
9913
10207
  async activateAgent(state, chainId, asset) {
9914
10208
  this.assertChain(chainId);
9915
10209
  const targetAsset = asset ?? "USDC";
9916
10210
  this.assertAsset(targetAsset);
9917
- await this.ensureAgent(state, chainId, targetAsset);
10211
+ const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
10212
+ for (const each of [targetAsset, ...others]) {
10213
+ try {
10214
+ await this.ensureAgent(state, chainId, each);
10215
+ } catch (error) {
10216
+ if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
10217
+ const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
10218
+ if (each === targetAsset || !temporary) throw error;
10219
+ debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
10220
+ code: error.code,
10221
+ statusCode: error.details?.statusCode
10222
+ });
10223
+ }
10224
+ }
10225
+ }
10226
+ /** The same failure, marked as one that will not go away this session. */
10227
+ permanentFailure(error) {
10228
+ const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
10229
+ return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
10230
+ }
10231
+ isSlotUnavailable(state, chainId, asset) {
10232
+ if (asset !== "USDC" && asset !== "WETH") return false;
10233
+ return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
9918
10234
  }
9919
10235
  async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
9920
10236
  this.assertChain(chainId);
@@ -9927,7 +10243,20 @@ var YieldseekerAgent = class {
9927
10243
  this.id
9928
10244
  );
9929
10245
  }
9930
- const context = await this.ensureAgent(state, chainId, asset);
10246
+ const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
10247
+ if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
10248
+ const { agentId, providerCode, reason } = error.details ?? {};
10249
+ throw this.agentClosed(
10250
+ chainId,
10251
+ asset,
10252
+ typeof agentId === "string" ? agentId : "",
10253
+ typeof providerCode === "string" ? providerCode : void 0,
10254
+ { notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
10255
+ );
10256
+ }
10257
+ throw error;
10258
+ });
10259
+ const context = await this.assertAgentOpen(state, chainId, asset, selected);
9931
10260
  await this.assertDepositWalletVerified(state, chainId, asset, context);
9932
10261
  const generation = this.readGeneration;
9933
10262
  const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
@@ -10117,15 +10446,14 @@ var YieldseekerAgent = class {
10117
10446
  if (timer) clearTimeout(timer);
10118
10447
  }
10119
10448
  };
10120
- const feeRateRead = amount === void 0 ? Promise.resolve(0) : boundedVerification(
10121
- (() => {
10122
- try {
10123
- return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
10124
- } catch (error) {
10125
- return Promise.reject(error);
10126
- }
10127
- })().catch(() => void 0)
10128
- );
10449
+ const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
10450
+ try {
10451
+ return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
10452
+ } catch (error) {
10453
+ return Promise.reject(error);
10454
+ }
10455
+ })().catch(() => void 0);
10456
+ const feeRateRead = boundedVerification(feeRateAnswer);
10129
10457
  const positionsRead = this.readWithdrawalPositions(state, chainId, context);
10130
10458
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
10131
10459
  const agentWallet = (0, import_viem17.getAddress)(context.wallet.walletAddress);
@@ -10435,9 +10763,10 @@ var YieldseekerAgent = class {
10435
10763
  }
10436
10764
  const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10437
10765
  const availableForOwner = ownerFunds.available;
10438
- const feeRate = feeRateBps ?? 0;
10439
- const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
10440
10766
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10767
+ const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
10768
+ this.assertSession(generation, chainId, asset);
10769
+ const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
10441
10770
  if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
10442
10771
  this.invalidateFundingRead(state, chainId, asset);
10443
10772
  if (amount === void 0 && positionsStatus !== "empty")
@@ -10691,7 +11020,7 @@ var YieldseekerAgent = class {
10691
11020
  positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
10692
11021
  const needsInventory = !proof.inventoryComplete;
10693
11022
  if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
10694
- const catalog = await this.loadVaultOptions(asset).catch(() => []);
11023
+ const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
10695
11024
  const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && (0, import_viem17.isAddress)(o.address));
10696
11025
  if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
10697
11026
  for (const option of eligible) {
@@ -10767,7 +11096,8 @@ var YieldseekerAgent = class {
10767
11096
  const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
10768
11097
  const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
10769
11098
  const receivedAssets = new Set((historic?.movements ?? []).filter((movement) => movement.chainId === chainId && movement.agentWalletId === context.wallet.agentWalletId && movement.toAddress?.toLowerCase() === context.wallet.walletAddress.toLowerCase()).filter((movement) => typeof movement.assetAddress === "string").map((movement) => movement.assetAddress.toLowerCase()));
10770
- for (const option of this.vaultOptions.get(context.asset)?.value ?? []) {
11099
+ const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
11100
+ for (const option of cachedOptions?.value ?? []) {
10771
11101
  if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !(0, import_viem17.isAddress)(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
10772
11102
  hints.set(option.address.toLowerCase(), {
10773
11103
  vaultOption: option,
@@ -10980,7 +11310,7 @@ var YieldseekerAgent = class {
10980
11310
  assertReadCurrent();
10981
11311
  return proof(true);
10982
11312
  }
10983
- const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
11313
+ const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
10984
11314
  assertReadCurrent();
10985
11315
  const eligible = /* @__PURE__ */ new Map();
10986
11316
  for (const option of catalog ?? []) {
@@ -11123,8 +11453,37 @@ var YieldseekerAgent = class {
11123
11453
  }
11124
11454
  return false;
11125
11455
  }
11456
+ /**
11457
+ * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
11458
+ * it now instead of on its next 30-minute check. Yieldseeker decides whether
11459
+ * anything moves (the funding minimum, a deployed agent, no manual
11460
+ * withdrawal in the last hour). Uses the agent this session already knows
11461
+ * for the asset and the saved sign-in only: never prompts, never retries,
11462
+ * never throws.
11463
+ */
11464
+ async depositConfirmed(state, chainId, evidence) {
11465
+ try {
11466
+ const asset = String(evidence.token).toUpperCase();
11467
+ if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
11468
+ return { notified: false, reason: "UNSUPPORTED" };
11469
+ const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11470
+ if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
11471
+ return { notified: false, reason: "NO_AGENT" };
11472
+ if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11473
+ await this.walletRequest(
11474
+ state,
11475
+ chainId,
11476
+ this.agentPath(context, "deposit-made"),
11477
+ { method: "POST", body: {}, promptless: true }
11478
+ );
11479
+ return { notified: true };
11480
+ } catch (error) {
11481
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
11482
+ }
11483
+ }
11126
11484
  async getFundingWallet(state, chainId, asset) {
11127
11485
  this.assertAsset(asset);
11486
+ this.throwIfSlotUnavailable(state, chainId, asset);
11128
11487
  const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11129
11488
  if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
11130
11489
  return context.wallet.walletAddress;
@@ -11185,7 +11544,7 @@ var YieldseekerAgent = class {
11185
11544
  });
11186
11545
  const catalog = await Promise.all(
11187
11546
  [...new Set(contexts.map((context) => context.asset))].map(
11188
- (contextAsset) => this.loadVaultOptions(contextAsset)
11547
+ (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
11189
11548
  )
11190
11549
  );
11191
11550
  const vaultAddresses = new Set(
@@ -11210,11 +11569,11 @@ var YieldseekerAgent = class {
11210
11569
  );
11211
11570
  }
11212
11571
  async getAgentApy(days, options) {
11213
- if (!this.supportsAgentApyPeriod(days)) {
11572
+ if (days === "14D") {
11214
11573
  throw new OwneyError(
11215
11574
  "AGENT_APY_PERIOD_UNSUPPORTED",
11216
11575
  `Yieldseeker does not provide a representative ${days} strategy APY.`,
11217
- { days, supportedDays: ["7D"] },
11576
+ { days, supportedDays: ["7D", "30D"] },
11218
11577
  this.id
11219
11578
  );
11220
11579
  }
@@ -11227,10 +11586,10 @@ var YieldseekerAgent = class {
11227
11586
  return { asset, stats: await this.loadAssetApyStats(asset) };
11228
11587
  })
11229
11588
  );
11230
- return mapYieldseekerAgentApy(values);
11589
+ return mapYieldseekerAgentApy(values, days);
11231
11590
  }
11232
11591
  supportsAgentApyPeriod(days) {
11233
- return days === "7D";
11592
+ return days === "7D" || days === "30D";
11234
11593
  }
11235
11594
  async loadAssetApyStats(asset) {
11236
11595
  const cached = this.assetApyStats.get(asset);
@@ -11242,7 +11601,7 @@ var YieldseekerAgent = class {
11242
11601
  `/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
11243
11602
  ).then((response) => {
11244
11603
  const stats = response?.assetApyStats;
11245
- if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d)) {
11604
+ if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d) || typeof stats.expectedApy30d !== "number" || !Number.isFinite(stats.expectedApy30d)) {
11246
11605
  throw this.invalidResponse("asset APY statistics");
11247
11606
  }
11248
11607
  this.assetApyStats.set(asset, {
@@ -11254,27 +11613,321 @@ var YieldseekerAgent = class {
11254
11613
  this.pendingAssetApyStats.set(asset, request2);
11255
11614
  return request2;
11256
11615
  }
11257
- async loadVaultOptions(asset) {
11258
- const cached = this.vaultOptions.get(asset);
11616
+ /**
11617
+ * The deposit-time Pools step's catalogue: every vault Yieldseeker lists
11618
+ * for a new agent on `asset` on Base, grouped by provider (the provider is
11619
+ * both `protocolId` and `name`). Nothing is filtered on our side, on
11620
+ * liquidity, size or provider. `strategy` is accepted for the IAgent
11621
+ * contract and ignored.
11622
+ */
11623
+ async getPoolCatalog(params) {
11624
+ const asset = params.asset.toUpperCase();
11625
+ this.assertAsset(asset);
11626
+ const byProvider = /* @__PURE__ */ new Map();
11627
+ for (const vault of await this.loadVaultOptions(asset)) {
11628
+ const pools = byProvider.get(vault.provider) ?? [];
11629
+ pools.push({
11630
+ chainId: 8453,
11631
+ token: asset,
11632
+ name: vault.name,
11633
+ apy: apyAsPercent(vault.totalApy),
11634
+ tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
11635
+ link: null,
11636
+ address: vault.address
11637
+ });
11638
+ byProvider.set(vault.provider, pools);
11639
+ }
11640
+ return [...byProvider].map(([provider, pools]) => ({
11641
+ protocolId: provider,
11642
+ name: provider,
11643
+ logo: null,
11644
+ pools
11645
+ }));
11646
+ }
11647
+ /**
11648
+ * The asset's vaults on Base. By default only those a new agent can use:
11649
+ * Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
11650
+ * among them), gated or can't use, so the picker follows its list
11651
+ * (2026-11-04). `includeUnavailable` adds those back, for anything about
11652
+ * money an agent may still hold in one: withdrawals and activity.
11653
+ */
11654
+ async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
11655
+ const key2 = vaultOptionsKey(asset, includeUnavailable);
11656
+ const cached = this.vaultOptions.get(key2);
11259
11657
  if (cached && cached.expiresAt > Date.now()) return cached.value;
11260
- const pending2 = this.pendingVaultOptions.get(asset);
11658
+ const pending2 = this.pendingVaultOptions.get(key2);
11261
11659
  if (pending2) return pending2;
11262
11660
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
11263
11661
  const request2 = this.api.request(
11264
- `/chains/8453/assets/${metadata.address}/vault-options`
11662
+ `/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
11265
11663
  ).then((response) => {
11266
11664
  if (!Array.isArray(response?.vaultOptions)) {
11267
11665
  throw this.invalidResponse("vault options");
11268
11666
  }
11269
- this.vaultOptions.set(asset, {
11667
+ this.vaultOptions.set(key2, {
11270
11668
  expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
11271
11669
  value: response.vaultOptions
11272
11670
  });
11273
11671
  return response.vaultOptions;
11274
- }).finally(() => this.pendingVaultOptions.delete(asset));
11275
- this.pendingVaultOptions.set(asset, request2);
11672
+ }).finally(() => this.pendingVaultOptions.delete(key2));
11673
+ this.pendingVaultOptions.set(key2, request2);
11276
11674
  return request2;
11277
11675
  }
11676
+ /**
11677
+ * Save the user's Yieldseeker picks as the agent's managed vault list, then
11678
+ * read the rules back before any money moves. Each asset has its own agent,
11679
+ * so each is saved on its own. `pools` and `availablePools` hold vault
11680
+ * addresses.
11681
+ *
11682
+ * - Only Base entries are ours. An asset with no picks whose entries showed
11683
+ * no vault is skipped and nothing is sent.
11684
+ * - Some vaults picked: the managed list names them. Saving it again
11685
+ * replaces it, so there is only ever one.
11686
+ * - None picked (vaults shown): the managed list names no vault, and the
11687
+ * rules must read back as an empty allow-list. Yieldseeker then keeps the
11688
+ * agent's money out of every vault, as Zyfai does with an empty pool list,
11689
+ * and the next Pools step reads "none". Only an agent that already exists
11690
+ * is written: one is never created just to hold "none".
11691
+ * - Every vault picked: the managed list is deleted, and no allow-list may
11692
+ * remain, so vaults Yieldseeker adds later are allowed too.
11693
+ * - A free-text allow-list we saved before the managed list existed is
11694
+ * deleted once the new state is written. A failed delete does not fail the
11695
+ * save; it is debug-logged, and the read-back decides.
11696
+ * - A read-back that differs puts the previous managed list back (or deletes
11697
+ * the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
11698
+ * it back fails too, that is still the error thrown. An old free-text list
11699
+ * already deleted is not put back.
11700
+ * - An agent already holding the most active memories, none of them ours,
11701
+ * throws POOL_SELECTION_RULE_LIMIT before anything is written.
11702
+ *
11703
+ * Always Base, whichever chain the wallet is connected on.
11704
+ */
11705
+ async setPoolSelection(selection, state) {
11706
+ if (!state) {
11707
+ throw new OwneyError(
11708
+ "NOT_CONNECTED",
11709
+ "Connect a wallet before saving Yieldseeker pool picks.",
11710
+ void 0,
11711
+ this.id
11712
+ );
11713
+ }
11714
+ const byAsset = /* @__PURE__ */ new Map();
11715
+ for (const entry of selection.selections) {
11716
+ if (entry.chainId !== 8453) continue;
11717
+ this.assertAsset(entry.asset);
11718
+ const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
11719
+ group.picked.push(...entry.pools);
11720
+ group.shown.push(...entry.availablePools);
11721
+ byAsset.set(entry.asset, group);
11722
+ }
11723
+ for (const [asset, group] of byAsset) {
11724
+ const picks = uniqueAddresses(group.picked);
11725
+ const shown = uniqueAddresses(group.shown);
11726
+ if (picks.length === 0 && shown.length === 0) continue;
11727
+ const picked = new Set(picks.map((address) => address.toLowerCase()));
11728
+ const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11729
+ await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11730
+ }
11731
+ }
11732
+ async savePoolPicks(state, asset, picks, everyVaultPicked) {
11733
+ const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11734
+ if (!context) {
11735
+ debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11736
+ return;
11737
+ }
11738
+ const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11739
+ const managed = active.find(isManagedVaultList);
11740
+ const legacy = active.filter(isLegacyPoolSelectionMemory);
11741
+ const writing = !everyVaultPicked;
11742
+ if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
11743
+ throw new OwneyError(
11744
+ "POOL_SELECTION_RULE_LIMIT",
11745
+ `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.`,
11746
+ { asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
11747
+ this.id
11748
+ );
11749
+ }
11750
+ const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
11751
+ const change = { previous: managed, written: false };
11752
+ if (content === void 0) {
11753
+ if (managed) {
11754
+ await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
11755
+ method: "POST"
11756
+ });
11757
+ change.written = true;
11758
+ }
11759
+ } else {
11760
+ const answer = await this.memoryRequest(state, context, "memories", {
11761
+ method: "POST",
11762
+ body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11763
+ });
11764
+ change.written = true;
11765
+ if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
11766
+ }
11767
+ await this.deleteLegacyPoolMemories(state, context, asset, legacy);
11768
+ let failure;
11769
+ try {
11770
+ const allowed = await this.readAllowList(state, context);
11771
+ const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
11772
+ if (!applied) failure = "ALLOW_LIST_MISMATCH";
11773
+ } catch {
11774
+ failure = "READ_BACK_FAILED";
11775
+ }
11776
+ if (!failure) return;
11777
+ const restored = await this.restorePoolMemory(state, context, change);
11778
+ throw new OwneyError(
11779
+ "POOL_SELECTION_NOT_APPLIED",
11780
+ `Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
11781
+ { asset, reason: failure, restored },
11782
+ this.id
11783
+ );
11784
+ }
11785
+ /**
11786
+ * Delete the free-text allow-lists we saved before the managed list existed.
11787
+ * Never throws: a list left behind is caught by the read-back. Logs no
11788
+ * sign-in token.
11789
+ */
11790
+ async deleteLegacyPoolMemories(state, context, asset, memories) {
11791
+ for (const memory2 of memories) {
11792
+ try {
11793
+ await this.memoryRequest(state, context, `memories/${memory2.agentMemoryId}/delete`, {
11794
+ method: "POST"
11795
+ });
11796
+ } catch (error) {
11797
+ debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
11798
+ memoryId: memory2.agentMemoryId,
11799
+ code: error instanceof OwneyError ? error.code : void 0,
11800
+ message: error instanceof Error ? error.message : void 0
11801
+ });
11802
+ }
11803
+ }
11804
+ }
11805
+ /**
11806
+ * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11807
+ * has no brackets. No picks names no vault.
11808
+ */
11809
+ async poolMemoryContent(asset, picks) {
11810
+ if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11811
+ const vaults = new Map(
11812
+ (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11813
+ );
11814
+ const entries = picks.map((pick) => {
11815
+ const vault = vaults.get(pick.toLowerCase());
11816
+ const address = vault?.address ?? pick;
11817
+ return vault?.name ? `${address} (${vault.name})` : address;
11818
+ });
11819
+ return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
11820
+ }
11821
+ /** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
11822
+ async restorePoolMemory(state, context, change) {
11823
+ if (!change.written) return true;
11824
+ try {
11825
+ if (change.previous) {
11826
+ await this.memoryRequest(state, context, "memories", {
11827
+ method: "POST",
11828
+ body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11829
+ });
11830
+ return true;
11831
+ }
11832
+ const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory2) => isActiveMemory(memory2) && isManagedVaultList(memory2)).map((memory2) => memory2.agentMemoryId);
11833
+ for (const id of ids) {
11834
+ await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
11835
+ }
11836
+ return true;
11837
+ } catch {
11838
+ return false;
11839
+ }
11840
+ }
11841
+ /**
11842
+ * What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
11843
+ * pairs: the allowed vault addresses under the provider each belongs to, for
11844
+ * the vaults a new agent can use. An agent with no allow-list adds nothing,
11845
+ * and no pairs at all means every shown vault is on. Reads never create an
11846
+ * agent, and always read Base. A read that fails throws, because "no
11847
+ * allow-list" would wrongly mean "everything".
11848
+ *
11849
+ * An allow-list naming none of the listed vaults (the saved "none", or vaults
11850
+ * Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
11851
+ * it reports none chosen for its asset: a pair with empty `pools` for every
11852
+ * provider listing vaults for it. With no vault listed at all there is
11853
+ * nothing to name that by, and it throws: the rules still restrict the agent.
11854
+ *
11855
+ * `pairs` is accepted for the contract but does not trim the answer: cutting
11856
+ * a real allow-list down to the pairs asked about could leave none, and none
11857
+ * reads as every vault on.
11858
+ */
11859
+ async getPoolSelection(state, _chainId, params) {
11860
+ const byProvider = /* @__PURE__ */ new Map();
11861
+ for (const asset of new Set(params.assets)) {
11862
+ this.assertAsset(asset);
11863
+ const context = await this.findAgent(state, 8453, asset);
11864
+ if (!context) continue;
11865
+ const allowed = await this.readAllowList(state, context);
11866
+ if (allowed === void 0) continue;
11867
+ const options = await this.loadVaultOptions(asset);
11868
+ if (options.length === 0) {
11869
+ throw this.invalidResponse("pool selection", {
11870
+ reason: "vault-options lists no vault while an allow-list restricts the agent.",
11871
+ asset
11872
+ });
11873
+ }
11874
+ const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
11875
+ const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
11876
+ if (known.length === 0) {
11877
+ for (const vault of options) {
11878
+ if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
11879
+ }
11880
+ continue;
11881
+ }
11882
+ for (const vault of known) {
11883
+ const pools = byProvider.get(vault.provider) ?? [];
11884
+ byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
11885
+ }
11886
+ }
11887
+ return {
11888
+ strategies: [],
11889
+ pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
11890
+ };
11891
+ }
11892
+ /**
11893
+ * The allow-list in the agent's rules: every `allowedVaultAddresses` on an
11894
+ * `ignored_vault` user rule. Undefined when no rule has one, which allows
11895
+ * every vault; an empty list allows none. A response that does not have the
11896
+ * expected shape throws rather than reading as no allow-list.
11897
+ */
11898
+ async readAllowList(state, context) {
11899
+ const rules = await this.memoryRequest(
11900
+ state,
11901
+ context,
11902
+ "memories/effective-rules"
11903
+ );
11904
+ if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
11905
+ let allowed;
11906
+ for (const rule of rules.userRules) {
11907
+ if (rule?.ruleType !== "ignored_vault") continue;
11908
+ const list = rule.ruleConfig?.allowedVaultAddresses;
11909
+ if (list === void 0 || list === null) continue;
11910
+ if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
11911
+ throw this.invalidResponse("effective rules");
11912
+ }
11913
+ allowed = [...allowed ?? [], ...list];
11914
+ }
11915
+ return allowed;
11916
+ }
11917
+ async listMemories(state, context) {
11918
+ const response = await this.memoryRequest(state, context, "memories");
11919
+ if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
11920
+ return response.memories;
11921
+ }
11922
+ /** A memory call for an agent, on Base whichever chain the wallet is on. */
11923
+ async memoryRequest(state, context, suffix, options = {}) {
11924
+ try {
11925
+ return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
11926
+ } catch (error) {
11927
+ if (error instanceof OwneyError) throw error;
11928
+ throw this.mapRequestFailure(error);
11929
+ }
11930
+ }
11278
11931
  userKey(state, chainId) {
11279
11932
  return `${state.walletAddress.toLowerCase()}:${chainId}`;
11280
11933
  }
@@ -11327,6 +11980,7 @@ var YieldseekerAgent = class {
11327
11980
  this.agentContexts.set(slot, context);
11328
11981
  this.pendingSlotInvalidations.delete(slot);
11329
11982
  this.missingSlots.delete(slot);
11983
+ this.closedSlots.delete(slot);
11330
11984
  }
11331
11985
  assertSession(generation, chainId, asset) {
11332
11986
  if (this.readGeneration !== generation) {
@@ -11438,8 +12092,10 @@ var YieldseekerAgent = class {
11438
12092
  * highest-priority set of `priorities` (index 0 first). Hinted agentIds are
11439
12093
  * resolved first and a hinted top-priority match ends the search; then other
11440
12094
  * listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
12095
+ * A candidate whose wallet shows it closed (deactivated) never ranks, and its
12096
+ * agentId is added to `closed`.
11441
12097
  */
11442
- async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
12098
+ async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
11443
12099
  const fitting = /* @__PURE__ */ new Map();
11444
12100
  for (const agent of agents) {
11445
12101
  if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
@@ -11461,6 +12117,10 @@ var YieldseekerAgent = class {
11461
12117
  failure ??= { error: result.reason };
11462
12118
  continue;
11463
12119
  }
12120
+ if (result.value.wallet.deactivatedDate) {
12121
+ closed?.add(result.value.agent.agentId);
12122
+ continue;
12123
+ }
11464
12124
  const wallet = result.value.wallet.walletAddress.toLowerCase();
11465
12125
  const rank = priorities.findIndex((wallets) => wallets.has(wallet));
11466
12126
  if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
@@ -11475,32 +12135,213 @@ var YieldseekerAgent = class {
11475
12135
  }
11476
12136
  /**
11477
12137
  * chooseAgent, re-reading a cached list once (bypassing its cache) when the
11478
- * verified agent is missing. A slot still missing after that re-read is
11479
- * remembered for the list cache window, so later reads fail from the cached
11480
- * list without another re-read.
12138
+ * verified agent is missing. Still missing, Yieldseeker may have closed
12139
+ * (deactivated) it: the verified record's agent is reactivated and selected
12140
+ * from a fresh list, by the verified wallet only (never created). A slot
12141
+ * that still fails is remembered with its error for the list cache window,
12142
+ * so later reads fail without another re-read or reactivate. A slot
12143
+ * Yieldseeker will not reopen because of its active-agent limit throws
12144
+ * YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
12145
+ * no request.
11481
12146
  */
11482
12147
  async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
12148
+ this.throwIfSlotUnavailable(state, chainId, asset);
11483
12149
  try {
11484
12150
  return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
11485
12151
  } catch (error) {
11486
12152
  if (!this.isAgentMissing(error)) throw error;
11487
12153
  const slot = this.slotKey(state, chainId, asset);
11488
- if (this.isSlotMissing(slot)) throw error;
12154
+ this.throwIfSlotMissing(slot);
11489
12155
  const generation = this.readGeneration;
11490
12156
  const fresh = await this.listAgents(state, chainId, user, true);
11491
12157
  this.assertSession(generation, chainId, asset);
12158
+ let missing;
11492
12159
  try {
11493
12160
  return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
11494
12161
  } catch (retryError) {
11495
- if (this.isAgentMissing(retryError) && this.readGeneration === generation) {
11496
- this.missingSlots.set(slot, Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS);
12162
+ if (!this.isAgentMissing(retryError)) throw retryError;
12163
+ missing = retryError;
12164
+ }
12165
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
12166
+ const agentId = verified?.providerAgentId;
12167
+ if (!verified || !agentId) {
12168
+ this.rememberMissingSlot(slot, generation, missing);
12169
+ throw missing;
12170
+ }
12171
+ this.throwIfSlotMissing(slot);
12172
+ let reopened;
12173
+ try {
12174
+ reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
12175
+ this.assertSession(generation, chainId, asset);
12176
+ } catch (reopenError) {
12177
+ this.rememberMissingSlot(slot, generation, reopenError);
12178
+ throw reopenError;
12179
+ }
12180
+ try {
12181
+ const agent = await this.agentWithWallet(
12182
+ state,
12183
+ chainId,
12184
+ user,
12185
+ reopened,
12186
+ asset,
12187
+ [/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
12188
+ [agentId]
12189
+ );
12190
+ if (agent) return agent;
12191
+ throw this.agentMissing(chainId, asset, agentId);
12192
+ } catch (reopenedError) {
12193
+ if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
12194
+ throw reopenedError;
12195
+ }
12196
+ }
12197
+ }
12198
+ throwIfSlotUnavailable(state, chainId, asset) {
12199
+ const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
12200
+ if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
12201
+ }
12202
+ /**
12203
+ * Rethrow the error a slot's lookup failed with while the slot is still
12204
+ * marked, or for the session when Yieldseeker will never reopen its agent.
12205
+ * A remembered rate limit is rethrown with the time left on its marker as
12206
+ * its retry delay (`retryAfterSeconds`): no new attempt is made before then,
12207
+ * so a caller that waits it out retries once instead of every few seconds.
12208
+ */
12209
+ throwIfSlotMissing(slot) {
12210
+ const closed = this.closedSlots.get(slot);
12211
+ if (closed) throw closed;
12212
+ const missing = this.missingSlots.get(slot);
12213
+ if (!missing || missing.until <= Date.now()) return;
12214
+ const { error } = missing;
12215
+ if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
12216
+ const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
12217
+ const rethrown = new OwneyError(
12218
+ error.code,
12219
+ error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
12220
+ { ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
12221
+ error.agentId
12222
+ );
12223
+ this.rethrownSlotFailures.set(rethrown, error);
12224
+ throw rethrown;
12225
+ }
12226
+ /**
12227
+ * Remember a slot's failed lookup or reactivate for the list-cache window.
12228
+ * A sign-in failure is not remembered (the wallet's rejection,
12229
+ * AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
12230
+ * remembered it would refuse the next sign-in, even one the user starts,
12231
+ * with no request for the whole window.
12232
+ */
12233
+ rememberMissingSlot(slot, generation, error) {
12234
+ if (this.readGeneration !== generation) return;
12235
+ if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
12236
+ this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
12237
+ }
12238
+ /**
12239
+ * Reactivate the slot's verified agent, then read the list bypassing its
12240
+ * cache, with a read sent after the reactivate answered. Concurrent lookups
12241
+ * of one slot share one reopen. Resolves to the fresh list. At the
12242
+ * active-agent limit the slot is recorded unavailable and this throws
12243
+ * YIELDSEEKER_SLOT_UNAVAILABLE.
12244
+ */
12245
+ reopenAgent(state, chainId, user, asset, agentId) {
12246
+ const slot = this.slotKey(state, chainId, asset);
12247
+ const pending2 = this.pendingReopens.get(slot);
12248
+ if (pending2) return pending2;
12249
+ const generation = this.readGeneration;
12250
+ const request2 = (async () => {
12251
+ const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
12252
+ this.assertSession(generation, chainId, asset);
12253
+ if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
12254
+ this.forgetAgentWallet(agentId);
12255
+ this.missingSlots.delete(slot);
12256
+ await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
12257
+ this.assertSession(generation, chainId, asset);
12258
+ const fresh = await this.listAgents(state, chainId, user, true);
12259
+ this.assertSession(generation, chainId, asset);
12260
+ return fresh;
12261
+ })().finally(() => {
12262
+ if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
12263
+ });
12264
+ this.pendingReopens.set(slot, request2);
12265
+ return request2;
12266
+ }
12267
+ /**
12268
+ * The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
12269
+ * and the pre-deposit check (assertAgentOpen), so a slot costs at most one
12270
+ * reactivate per list-cache window:
12271
+ * - a slot recorded unavailable (the limit) answers "limit" with no request;
12272
+ * - concurrent callers share one request;
12273
+ * - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
12274
+ * remembered as the slot's failure for the list-cache window (missingSlots)
12275
+ * and rethrown to later callers with no request; a closed code
12276
+ * (closedSlots) for the session; a sign-in failure is not remembered;
12277
+ * - the limit is recorded in unavailableSlots only while the session is
12278
+ * unchanged, so a disconnect during the request is not undone by its late
12279
+ * answer.
12280
+ */
12281
+ async reactivateSlot(state, chainId, user, asset, agentId) {
12282
+ const slot = this.slotKey(state, chainId, asset);
12283
+ const limit = this.unavailableSlots.get(slot);
12284
+ if (limit !== void 0) return { outcome: "limit", providerCode: limit };
12285
+ const key2 = `${slot}:${agentId}`;
12286
+ const pending2 = this.pendingReactivates.get(key2);
12287
+ if (pending2) return pending2;
12288
+ this.throwIfSlotMissing(slot);
12289
+ const generation = this.readGeneration;
12290
+ const request2 = (async () => {
12291
+ try {
12292
+ const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
12293
+ if (result.outcome === "limit" && this.readGeneration === generation) {
12294
+ this.unavailableSlots.set(slot, result.providerCode);
11497
12295
  }
11498
- throw retryError;
12296
+ return result;
12297
+ } catch (error) {
12298
+ 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)) {
12299
+ this.closedSlots.set(slot, error);
12300
+ }
12301
+ this.rememberMissingSlot(slot, generation, error);
12302
+ throw error;
11499
12303
  }
12304
+ })().finally(() => {
12305
+ if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
12306
+ });
12307
+ this.pendingReactivates.set(key2, request2);
12308
+ return request2;
12309
+ }
12310
+ /**
12311
+ * Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
12312
+ * Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
12313
+ * by another tab) counts as reopened; the active-agent limit is an outcome,
12314
+ * not an error. An agent that cannot come back throws
12315
+ * YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
12316
+ * 5xx, an unknown code) throws the mapped API error.
12317
+ */
12318
+ async reactivateAgent(state, chainId, user, asset, agentId) {
12319
+ try {
12320
+ await this.providerRequest(
12321
+ state,
12322
+ chainId,
12323
+ `/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
12324
+ { method: "POST", body: {} }
12325
+ );
12326
+ return { outcome: "reopened" };
12327
+ } catch (error) {
12328
+ if (error instanceof OwneyError) throw error;
12329
+ const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
12330
+ if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
12331
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
12332
+ return { outcome: "limit", providerCode };
12333
+ }
12334
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
12335
+ throw this.agentClosed(chainId, asset, agentId, providerCode);
12336
+ }
12337
+ throw this.mapRequestFailure(error);
11500
12338
  }
11501
12339
  }
11502
- isSlotMissing(slot) {
11503
- return (this.missingSlots.get(slot) ?? 0) > Date.now();
12340
+ /** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
12341
+ forgetAgentWallet(agentId) {
12342
+ const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
12343
+ for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
12344
+ for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
11504
12345
  }
11505
12346
  /**
11506
12347
  * The agent that serves deposits and withdrawals for a slot (Ruling 23):
@@ -11508,7 +12349,8 @@ var YieldseekerAgent = class {
11508
12349
  * whatever its name; the stored agentId is only a hint;
11509
12350
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
11510
12351
  * 3. else the fitting agent named "owney" (first use, migration, or a
11511
- * verified wallet that is not a fitting listed agent);
12352
+ * verified wallet that is not a fitting listed agent), unless step 1/2
12353
+ * read its wallet and it is closed (deactivated): that agent is not listed;
11512
12354
  * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
11513
12355
  * create); without one, undefined (the caller may create).
11514
12356
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
@@ -11519,6 +12361,7 @@ var YieldseekerAgent = class {
11519
12361
  const slot = this.slotAccounts(accounts, chainId, asset);
11520
12362
  const verified = slot.find((account) => account.status === "verified");
11521
12363
  const superseded = slot.filter((account) => account.status === "superseded");
12364
+ const closed = /* @__PURE__ */ new Set();
11522
12365
  if (verified || superseded.length) {
11523
12366
  const priorities = [];
11524
12367
  if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
@@ -11532,11 +12375,12 @@ var YieldseekerAgent = class {
11532
12375
  agents,
11533
12376
  asset,
11534
12377
  priorities,
11535
- [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
12378
+ [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
12379
+ closed
11536
12380
  );
11537
12381
  if (match) return match;
11538
12382
  }
11539
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
12383
+ const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
11540
12384
  if (named) return named;
11541
12385
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
11542
12386
  return void 0;
@@ -11552,6 +12396,39 @@ var YieldseekerAgent = class {
11552
12396
  this.id
11553
12397
  );
11554
12398
  }
12399
+ slotUnavailable(chainId, asset, providerCode) {
12400
+ return new OwneyError(
12401
+ "YIELDSEEKER_SLOT_UNAVAILABLE",
12402
+ `Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
12403
+ { rpcSource: "agent-api", chainId, asset, providerCode },
12404
+ this.id
12405
+ );
12406
+ }
12407
+ /** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
12408
+ isSlotEmpty(error) {
12409
+ return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
12410
+ }
12411
+ /**
12412
+ * The slot's lookup failed through the missing-agent / reopen path and was
12413
+ * remembered with this very error, even a transient one (429, 5xx, timeout),
12414
+ * or with the copy of it a remembered rate limit is rethrown as. Compares
12415
+ * the remembered error, not its expiry, so it holds however long the rest
12416
+ * of the read takes.
12417
+ */
12418
+ isMarkedSlotFailure(slot, error) {
12419
+ const marker = this.missingSlots.get(slot);
12420
+ if (!marker) return false;
12421
+ return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
12422
+ }
12423
+ /** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
12424
+ agentClosed(chainId, asset, agentId, providerCode, extra) {
12425
+ return new OwneyError(
12426
+ "YIELDSEEKER_AGENT_CLOSED",
12427
+ `Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
12428
+ { rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
12429
+ this.id
12430
+ );
12431
+ }
11555
12432
  /**
11556
12433
  * Fire-and-forget: record which agent serves this slot. Never awaited on the
11557
12434
  * funds path and never throws; once per agent wallet and deployment state
@@ -11641,7 +12518,7 @@ var YieldseekerAgent = class {
11641
12518
  } catch (error) {
11642
12519
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
11643
12520
  if (error instanceof OwneyError) throw error;
11644
- throw this.mapApiError(error);
12521
+ throw this.mapRequestFailure(error);
11645
12522
  }
11646
12523
  let created;
11647
12524
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
@@ -11662,7 +12539,7 @@ var YieldseekerAgent = class {
11662
12539
  } catch (createError) {
11663
12540
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
11664
12541
  if (canRetry) continue;
11665
- throw this.mapApiError(createError);
12542
+ throw this.mapRequestFailure(createError);
11666
12543
  }
11667
12544
  }
11668
12545
  user = created?.user ?? null;
@@ -11719,6 +12596,7 @@ var YieldseekerAgent = class {
11719
12596
  return context;
11720
12597
  }
11721
12598
  async resolveAgent(state, chainId, asset, createIfMissing) {
12599
+ this.throwIfSlotUnavailable(state, chainId, asset);
11722
12600
  const generation = this.readGeneration;
11723
12601
  const accountsRead = this.agentAccounts(state, chainId);
11724
12602
  const user = await this.resolveUser(state, chainId);
@@ -11761,7 +12639,7 @@ var YieldseekerAgent = class {
11761
12639
  );
11762
12640
  } catch (error) {
11763
12641
  const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
11764
- if (!conflict) throw this.mapApiError(error);
12642
+ if (!conflict) throw this.mapRequestFailure(error);
11765
12643
  this.assertSession(generation, chainId, asset);
11766
12644
  return this.adoptConflictingAgent(
11767
12645
  state,
@@ -11854,10 +12732,11 @@ var YieldseekerAgent = class {
11854
12732
  const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
11855
12733
  if (agent) selected.set(asset, agent);
11856
12734
  } catch (error) {
11857
- if (assetFilter || !this.isAgentMissing(error)) throw error;
12735
+ if (assetFilter) throw error;
12736
+ if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
11858
12737
  missing.push(error);
11859
12738
  missingAssets?.add(asset);
11860
- console.warn(`[owney-sdk] Yieldseeker ${asset} agent is missing:`, error);
12739
+ console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
11861
12740
  }
11862
12741
  }));
11863
12742
  this.assertSession(generation, chainId);
@@ -12492,6 +13371,7 @@ var YieldseekerAgent = class {
12492
13371
  try {
12493
13372
  return await this.providerRequest(state, chainId, path, options);
12494
13373
  } catch (error) {
13374
+ if (isWalletRejection(error)) throw error;
12495
13375
  const mapped = this.mapApiError(error);
12496
13376
  const delay = read2 ? rateLimitDelay(mapped) : void 0;
12497
13377
  if (delay !== void 0 && this.readGeneration === generation) {
@@ -12546,6 +13426,16 @@ var YieldseekerAgent = class {
12546
13426
  }
12547
13427
  }
12548
13428
  }
13429
+ /**
13430
+ * mapApiError for a request that may have opened the Yieldseeker sign-in
13431
+ * prompt (providerRequest signs when no sign-in is saved, and again when
13432
+ * Yieldseeker refuses one). The wallet's rejection, the user cancelling that
13433
+ * prompt, is returned unchanged: the client and the app must see the user's
13434
+ * cancel (no further prompt, no retry), never a provider failure.
13435
+ */
13436
+ mapRequestFailure(error) {
13437
+ return isWalletRejection(error) ? error : this.mapApiError(error);
13438
+ }
12549
13439
  mapApiError(error) {
12550
13440
  if (!(error instanceof YieldseekerApiError)) {
12551
13441
  return new OwneyError(
@@ -13141,6 +14031,8 @@ var FALLBACK_WRAP_GAS = 50000n;
13141
14031
  var APPROVE_GAS = 60000n;
13142
14032
  var GAS_SAFETY = 2n;
13143
14033
  var MIN_WALLET_GAS_PRICE = 3000000000n;
14034
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
14035
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
13144
14036
  async function wrapNative(deps, options) {
13145
14037
  const { chainId, wrapper, nativeSymbol, requested } = options;
13146
14038
  const balance = await deps.readNativeBalance();
@@ -13198,16 +14090,90 @@ async function wrapNative(deps, options) {
13198
14090
  }
13199
14091
  );
13200
14092
  }
14093
+ let baseline;
14094
+ if (deps.readWrappedBalance) {
14095
+ try {
14096
+ baseline = await deps.readWrappedBalance();
14097
+ } catch (error) {
14098
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
14099
+ message: error instanceof Error ? error.message : String(error)
14100
+ });
14101
+ }
14102
+ }
13201
14103
  await deps.ensureChain(chainId);
13202
14104
  debugLog("owney-sdk", "wrap: sending deposit()", {
13203
14105
  wrapper,
13204
14106
  value: wrapped.toString()
13205
14107
  });
13206
- const txHash = await deps.sendTransaction(
13207
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
13208
- options.onSubmitted
13209
- );
13210
- return { wrapped, txHash };
14108
+ let notified = false;
14109
+ const notify2 = (hash2) => {
14110
+ if (notified) return;
14111
+ notified = true;
14112
+ options.onSubmitted?.(hash2);
14113
+ };
14114
+ const outcome = await new Promise((resolve, reject) => {
14115
+ let done = false;
14116
+ let timer;
14117
+ const finish = (settle) => {
14118
+ if (done) return;
14119
+ done = true;
14120
+ clearTimeout(timer);
14121
+ settle();
14122
+ };
14123
+ timer = setTimeout(
14124
+ () => finish(
14125
+ () => reject(
14126
+ new OwneyError(
14127
+ "SWAP_WALLET_PROMPT_TIMEOUT",
14128
+ // Hedged on purpose: a wallet that never answered may still have
14129
+ // sent it, and wrapping again would wrap twice.
14130
+ `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}.`,
14131
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
14132
+ )
14133
+ )
14134
+ ),
14135
+ WRAP_PROMPT_TIMEOUT_MS
14136
+ );
14137
+ deps.sendTransaction(
14138
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
14139
+ (hash2) => {
14140
+ clearTimeout(timer);
14141
+ notify2(hash2);
14142
+ }
14143
+ ).then(
14144
+ (txHash) => finish(() => resolve({ txHash })),
14145
+ (error) => finish(() => reject(error))
14146
+ );
14147
+ if (baseline !== void 0 && deps.readWrappedBalance) {
14148
+ const read2 = deps.readWrappedBalance;
14149
+ const target = baseline + wrapped;
14150
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
14151
+ void (async () => {
14152
+ while (!done) {
14153
+ await sleep4(WRAP_WATCH_INTERVAL_MS);
14154
+ if (done) return;
14155
+ try {
14156
+ if (await read2() >= target) {
14157
+ debugLog(
14158
+ "owney-sdk",
14159
+ "wrap: landed on chain before the wallet answered"
14160
+ );
14161
+ finish(() => {
14162
+ notify2();
14163
+ resolve({});
14164
+ });
14165
+ return;
14166
+ }
14167
+ } catch {
14168
+ }
14169
+ }
14170
+ })();
14171
+ }
14172
+ });
14173
+ return {
14174
+ wrapped,
14175
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
14176
+ };
13211
14177
  }
13212
14178
  function requireWrapper(quote) {
13213
14179
  const wrapper = quote.wrappedNative;
@@ -14761,9 +15727,40 @@ function aggregateApyHistory(agentApys) {
14761
15727
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
14762
15728
  if (total <= 0 || !Number.isFinite(total)) return [];
14763
15729
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
14764
- return Number.isFinite(apy) ? [{ date, apy }] : [];
15730
+ if (!Number.isFinite(apy)) return [];
15731
+ const incentives = aggregateIncentives(points, total);
15732
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
14765
15733
  });
14766
15734
  }
15735
+ function incentiveKey(incentive) {
15736
+ return JSON.stringify([
15737
+ incentive.source,
15738
+ incentive.agentId,
15739
+ incentive.opportunityId,
15740
+ [...incentive.campaignIds].sort()
15741
+ ]);
15742
+ }
15743
+ function aggregateIncentives(points, totalBalance) {
15744
+ const byProgram = /* @__PURE__ */ new Map();
15745
+ for (const point of points) {
15746
+ const weight = point.historicalBalance.amount / totalBalance;
15747
+ for (const incentive of point.incentives ?? []) {
15748
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
15749
+ const key2 = incentiveKey(incentive);
15750
+ const existing = byProgram.get(key2);
15751
+ if (existing) {
15752
+ existing.apyContribution += incentive.apyContribution * weight;
15753
+ } else {
15754
+ byProgram.set(key2, {
15755
+ ...incentive,
15756
+ campaignIds: [...incentive.campaignIds],
15757
+ apyContribution: incentive.apyContribution * weight
15758
+ });
15759
+ }
15760
+ }
15761
+ }
15762
+ return [...byProgram.values()];
15763
+ }
14767
15764
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
14768
15765
  const sums = {};
14769
15766
  const weights = {};
@@ -15568,6 +16565,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
15568
16565
  }
15569
16566
  }
15570
16567
 
16568
+ // src/lib/walletconnect-switch.ts
16569
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
16570
+ var HOLD_CHAIN_MS = 15e3;
16571
+ var MAX_RESENDS = 2;
16572
+ var holds = /* @__PURE__ */ new Map();
16573
+ function parseChainId(raw2) {
16574
+ if (typeof raw2 === "number") return raw2;
16575
+ if (typeof raw2 !== "string") return void 0;
16576
+ const ref = raw2.split(":").pop() ?? raw2;
16577
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
16578
+ return Number.isFinite(id) ? id : void 0;
16579
+ }
16580
+ function walletConnectCore(provider) {
16581
+ const p = provider;
16582
+ const core = p?.signer ?? p;
16583
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
16584
+ return null;
16585
+ }
16586
+ const peer = core.session.peer?.metadata?.name ?? "";
16587
+ if (!/metamask/i.test(peer)) return null;
16588
+ return core;
16589
+ }
16590
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
16591
+ const core = walletConnectCore(provider);
16592
+ if (!core) return false;
16593
+ holds.get(core.session.topic)?.();
16594
+ await requestSwitch(core, provider, chainId, timeoutMs);
16595
+ holdChain(core, provider, chainId);
16596
+ return true;
16597
+ }
16598
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
16599
+ const current = Number(
16600
+ await provider.request({ method: "eth_chainId" })
16601
+ );
16602
+ const hexChainId = `0x${chainId.toString(16)}`;
16603
+ let timer;
16604
+ try {
16605
+ await Promise.race([
16606
+ core.client.request({
16607
+ topic: core.session.topic,
16608
+ chainId: `eip155:${current}`,
16609
+ request: {
16610
+ method: "wallet_switchEthereumChain",
16611
+ params: [{ chainId: hexChainId }]
16612
+ }
16613
+ }),
16614
+ new Promise((_, reject) => {
16615
+ timer = setTimeout(
16616
+ () => reject(
16617
+ new Error("The wallet did not answer the network switch in time")
16618
+ ),
16619
+ timeoutMs
16620
+ );
16621
+ })
16622
+ ]);
16623
+ } finally {
16624
+ clearTimeout(timer);
16625
+ }
16626
+ try {
16627
+ core.setDefaultChain(`eip155:${chainId}`);
16628
+ } catch {
16629
+ }
16630
+ }
16631
+ function holdChain(core, provider, chainId) {
16632
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
16633
+ return;
16634
+ }
16635
+ let resends = 0;
16636
+ const listener = (raw2) => {
16637
+ const reported = parseChainId(raw2);
16638
+ debugLog("wc-switch", "wallet reported chain", {
16639
+ reported,
16640
+ holding: chainId,
16641
+ resends
16642
+ });
16643
+ if (reported === void 0 || reported === chainId) return;
16644
+ if (resends >= MAX_RESENDS) return;
16645
+ resends += 1;
16646
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
16647
+ (error) => debugLog("wc-switch", "re-switch failed", {
16648
+ error: error instanceof Error ? error.message : String(error)
16649
+ })
16650
+ );
16651
+ };
16652
+ const release = () => {
16653
+ clearTimeout(timer);
16654
+ core.removeListener?.("chainChanged", listener);
16655
+ if (holds.get(core.session.topic) === release) {
16656
+ holds.delete(core.session.topic);
16657
+ }
16658
+ };
16659
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
16660
+ core.on("chainChanged", listener);
16661
+ holds.set(core.session.topic, release);
16662
+ }
16663
+ function withWalletConnectSwitch(provider) {
16664
+ if (!walletConnectCore(provider)) return provider;
16665
+ const target = provider;
16666
+ const request2 = async (args) => {
16667
+ if (args?.method !== "wallet_switchEthereumChain") {
16668
+ return target.request(args);
16669
+ }
16670
+ const [param] = args.params ?? [];
16671
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
16672
+ if (!Number.isFinite(chainId)) return target.request(args);
16673
+ await switchWalletConnectChain(target, chainId);
16674
+ return null;
16675
+ };
16676
+ return new Proxy(target, {
16677
+ get(obj, prop) {
16678
+ if (prop === "request") return request2;
16679
+ const value = Reflect.get(obj, prop, obj);
16680
+ return typeof value === "function" ? value.bind(obj) : value;
16681
+ }
16682
+ });
16683
+ }
16684
+
15571
16685
  // src/lib/sponsored-calls-deposit.ts
15572
16686
  var import_viem24 = require("viem");
15573
16687
  init_errors();
@@ -15839,6 +16953,14 @@ var OwneySDK = class {
15839
16953
  * withdraw, but they are excluded from new deposits / activations.
15840
16954
  */
15841
16955
  disabledAgents = /* @__PURE__ */ new Set();
16956
+ /**
16957
+ * Agents whose sign-in the user cancelled this session (the wallet rejected
16958
+ * the prompt), keyed by chain. Until the app ends the session they are read
16959
+ * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
16960
+ * the user cancelled. A later successful activation of the agent removes
16961
+ * it, and `disconnect()` or a different wallet's `connect()` clears the map.
16962
+ */
16963
+ declinedSignIns = /* @__PURE__ */ new Map();
15842
16964
  state = null;
15843
16965
  connectionRevision = 0;
15844
16966
  disconnectingAgents = null;
@@ -15874,6 +16996,8 @@ var OwneySDK = class {
15874
16996
  * session started: true when it armed the refresh, false when its deadline
15875
16997
  * had passed (it only dropped the cache and forced one snapshot read). */
15876
16998
  recoveredFundingReads = /* @__PURE__ */ new Map();
16999
+ /** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
17000
+ announcedDeposits = /* @__PURE__ */ new Set();
15877
17001
  fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
15878
17002
  activationChecks = /* @__PURE__ */ new Map();
15879
17003
  // Protect the SDK entry point as well as the mini-app hook. This owns only
@@ -16129,10 +17253,15 @@ var OwneySDK = class {
16129
17253
  }
16130
17254
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
16131
17255
  this.clearConnectionState();
17256
+ if (replacingOwner) this.declinedSignIns.clear();
16132
17257
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
16133
17258
  if (revision !== this.connectionRevision)
16134
17259
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
16135
- this.state = { provider, walletAddress, chainId: null };
17260
+ this.state = {
17261
+ provider: withWalletConnectSwitch(provider),
17262
+ walletAddress,
17263
+ chainId: null
17264
+ };
16136
17265
  }
16137
17266
  /**
16138
17267
  * Disconnect from all agents and clear connection state.
@@ -16141,6 +17270,7 @@ var OwneySDK = class {
16141
17270
  async disconnect() {
16142
17271
  ++this.connectionRevision;
16143
17272
  this.clearConnectionState();
17273
+ this.declinedSignIns.clear();
16144
17274
  await this.disconnectAgents();
16145
17275
  }
16146
17276
  clearConnectionState() {
@@ -16170,6 +17300,44 @@ var OwneySDK = class {
16170
17300
  isAgentDisabled(agentId) {
16171
17301
  return this.disabledAgents.has(agentId);
16172
17302
  }
17303
+ /**
17304
+ * True when `id` takes no new deposits on this chain and asset this
17305
+ * session: its adapter reports no agent for the slot.
17306
+ */
17307
+ isAgentUnavailable(id, chainId, asset) {
17308
+ if (asset === void 0) return false;
17309
+ return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
17310
+ }
17311
+ /**
17312
+ * The agents that take no new deposits on this chain and asset this
17313
+ * session, so the app can show them as unavailable: each agent whose
17314
+ * provider has no agent for this slot. They stay withdrawable.
17315
+ */
17316
+ getUnavailableAgentIds(chainId, asset) {
17317
+ return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
17318
+ }
17319
+ /**
17320
+ * The adapter reports no agent for this chain and asset this session (see
17321
+ * `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
17322
+ * withdrawal without an explicit agent leaves it out instead of failing its
17323
+ * leg.
17324
+ */
17325
+ hasNoAgentForSlot(agent, state, chainId, asset) {
17326
+ return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
17327
+ }
17328
+ /**
17329
+ * The state an agent's reads use. An agent whose sign-in the user cancelled
17330
+ * on the connection chain this session is read from a saved sign-in only,
17331
+ * as `offChainPortfolioAgents` reads: a read that would need a wallet
17332
+ * prompt fails for that agent instead of reopening the prompt the user
17333
+ * cancelled. A later successful activation of the agent, or `disconnect()`,
17334
+ * lifts it.
17335
+ */
17336
+ readStateFor(agentId, state) {
17337
+ const chainId = state.chainId;
17338
+ if (state.promptless === true || chainId === null) return state;
17339
+ return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
17340
+ }
16173
17341
  /**
16174
17342
  * Check if the SDK has an active connection state.
16175
17343
  * @returns `true` if `connect()` has been called and `disconnect()` has not
@@ -16386,10 +17554,14 @@ var OwneySDK = class {
16386
17554
  * connection chain, then the off-chain ones on their own chain. */
16387
17555
  portfolioReads(state, chainId) {
16388
17556
  return [
16389
- ...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
16390
- ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
17557
+ ...this.activeReads(state, chainId),
17558
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
16391
17559
  ];
16392
17560
  }
17561
+ /** The active agents, each with the state its reads use (`readStateFor`). */
17562
+ activeReads(state, chainId) {
17563
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
17564
+ }
16393
17565
  /**
16394
17566
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
16395
17567
  * throws — it degrades to null — so this cannot break activation.
@@ -16513,7 +17685,7 @@ var OwneySDK = class {
16513
17685
  */
16514
17686
  async getAvailableAgents(options = {}) {
16515
17687
  await this.ensureAgentsInitialized();
16516
- const { chainId, asset, includeDisabled = false } = options;
17688
+ const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
16517
17689
  const available = [];
16518
17690
  for (const [id, agent] of this.agents) {
16519
17691
  const isEnabled = !this.isAgentDisabled(id);
@@ -16529,6 +17701,9 @@ var OwneySDK = class {
16529
17701
  continue;
16530
17702
  }
16531
17703
  }
17704
+ if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
17705
+ continue;
17706
+ }
16532
17707
  available.push({
16533
17708
  id,
16534
17709
  isEnabled,
@@ -16548,8 +17723,17 @@ var OwneySDK = class {
16548
17723
  * that support the given chainId (incompatible agents are silently skipped).
16549
17724
  * If provided, ALL specified agents must support the chainId or the call
16550
17725
  * throws before activating any agent.
17726
+ * @param options - Optional. `asset` limits setup to that asset;
17727
+ * `onAgentsSelected` fires once reads can start.
17728
+ * @throws Activation stops at the first agent that fails, and the caller
17729
+ * should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
17730
+ * earlier agent activated; `walletRejected` in its details means the user
17731
+ * rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
17732
+ * never be readied (`details.permanent`). Otherwise the agent's own error
17733
+ * is thrown as is. Until it signs in, an agent whose signature the user
17734
+ * rejected is read from a saved sign-in only and opens no prompt.
16551
17735
  */
16552
- async activateAgent(chainId, agentId, asset) {
17736
+ async activateAgent(chainId, agentId, options = {}) {
16553
17737
  const state = this.requireState();
16554
17738
  await this.ensureAgentsInitialized();
16555
17739
  this.assertActivationSession(state);
@@ -16586,7 +17770,8 @@ var OwneySDK = class {
16586
17770
  this.activeAgents.add(id);
16587
17771
  }
16588
17772
  state.chainId = chainId;
16589
- await this.activateAgentsInTurn(agents, state, chainId, asset);
17773
+ options.onAgentsSelected?.();
17774
+ await this.activateAgentsInTurn(agents, state, chainId, options.asset);
16590
17775
  return;
16591
17776
  }
16592
17777
  const compatible = [...this.agents.values()].filter(
@@ -16604,10 +17789,11 @@ var OwneySDK = class {
16604
17789
  this.activeAgents.add(agent.id);
16605
17790
  }
16606
17791
  state.chainId = chainId;
17792
+ options.onAgentsSelected?.();
16607
17793
  const enabledCompatible = compatible.filter(
16608
17794
  (agent) => !this.isAgentDisabled(agent.id)
16609
17795
  );
16610
- await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
17796
+ await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
16611
17797
  }
16612
17798
  assertActivationSession(state) {
16613
17799
  if (this.state !== state) {
@@ -16627,12 +17813,17 @@ var OwneySDK = class {
16627
17813
  * Serializing costs no real wall-clock: the user can only approve one prompt
16628
17814
  * at a time anyway.
16629
17815
  *
16630
- * Stop at the first failure so a canceled sign-in does not open another
16631
- * agent's wallet prompt. Report any earlier successes for diagnostics; the
16632
- * app discards the session when the complete sign-in does not succeed.
17816
+ * Stop at the first failure (2026-11-06): a connect needs every agent, so
17817
+ * no later agent's wallet prompt opens for a sign-in that already failed.
17818
+ * When an earlier agent activated, the partial failure reports it, and
17819
+ * `walletRejected` tells the app the user canceled; the app ends the
17820
+ * session either way. When none activated, the agent's own error is thrown.
17821
+ * A failure the provider marks `permanent` is thrown as
17822
+ * `AGENT_ACTIVATION_BLOCKED`.
16633
17823
  */
16634
17824
  async activateAgentsInTurn(agents, state, chainId, asset) {
16635
17825
  let firstError = null;
17826
+ let walletRejected = false;
16636
17827
  const activatedAgentIds = [];
16637
17828
  const failedAgents = [];
16638
17829
  for (const agent of agents) {
@@ -16643,6 +17834,7 @@ var OwneySDK = class {
16643
17834
  await this.applyOrgPolicyTo(agent, state, chainId);
16644
17835
  this.assertActivationSession(state);
16645
17836
  activatedAgentIds.push(agent.id);
17837
+ this.declinedSignIns.get(chainId)?.delete(agent.id);
16646
17838
  } catch (error) {
16647
17839
  this.assertActivationSession(state);
16648
17840
  const message = error !== null && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "No activation error message was returned.";
@@ -16652,15 +17844,28 @@ var OwneySDK = class {
16652
17844
  message,
16653
17845
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
16654
17846
  });
16655
- if (firstError === null) {
16656
- firstError = error;
16657
- } else {
16658
- console.error(`activateAgent(${agent.id}) failed:`, error);
17847
+ firstError = error;
17848
+ if (this.isUserRejectedWithdrawal(error)) {
17849
+ walletRejected = true;
17850
+ const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
17851
+ declined.add(agent.id);
17852
+ this.declinedSignIns.set(chainId, declined);
16659
17853
  }
16660
17854
  break;
16661
17855
  }
16662
17856
  }
16663
17857
  if (firstError === null) return;
17858
+ if (failedAgents.some(({ details }) => details?.permanent === true)) {
17859
+ throw new OwneyError(
17860
+ "AGENT_ACTIVATION_BLOCKED",
17861
+ failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
17862
+ {
17863
+ activatedAgentIds,
17864
+ failedAgentIds: failedAgents.map(({ agentId }) => agentId),
17865
+ failures: failedAgents
17866
+ }
17867
+ );
17868
+ }
16664
17869
  if (activatedAgentIds.length === 0) throw firstError;
16665
17870
  const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
16666
17871
  const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
@@ -16670,7 +17875,7 @@ var OwneySDK = class {
16670
17875
  throw new OwneyError(
16671
17876
  "AGENT_ACTIVATION_PARTIAL_FAILURE",
16672
17877
  `${activeNames} activated. ${failureMessages}`,
16673
- { activatedAgentIds, failedAgentIds, failures: failedAgents }
17878
+ { activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
16674
17879
  );
16675
17880
  }
16676
17881
  /**
@@ -16685,6 +17890,10 @@ var OwneySDK = class {
16685
17890
  * all shares into one signature; custom callbacks still run once per agent.
16686
17891
  * @param options.agentId - Optional explicit target. Otherwise split equally,
16687
17892
  * or fund remaining agents when a recovery deposit cannot meet every minimum.
17893
+ * @param options.excludeAgentIds - Agents that must receive nothing. The rest
17894
+ * split the whole amount under their own minimums. Throws
17895
+ * `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
17896
+ * when resuming a signed batch.
16688
17897
  * @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
16689
17898
  */
16690
17899
  async deposit(options) {
@@ -16713,6 +17922,7 @@ var OwneySDK = class {
16713
17922
  const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
16714
17923
  if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
16715
17924
  if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
17925
+ this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
16716
17926
  } catch {
16717
17927
  }
16718
17928
  };
@@ -16748,6 +17958,8 @@ var OwneySDK = class {
16748
17958
  const state = this.requireState();
16749
17959
  const chainId = options.chainId ?? this.requireChainId();
16750
17960
  const activatedChain = state.chainId;
17961
+ const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
17962
+ this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
16751
17963
  let checkpointFailure;
16752
17964
  let checkpointFailedEvidence = [];
16753
17965
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
@@ -16844,11 +18056,11 @@ var OwneySDK = class {
16844
18056
  const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
16845
18057
  if (!batchTransfer2) throw invalid2();
16846
18058
  const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
16847
- if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
18059
+ if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
16848
18060
  throw new OwneyError(
16849
18061
  error.code,
16850
- "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
16851
- { ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
18062
+ 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.",
18063
+ { cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
16852
18064
  error.agentId
16853
18065
  );
16854
18066
  throw error;
@@ -16886,7 +18098,7 @@ var OwneySDK = class {
16886
18098
  this.validateChainHasAgents(chainId);
16887
18099
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
16888
18100
  excludeDisabled: true
16889
- });
18101
+ }).filter((agent) => !excludeAgentIds?.includes(agent.id));
16890
18102
  const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
16891
18103
  const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
16892
18104
  const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
@@ -17034,7 +18246,7 @@ var OwneySDK = class {
17034
18246
  }
17035
18247
  try {
17036
18248
  if (!depositCallback && appObserves && !options.resumeTxHash) {
17037
- const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
18249
+ const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
17038
18250
  for (const id of ids) {
17039
18251
  const evidence = [...prepared.values()].find((value) => value.agentId === id);
17040
18252
  const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
@@ -17134,6 +18346,29 @@ var OwneySDK = class {
17134
18346
  }
17135
18347
  }
17136
18348
  }
18349
+ /**
18350
+ * Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
18351
+ * the explicit `agentId` is listed, or every agent that can take this asset
18352
+ * on this chain (and is not disabled) is. A no-op without a list, so a deposit
18353
+ * without exclusions is exactly as it was. Reads no provider.
18354
+ */
18355
+ assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
18356
+ if (!excludeAgentIds?.length) return;
18357
+ const refuse = (message) => new OwneyError(
18358
+ "ALL_AGENTS_EXCLUDED",
18359
+ message,
18360
+ { phase: "prepare", rejectedBeforeSubmission: true }
18361
+ );
18362
+ if (agentId) {
18363
+ if (excludeAgentIds.includes(agentId))
18364
+ throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
18365
+ return;
18366
+ }
18367
+ this.validateChainHasAgents(chainId);
18368
+ const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
18369
+ if (remaining.length === 0)
18370
+ throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
18371
+ }
17137
18372
  getMinDepositAmount(agent, chainId, asset) {
17138
18373
  const chainAssets = agent.supportedAssets.find(
17139
18374
  (sa) => sa.chainId === chainId
@@ -17288,9 +18523,15 @@ var OwneySDK = class {
17288
18523
  );
17289
18524
  }
17290
18525
  }
18526
+ /**
18527
+ * The agents that support this asset on this chain. `excludeDisabled` is for
18528
+ * new deposits: it also leaves out the agents unavailable for this slot this
18529
+ * session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
18530
+ * recovery still see every agent that may hold funds.
18531
+ */
17291
18532
  getEligibleAgents(chainId, asset, opts) {
17292
18533
  const eligible = [...this.agents.values()].filter((agent) => {
17293
- if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
18534
+ if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
17294
18535
  return false;
17295
18536
  }
17296
18537
  const chainAssets = agent.supportedAssets.find(
@@ -17318,20 +18559,13 @@ var OwneySDK = class {
17318
18559
  return approvalOrder || left.index - right.index;
17319
18560
  }).map(({ agent }) => agent);
17320
18561
  }
18562
+ /**
18563
+ * The user cancelled a wallet prompt, for any agent: see isWalletRejection.
18564
+ * That includes an agent error that kept the rejection only as text in
18565
+ * `details.cause`.
18566
+ */
17321
18567
  isUserRejectedWithdrawal(error) {
17322
- let current = error;
17323
- const seen = /* @__PURE__ */ new Set();
17324
- while (current && typeof current === "object" && !seen.has(current)) {
17325
- seen.add(current);
17326
- const candidate = current;
17327
- if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
17328
- const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
17329
- if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
17330
- return true;
17331
- }
17332
- current = candidate.cause;
17333
- }
17334
- return false;
18568
+ return isWalletRejection(error);
17335
18569
  }
17336
18570
  captureReadScope(requestedChain) {
17337
18571
  const original = this.requireState();
@@ -17432,6 +18666,7 @@ var OwneySDK = class {
17432
18666
  if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
17433
18667
  verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
17434
18668
  }
18669
+ if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
17435
18670
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
17436
18671
  if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
17437
18672
  agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
@@ -17440,6 +18675,33 @@ var OwneySDK = class {
17440
18675
  }
17441
18676
  return verified;
17442
18677
  }
18678
+ /**
18679
+ * Tells the agent, once per confirmed deposit transfer, that its deposit
18680
+ * landed (`IAgent.depositConfirmed`), and records the outcome on the
18681
+ * deposit's ledger operation when there is one. In the background: never
18682
+ * throws and never delays the deposit. A missed notice only leaves the
18683
+ * provider on its own schedule.
18684
+ */
18685
+ announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18686
+ try {
18687
+ if (evidence.transfer !== "confirmed") return;
18688
+ const agent = this.agents.get(evidence.agentId);
18689
+ const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
18690
+ if (!agent?.depositConfirmed || !movement) return;
18691
+ const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
18692
+ if (this.announcedDeposits.has(key2)) return;
18693
+ this.announcedDeposits.add(key2);
18694
+ if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18695
+ const legKey = `agent:${evidence.agentId}`;
18696
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18697
+ try {
18698
+ ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18699
+ } catch {
18700
+ }
18701
+ });
18702
+ } catch {
18703
+ }
18704
+ }
17443
18705
  noteFundingRefresh(key2, armed) {
17444
18706
  this.recoveredFundingReads.delete(key2);
17445
18707
  this.recoveredFundingReads.set(key2, armed);
@@ -17928,6 +19190,14 @@ var OwneySDK = class {
17928
19190
  return hash2;
17929
19191
  },
17930
19192
  ensureChain: (id) => this.ensureSwapChain(id),
19193
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
19194
+ // page cannot also hide that it landed (ROUT-726).
19195
+ readWrappedBalance: () => publicClient.readContract({
19196
+ address: wrapper.address,
19197
+ abi: ERC20_ALLOWANCE_ABI,
19198
+ functionName: "balanceOf",
19199
+ args: [walletAddress]
19200
+ }),
17931
19201
  // Read through the same public client as every other sizing input, so
17932
19202
  // a wallet sitting on the wrong chain cannot answer for this one.
17933
19203
  readAllowance: (token, spender) => publicClient.readContract({
@@ -18373,8 +19643,17 @@ var OwneySDK = class {
18373
19643
  * second half of `swapAndDeposit` on its own. Cleared only once the deposit
18374
19644
  * has actually gone through — a failure here leaves the record in place so it
18375
19645
  * can be offered again rather than silently dropped.
19646
+ *
19647
+ * The record does not remember `excludeAgentIds`, on purpose: the caller must
19648
+ * pass the CURRENT list, because the user's choice may have changed since the
19649
+ * swap (a deposit reads it fresh each time). Without it, a record with no
19650
+ * `agentId` splits across every eligible agent. When the list leaves nobody to
19651
+ * fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
19652
+ * before the wallet is touched and keeps the record.
19653
+ *
19654
+ * @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
18376
19655
  */
18377
- async completePendingDeposit(id) {
19656
+ async completePendingDeposit(id, options = {}) {
18378
19657
  const entry = listPendingDeposits().find((p) => p.id === id);
18379
19658
  if (!entry) {
18380
19659
  throw new OwneyError(
@@ -18383,6 +19662,12 @@ var OwneySDK = class {
18383
19662
  { id }
18384
19663
  );
18385
19664
  }
19665
+ this.assertDepositAgentsRemain(
19666
+ entry.chainId,
19667
+ entry.symbol,
19668
+ entry.agentId,
19669
+ options.excludeAgentIds
19670
+ );
18386
19671
  await this.ensureSwapChain(entry.chainId);
18387
19672
  const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
18388
19673
  const amount = token ? await this.settleSwapDepositAmount(
@@ -18395,6 +19680,7 @@ var OwneySDK = class {
18395
19680
  amount,
18396
19681
  asset: entry.symbol,
18397
19682
  ...entry.agentId ? { agentId: entry.agentId } : {},
19683
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18398
19684
  // The swap's own funding-ledger operation; older records have none.
18399
19685
  ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
18400
19686
  ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
@@ -18623,6 +19909,7 @@ var OwneySDK = class {
18623
19909
  async swapAndDeposit(options) {
18624
19910
  const state = this.requireState();
18625
19911
  options.assertCurrent?.();
19912
+ this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
18626
19913
  if (options.agentId) {
18627
19914
  this.validateAssetSupport(
18628
19915
  this.getAgent(options.agentId),
@@ -18724,6 +20011,7 @@ var OwneySDK = class {
18724
20011
  amount,
18725
20012
  asset: options.to.symbol,
18726
20013
  ...options.agentId ? { agentId: options.agentId } : {},
20014
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18727
20015
  ...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
18728
20016
  ...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
18729
20017
  ...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
@@ -19263,7 +20551,7 @@ var OwneySDK = class {
19263
20551
  "A withdrawal request is already running.",
19264
20552
  { chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
19265
20553
  );
19266
- const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
20554
+ const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
19267
20555
  const attempted = /* @__PURE__ */ new Set();
19268
20556
  this.withdrawalSubmissions.add(submissionKey);
19269
20557
  let ledgerOp;
@@ -19734,6 +21022,8 @@ var OwneySDK = class {
19734
21022
  progress({ ...evidence, transfer: "failed", delivery: "failed" });
19735
21023
  if (serverLegs.size && requested2 === void 0 && agent.withdrawalRequiresWalletApproval && error instanceof OwneyError && error.code === "WITHDRAW_INSUFFICIENT_BALANCE" && error.details?.available === "0" && evidence.transfer === "failed" && !evidence.txHash && !evidence.userOpHash && !evidence.callsId)
19736
21024
  ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
21025
+ 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"))
21026
+ ledgerLeg?.(evidence, error.code);
19737
21027
  settled2({ settled: "threw", evidence });
19738
21028
  throw error;
19739
21029
  }
@@ -19841,7 +21131,7 @@ var OwneySDK = class {
19841
21131
  serverLegs.set(planned.agentId, leg);
19842
21132
  }
19843
21133
  };
19844
- const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
21134
+ const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
19845
21135
  const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
19846
21136
  if (!amount) {
19847
21137
  const results2 = {};
@@ -20241,9 +21531,10 @@ var OwneySDK = class {
20241
21531
  }
20242
21532
  async getBalances(agentId, options) {
20243
21533
  if (agentId) {
20244
- const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
21534
+ const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20245
21535
  const asset = options?.asset;
20246
21536
  const agent = this.getAgent(agentId);
21537
+ const state = this.readStateFor(agentId, scope);
20247
21538
  const result = await this.readAgent(
20248
21539
  agent,
20249
21540
  "balances",
@@ -20274,10 +21565,10 @@ var OwneySDK = class {
20274
21565
  async readAggregatedBalances(options, portfolio = false) {
20275
21566
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20276
21567
  const asset = options?.asset;
20277
- const readBalance = (read2) => read2.state === state ? this.readAgent(
21568
+ const readBalance = (read2) => !read2.offChain ? this.readAgent(
20278
21569
  read2.agent,
20279
21570
  "balances",
20280
- () => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
21571
+ () => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
20281
21572
  asset ? { asset } : null
20282
21573
  ) : this.readAgent(
20283
21574
  read2.agent,
@@ -20287,7 +21578,7 @@ var OwneySDK = class {
20287
21578
  );
20288
21579
  let totalBalance = 0;
20289
21580
  const results = {};
20290
- const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
21581
+ const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
20291
21582
  const balanceResults = await Promise.allSettled(
20292
21583
  entries.map(async ([id, read2]) => {
20293
21584
  const { agent } = read2;
@@ -20342,10 +21633,11 @@ var OwneySDK = class {
20342
21633
  const chainId = this.requireChainId();
20343
21634
  if (agentId) {
20344
21635
  const agent = this.getAgent(agentId);
21636
+ const readState = this.readStateFor(agentId, state);
20345
21637
  return this.readAgent(
20346
21638
  agent,
20347
21639
  "earnings",
20348
- () => agent.getEarnings(state, chainId)
21640
+ () => agent.getEarnings(readState, chainId)
20349
21641
  );
20350
21642
  }
20351
21643
  return this.aggregateEarnings(
@@ -20354,7 +21646,7 @@ var OwneySDK = class {
20354
21646
  read2.agent,
20355
21647
  "earnings",
20356
21648
  () => read2.agent.getEarnings(read2.state, read2.chainId),
20357
- read2.state === state ? null : { chainId: read2.chainId }
21649
+ read2.offChain ? { chainId: read2.chainId } : null
20358
21650
  )
20359
21651
  );
20360
21652
  }
@@ -20365,13 +21657,13 @@ var OwneySDK = class {
20365
21657
  async refreshEarnings(agentId) {
20366
21658
  const state = this.requireState();
20367
21659
  const chainId = this.requireChainId();
20368
- const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
21660
+ const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
20369
21661
  agent,
20370
21662
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
20371
21663
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
20372
- readState === state ? null : { chainId: readChain }
21664
+ offChain ? { chainId: readChain } : null
20373
21665
  );
20374
- if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
21666
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
20375
21667
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
20376
21668
  }
20377
21669
  async aggregateEarnings(entries, read2) {
@@ -20439,7 +21731,7 @@ var OwneySDK = class {
20439
21731
  for (const agent of agents) {
20440
21732
  for (const legChainId of chainIds) {
20441
21733
  if (agentRunsOn(agent, legChainId))
20442
- legs.push({ agent, legChainId, legState: state });
21734
+ legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
20443
21735
  }
20444
21736
  }
20445
21737
  if (!agentId) {
@@ -20479,22 +21771,21 @@ var OwneySDK = class {
20479
21771
  assets: []
20480
21772
  };
20481
21773
  }
21774
+ const readState = this.readStateFor(agentId, state);
20482
21775
  return this.readAgent(
20483
21776
  agent,
20484
21777
  "dailyEarnings",
20485
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21778
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
20486
21779
  { days, tokenSymbol }
20487
21780
  );
20488
21781
  }
20489
- const entries = [...this.getActiveAgents().entries()].filter(
20490
- ([, agent]) => agent.getDailyEarnings
20491
- );
21782
+ const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
20492
21783
  const settled2 = await Promise.allSettled(
20493
21784
  entries.map(
20494
- ([, agent]) => this.readAgent(
21785
+ ({ agent, state: readState }) => this.readAgent(
20495
21786
  agent,
20496
21787
  "dailyEarnings",
20497
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21788
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
20498
21789
  { days, tokenSymbol }
20499
21790
  )
20500
21791
  )
@@ -20543,7 +21834,7 @@ var OwneySDK = class {
20543
21834
  `Agent ${agent.id} does not support pool customization`
20544
21835
  );
20545
21836
  }
20546
- await agent.setPoolSelection(params.selection);
21837
+ await agent.setPoolSelection(params.selection, this.state ?? void 0);
20547
21838
  }
20548
21839
  /**
20549
21840
  * The pool selection saved on the user's account (ROUT-650), so the Pools
@@ -20566,6 +21857,15 @@ var OwneySDK = class {
20566
21857
  assets: params.assets
20567
21858
  });
20568
21859
  }
21860
+ /**
21861
+ * The agents a person can customize pools for: registered, enabled, and
21862
+ * able to list a pool catalogue. Waits for agent initialization, so an agent
21863
+ * the organization disabled is known and left out.
21864
+ */
21865
+ async getPoolCustomizationAgents() {
21866
+ await this.ensureAgentsInitialized();
21867
+ return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
21868
+ }
20569
21869
  async getAccountApy({
20570
21870
  agentId,
20571
21871
  days,
@@ -20577,17 +21877,23 @@ var OwneySDK = class {
20577
21877
  const scopeChainId = scope === "all" ? null : scope;
20578
21878
  if (agentId) {
20579
21879
  const agent = this.getAgent(agentId);
20580
- return this.readAgent(
21880
+ const readState = this.readStateFor(agentId, state);
21881
+ const accountApy = await this.readAgent(
20581
21882
  agent,
20582
21883
  "accountApy",
20583
- () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
21884
+ () => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
20584
21885
  { days, tokenSymbol, scopeChainId }
20585
21886
  );
21887
+ return this.enrichApyHistory(
21888
+ accountApy,
21889
+ agentId,
21890
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21891
+ tokenSymbol
21892
+ );
20586
21893
  }
20587
- const entries = scopeChainId === void 0 ? [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })) : this.portfolioReads(state, chainId).filter((read2) => read2.state === state || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
21894
+ const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
20588
21895
  const reads = await Promise.all(
20589
- entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
20590
- const offChain = readState !== state;
21896
+ entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
20591
21897
  const pair = Promise.all([
20592
21898
  this.readAgent(
20593
21899
  agent,
@@ -20619,7 +21925,12 @@ var OwneySDK = class {
20619
21925
  const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
20620
21926
  const results = {};
20621
21927
  for (const [id, apy] of apyResults) {
20622
- results[id] = apy;
21928
+ results[id] = await this.enrichApyHistory(
21929
+ apy,
21930
+ id,
21931
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21932
+ tokenSymbol
21933
+ );
20623
21934
  }
20624
21935
  const balances = {};
20625
21936
  for (const [id, bal] of balanceResults) {
@@ -20649,6 +21960,36 @@ var OwneySDK = class {
20649
21960
  history
20650
21961
  };
20651
21962
  }
21963
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
21964
+ const history = accountApy.history;
21965
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
21966
+ const incentives = await fetchApyIncentives(
21967
+ this.apiKey,
21968
+ {
21969
+ walletAddress: accountApy.walletAddress,
21970
+ agentId,
21971
+ chainId,
21972
+ asset: tokenSymbol,
21973
+ from: history[0].date,
21974
+ to: history[history.length - 1].date
21975
+ },
21976
+ this.routingApiBaseUrl
21977
+ );
21978
+ if (incentives.length === 0) return accountApy;
21979
+ const byDate = /* @__PURE__ */ new Map();
21980
+ for (const { date, ...incentive } of incentives) {
21981
+ const entries = byDate.get(date) ?? [];
21982
+ entries.push(incentive);
21983
+ byDate.set(date, entries);
21984
+ }
21985
+ return {
21986
+ ...accountApy,
21987
+ history: history.map((point) => {
21988
+ const pointIncentives = byDate.get(point.date);
21989
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
21990
+ })
21991
+ };
21992
+ }
20652
21993
  /**
20653
21994
  * Get transaction history for a specific agent, or all agents.
20654
21995
  *
@@ -20676,7 +22017,7 @@ var OwneySDK = class {
20676
22017
  for (const agent of agents) {
20677
22018
  for (const legChainId of chainIds) {
20678
22019
  if (agentRunsOn(agent, legChainId))
20679
- legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
22020
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
20680
22021
  }
20681
22022
  }
20682
22023
  if (!agentId) {
@@ -20720,7 +22061,8 @@ var OwneySDK = class {
20720
22061
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20721
22062
  if (agentId) {
20722
22063
  const agent = this.getAgent(agentId);
20723
- const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
22064
+ const readState = this.readStateFor(agentId, state);
22065
+ const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
20724
22066
  assertCurrent();
20725
22067
  return page;
20726
22068
  }
@@ -20734,10 +22076,11 @@ var OwneySDK = class {
20734
22076
  }
20735
22077
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
20736
22078
  try {
22079
+ const readState = this.readStateFor(agent.id, state);
20737
22080
  const page = await this.readAgent(
20738
22081
  agent,
20739
22082
  "history",
20740
- () => agent.getHistory(state, chainId, agentFilters),
22083
+ () => agent.getHistory(readState, chainId, agentFilters),
20741
22084
  agentFilters
20742
22085
  );
20743
22086
  return { agentId: agent.id, page };
@@ -20795,20 +22138,20 @@ var OwneySDK = class {
20795
22138
  const chainId = this.requireChainId();
20796
22139
  if (agentId) {
20797
22140
  const agent = this.getAgent(agentId);
22141
+ const readState = this.readStateFor(agentId, state);
20798
22142
  return this.readAgent(
20799
22143
  agent,
20800
22144
  "profile",
20801
- () => agent.getUserProfile(state, chainId)
22145
+ () => agent.getUserProfile(readState, chainId)
20802
22146
  );
20803
22147
  }
20804
22148
  const results = {};
20805
- const entries = [...this.getActiveAgents().entries()];
20806
22149
  const profileResults = await Promise.all(
20807
- entries.map(async ([id, agent]) => {
22150
+ this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
20808
22151
  const p = await this.readAgent(
20809
22152
  agent,
20810
22153
  "profile",
20811
- () => agent.getUserProfile(state, chainId)
22154
+ () => agent.getUserProfile(readState, chainId)
20812
22155
  );
20813
22156
  return [id, p];
20814
22157
  })
@@ -21018,10 +22361,11 @@ var OwneySDK = class {
21018
22361
  const entries = [...activeAgents.entries()];
21019
22362
  const balanceResults = await Promise.allSettled(
21020
22363
  entries.map(async ([id, agent]) => {
22364
+ const readState = this.readStateFor(id, state);
21021
22365
  const b = await this.readAgent(
21022
22366
  agent,
21023
22367
  "balances",
21024
- () => agent.getBalances(state, chainId)
22368
+ () => agent.getBalances(readState, chainId)
21025
22369
  );
21026
22370
  return [id, b.positions ?? []];
21027
22371
  })
@@ -21307,5 +22651,6 @@ function createOwneySIWX(config) {
21307
22651
  saveWithdrawSwap,
21308
22652
  setOwneyDebug,
21309
22653
  subscribeWithdrawSwaps,
22654
+ switchWalletConnectChain,
21310
22655
  updateWithdrawSwap
21311
22656
  });