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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -452,6 +452,35 @@ function debugLog(scope, message, data) {
452
452
  // src/lib/routing-api.ts
453
453
  var ROUTING_API_BASE_URL = "https://owney-routing-api-243946518160.europe-west4.run.app";
454
454
  var getRoutingApiBaseUrl = (override) => override ?? ROUTING_API_BASE_URL;
455
+ async function fetchApyIncentives(apiKey, input, baseUrl = ROUTING_API_BASE_URL) {
456
+ const query2 = new URLSearchParams({
457
+ walletAddress: input.walletAddress,
458
+ agentId: input.agentId,
459
+ chainId: String(input.chainId),
460
+ asset: input.asset.toUpperCase(),
461
+ from: input.from,
462
+ to: input.to
463
+ });
464
+ try {
465
+ const response = await fetch(`${baseUrl}/api/v1/apy-incentives?${query2}`, {
466
+ headers: {
467
+ Accept: "application/json",
468
+ "x-owney-api-key": apiKey
469
+ }
470
+ });
471
+ if (!response.ok) return [];
472
+ const body = await response.json();
473
+ if (!body.success || !Array.isArray(body.data)) return [];
474
+ return body.data.filter(
475
+ (item) => item && typeof item.date === "string" && item.source === "merkl" && typeof item.opportunityId === "string" && Array.isArray(item.campaignIds) && Number.isFinite(item.apr) && Number.isFinite(item.apyContribution)
476
+ );
477
+ } catch (error) {
478
+ debugLog("owney-sdk", "APY incentives unavailable; using native APY", {
479
+ error: error instanceof Error ? error.message : String(error)
480
+ });
481
+ return [];
482
+ }
483
+ }
455
484
  async function fetchOrgAgentConfig(apiKey, baseUrl = ROUTING_API_BASE_URL) {
456
485
  const url = `${baseUrl}/api/v1/agent/org-config`;
457
486
  try {
@@ -982,7 +1011,7 @@ var SnapshotHistory = class {
982
1011
  };
983
1012
 
984
1013
  // src/lib/funding-ledger.ts
985
- var SDK_VERSION = "0.7.32-beta.5";
1014
+ var SDK_VERSION = "0.7.32-beta.6";
986
1015
  var SCOPE2 = "funding-ledger";
987
1016
  var REQUEST_TIMEOUT_MS2 = 5e3;
988
1017
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -2292,7 +2321,7 @@ var CHAIN_NAMES = {
2292
2321
  function chainName(chainId) {
2293
2322
  return CHAIN_NAMES[chainId] ?? `chain ${chainId}`;
2294
2323
  }
2295
- var SETTLE_TIMEOUT_MS = 8e3;
2324
+ var SETTLE_TIMEOUT_MS = 15e3;
2296
2325
  var POLL_INTERVAL_MS = 200;
2297
2326
  var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2298
2327
  async function readChainId(pub) {
@@ -4432,11 +4461,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
4432
4461
  if (typeof window === "undefined") return;
4433
4462
  const internals = sdk;
4434
4463
  const original = internals.authenticateUser.bind(internals);
4435
- internals.authenticateUser = async () => {
4464
+ let inFlight2 = null;
4465
+ const authenticate = async () => {
4436
4466
  if (internals.authenticatedUserId !== null) return;
4437
4467
  const address = internals.walletClient?.account?.address;
4438
- const chainId = internals.currentChainId;
4439
- if (address && chainId) {
4468
+ const chainId = internals.currentChainId ?? 0;
4469
+ if (address) {
4440
4470
  const cached = readSession(address, chainId);
4441
4471
  if (cached) {
4442
4472
  internals.httpClient.setAuthToken(cached.token);
@@ -4448,9 +4478,9 @@ var ZyfaiAgent = class _ZyfaiAgent {
4448
4478
  }
4449
4479
  await original();
4450
4480
  const newAddress = internals.walletClient?.account?.address;
4451
- const newChainId = internals.currentChainId;
4481
+ const newChainId = internals.currentChainId ?? 0;
4452
4482
  const newToken = internals.httpClient.authToken;
4453
- if (newAddress && newChainId && newToken) {
4483
+ if (newAddress && newToken) {
4454
4484
  writeSession(newAddress, newChainId, {
4455
4485
  token: newToken,
4456
4486
  userId: internals.authenticatedUserId,
@@ -4459,6 +4489,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
4459
4489
  });
4460
4490
  }
4461
4491
  };
4492
+ internals.authenticateUser = () => {
4493
+ const address = internals.walletClient?.account?.address?.toLowerCase();
4494
+ if (inFlight2 && inFlight2.address === address) return inFlight2.promise;
4495
+ const promise = authenticate().finally(() => {
4496
+ if (inFlight2?.promise === promise) inFlight2 = null;
4497
+ });
4498
+ inFlight2 = { address, promise };
4499
+ return promise;
4500
+ };
4462
4501
  }
4463
4502
  // --- Private helpers ---
4464
4503
  getAddress() {
@@ -4691,12 +4730,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
4691
4730
  }
4692
4731
  // --- IAgent: Account lifecycle ---
4693
4732
  async activateAgent(state, chainId) {
4733
+ const startedAt = Date.now();
4694
4734
  try {
4695
4735
  debugLog("zyfai:activation", "starting", {
4696
4736
  walletAddress: state.walletAddress,
4697
4737
  chainId
4698
4738
  });
4699
4739
  await this.connectAuth(state, chainId);
4740
+ debugLog("zyfai:activation", "signed in", {
4741
+ ms: Date.now() - startedAt
4742
+ });
4700
4743
  const validChainId = isValidChainId(chainId);
4701
4744
  await Promise.all([
4702
4745
  this.ensureProtocolsSynced(validChainId, "USDC"),
@@ -4707,7 +4750,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
4707
4750
  // validator, so pool-wallet users see no prompt. Non-fatal.
4708
4751
  this.ensureSessionKeyIfDeployed(validChainId)
4709
4752
  ]);
4710
- debugLog("zyfai:activation", "completed", { chainId: validChainId });
4753
+ debugLog("zyfai:activation", "completed", {
4754
+ chainId: validChainId,
4755
+ ms: Date.now() - startedAt
4756
+ });
4711
4757
  } catch (error) {
4712
4758
  throw error;
4713
4759
  }
@@ -6403,6 +6449,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
6403
6449
  const generation = this.earningsGeneration;
6404
6450
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
6405
6451
  const raw2 = await this.sdk.getPortfolio(this.getAddress());
6452
+ debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
6406
6453
  const balance = mapBalances(raw2, validChainId, smartWallet);
6407
6454
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
6408
6455
  for (const asset of SupportedAssets.filter((item) => item.chainId === chainId)) {
@@ -6817,6 +6864,27 @@ import {
6817
6864
  } from "viem";
6818
6865
  import { base as base4 } from "viem/chains";
6819
6866
 
6867
+ // src/lib/wallet-rejection.ts
6868
+ var REJECTION_MESSAGE = /user (?:rejected|denied)|rejected by user|request rejected/i;
6869
+ function isWalletRejection(error) {
6870
+ let current = error;
6871
+ const seen = /* @__PURE__ */ new Set();
6872
+ while (current && typeof current === "object" && !seen.has(current)) {
6873
+ seen.add(current);
6874
+ const candidate = current;
6875
+ if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
6876
+ const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
6877
+ if (REJECTION_MESSAGE.test(message)) return true;
6878
+ const details = candidate.details;
6879
+ if (details && typeof details === "object") {
6880
+ const cause = details.cause;
6881
+ if (typeof cause === "string" && REJECTION_MESSAGE.test(cause)) return true;
6882
+ }
6883
+ current = candidate.cause;
6884
+ }
6885
+ return false;
6886
+ }
6887
+
6820
6888
  // src/agents/yieldseeker/yieldseeker.auth.ts
6821
6889
  import { SiweMessage, generateNonce } from "siwe";
6822
6890
  import {
@@ -7863,11 +7931,13 @@ function mapYieldseekerProfile(address, contexts) {
7863
7931
  protocols: [...protocols]
7864
7932
  };
7865
7933
  }
7866
- function mapYieldseekerAgentApy(stats) {
7934
+ function mapYieldseekerAgentApy(stats, days) {
7867
7935
  const perAsset = {};
7868
7936
  const all = [];
7869
7937
  for (const entry of stats) {
7870
- const expected = percent(entry.stats.expectedApy7d);
7938
+ const expected = percent(
7939
+ days === "30D" ? entry.stats.expectedApy30d : entry.stats.expectedApy7d
7940
+ );
7871
7941
  if (!Number.isFinite(expected)) continue;
7872
7942
  perAsset[entry.asset] = expected;
7873
7943
  all.push(expected);
@@ -8046,6 +8116,15 @@ function sponsorError(message, safeToFallback, details = {}) {
8046
8116
  "yieldseeker"
8047
8117
  );
8048
8118
  }
8119
+ function cannotSignRawHash(error) {
8120
+ for (let current = error, depth = 0; current && depth < 5; depth++) {
8121
+ const code = current.code;
8122
+ if (code === -32602 || code === -32601 || code === 4200) return true;
8123
+ if (code === 4001) return false;
8124
+ current = current.cause;
8125
+ }
8126
+ return false;
8127
+ }
8049
8128
  function assertIntentFresh(expiresAt) {
8050
8129
  if (!Number.isFinite(expiresAt) || Date.now() + 5e3 >= expiresAt * 1e3)
8051
8130
  throw sponsorError(
@@ -8407,7 +8486,18 @@ async function submitEoa(input) {
8407
8486
  transport: custom3(input.state.provider)
8408
8487
  });
8409
8488
  input.assertCurrent?.();
8410
- const signature = await wallet.signMessage({ message: { raw: userOpHash } });
8489
+ let signature;
8490
+ try {
8491
+ signature = await wallet.signMessage({ message: { raw: userOpHash } });
8492
+ } catch (error) {
8493
+ if (cannotSignRawHash(error))
8494
+ throw sponsorError(
8495
+ "This wallet cannot sign the gas-free withdrawal.",
8496
+ true,
8497
+ { failureCode: "OWNER_SIGNATURE_UNSUPPORTED" }
8498
+ );
8499
+ throw error;
8500
+ }
8411
8501
  operation = { ...operation, signature };
8412
8502
  await assertOwnerSession(input.state, input.owner);
8413
8503
  assertIntentFresh(input.expiresAt);
@@ -8679,11 +8769,47 @@ var YIELDSEEKER_USERNAME_RANDOM_LENGTH = 14;
8679
8769
  var YIELDSEEKER_USERNAME_CREATE_ATTEMPTS = 3;
8680
8770
  var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
8681
8771
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
8772
+ var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
8773
+ var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
8774
+ var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
8775
+ var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
8682
8776
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
8683
8777
  var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
8684
8778
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
8685
8779
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
8686
8780
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
8781
+ function apyAsPercent(fraction) {
8782
+ if (typeof fraction !== "number" || !Number.isFinite(fraction)) return null;
8783
+ return Number((fraction * 100).toPrecision(12));
8784
+ }
8785
+ function isActiveMemory(memory) {
8786
+ return !!memory && memory.isActive !== false && memory.isDeleted !== true;
8787
+ }
8788
+ function vaultOptionsKey(asset, includeUnavailable) {
8789
+ return `${asset}:${includeUnavailable ? "all" : "usable"}`;
8790
+ }
8791
+ function isManagedVaultList(memory) {
8792
+ return memory.managedRuleType === YIELDSEEKER_MANAGED_VAULT_RULE;
8793
+ }
8794
+ function isLegacyPoolSelectionMemory(memory) {
8795
+ if (isManagedVaultList(memory) || typeof memory.content !== "string") return false;
8796
+ const content = memory.content.trim();
8797
+ return content.startsWith(YIELDSEEKER_POOL_MEMORY_PREFIX) && /0x[0-9a-fA-F]{40}/.test(content.slice(YIELDSEEKER_POOL_MEMORY_PREFIX.length));
8798
+ }
8799
+ function uniqueAddresses(addresses) {
8800
+ const seen = /* @__PURE__ */ new Set();
8801
+ return addresses.filter((address) => {
8802
+ const key2 = address.toLowerCase();
8803
+ if (seen.has(key2)) return false;
8804
+ seen.add(key2);
8805
+ return true;
8806
+ });
8807
+ }
8808
+ function sameVaults(actual, expected) {
8809
+ const want = new Set(expected.map((address) => address.toLowerCase()));
8810
+ const got = new Set(actual.map((address) => address.toLowerCase()));
8811
+ return got.size === want.size && [...want].every((address) => got.has(address));
8812
+ }
8687
8813
  function isYieldseekerWalletCodeMissing(error) {
8688
8814
  for (let current = error, depth = 0; current && depth < 8; current = current.cause, depth++) {
8689
8815
  const { name, message } = current;
@@ -8693,6 +8819,8 @@ function isYieldseekerWalletCodeMissing(error) {
8693
8819
  return false;
8694
8820
  }
8695
8821
  var YIELDSEEKER_CREATE_CONFLICT_CODES = /* @__PURE__ */ new Set(["AGENT_ACCOUNT_EXISTS", "AGENT_CREATE_IN_PROGRESS"]);
8822
+ var YIELDSEEKER_REACTIVATE_LIMIT_CODES = /* @__PURE__ */ new Set(["USER_MAX_ACTIVE_AGENTS_REACHED", "USER_ALREADY_HAS_AGENT_FOR_ASSET"]);
8823
+ var YIELDSEEKER_REACTIVATE_CLOSED_CODES = /* @__PURE__ */ new Set(["AGENT_WALLET_OUTDATED", "AGENT_TYPE_NOT_SUPPORTED"]);
8696
8824
  var YIELDSEEKER_WALLET_MATCH_LIMIT = 5;
8697
8825
  var YIELDSEEKER_PORTFOLIO_CACHE_MS = 12e4;
8698
8826
  var YIELDSEEKER_SETTLEMENT_BACKOFF_MS = [5e3, 1e4, 2e4, 4e4, 6e4];
@@ -8712,6 +8840,7 @@ var YIELDSEEKER_ACTIVITY_CACHE_MS = 6e4;
8712
8840
  var YIELDSEEKER_MAX_WITHDRAW_SWEEPS = 3;
8713
8841
  var YIELDSEEKER_WITHDRAWAL_READ_TIMEOUT_MS = 3e4;
8714
8842
  var YIELDSEEKER_MAX_POSITION_VERIFICATION_MS = 2e3;
8843
+ var YIELDSEEKER_LATE_FEE_RATE_MS = 5e3;
8715
8844
  var YIELDSEEKER_WITHDRAWAL_CANDIDATE_LIMIT = 64;
8716
8845
  var YIELDSEEKER_VAULTS_PER_RPC_BATCH = 10;
8717
8846
  function generateYieldseekerUsername() {
@@ -8804,9 +8933,31 @@ var YieldseekerAgent = class {
8804
8933
  walletContexts = /* @__PURE__ */ new Map();
8805
8934
  agentAccountReads = /* @__PURE__ */ new Map();
8806
8935
  reportedAccounts = /* @__PURE__ */ new Set();
8807
- // Slots whose verified agent is missing even from a re-read list, until the
8808
- // list cache window ends. Stops a re-read on every portfolio poll.
8936
+ // Slots whose verified agent is missing even from a re-read list (and could
8937
+ // not be reopened), with the error the lookup failed with, until the list
8938
+ // cache window ends. Stops a re-read and a reactivate on every portfolio poll.
8809
8939
  missingSlots = /* @__PURE__ */ new Map();
8940
+ // A remembered rate limit rethrown with the time left on its marker
8941
+ // (throwIfSlotMissing), mapped to the remembered error it copies, so
8942
+ // isMarkedSlotFailure still recognises it.
8943
+ rethrownSlotFailures = /* @__PURE__ */ new WeakMap();
8944
+ // Slots whose verified agent Yieldseeker will never reopen (a reactivate
8945
+ // answered AGENT_WALLET_OUTDATED or AGENT_TYPE_NOT_SUPPORTED), keyed by
8946
+ // slotKey, with that YIELDSEEKER_AGENT_CLOSED error. A permanent answer, so
8947
+ // it is kept for the session, like unavailableSlots: reads and deposits get
8948
+ // it with no request until disconnect, or until a lookup selects an agent
8949
+ // for the slot.
8950
+ closedSlots = /* @__PURE__ */ new Map();
8951
+ // In-flight reopens (reactivate, then a fresh list read) keyed by slotKey,
8952
+ // shared by concurrent lookups of one slot.
8953
+ pendingReopens = /* @__PURE__ */ new Map();
8954
+ // Slots Yieldseeker will not give an agent this session (a reactivate answered
8955
+ // an active-agent limit), keyed by slotKey, with the provider's limit code.
8956
+ // Never expires: it answers without a request until disconnect.
8957
+ unavailableSlots = /* @__PURE__ */ new Map();
8958
+ // In-flight reactivates keyed by slotKey + agentId, shared by every caller
8959
+ // (a read-time reopen, deposits): one request however many ask.
8960
+ pendingReactivates = /* @__PURE__ */ new Map();
8810
8961
  // In-flight cache-bypassing list reads, shared by concurrent callers.
8811
8962
  freshListReads = /* @__PURE__ */ new Map();
8812
8963
  // Every contextKey computed this session; asset-only calls fall back to them.
@@ -8859,6 +9010,7 @@ var YieldseekerAgent = class {
8859
9010
  ledgerBudgetMs = LEDGER_READ_BUDGET_MS;
8860
9011
  /** slotKey -> the last successful ledger rows and when they arrived. */
8861
9012
  lastLedgerRows = /* @__PURE__ */ new Map();
9013
+ /** Keyed by `vaultOptionsKey`: each asset's usable list and its full list are cached apart. */
8862
9014
  vaultOptions = /* @__PURE__ */ new Map();
8863
9015
  pendingVaultOptions = /* @__PURE__ */ new Map();
8864
9016
  assetApyStats = /* @__PURE__ */ new Map();
@@ -8915,6 +9067,121 @@ var YieldseekerAgent = class {
8915
9067
  this.pendingWalletStatus.set(key2, pending);
8916
9068
  return { ...await pending };
8917
9069
  }
9070
+ /**
9071
+ * Deposits go only to an agent Yieldseeker still has open. The session caches
9072
+ * the selected agent, so a tab left open can hold one Yieldseeker has since
9073
+ * closed (deactivated). This reads the agent wallet fresh from Yieldseeker,
9074
+ * bypassing the cached wallet contexts, and:
9075
+ * - open, same wallet address: returns the context to deposit with;
9076
+ * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9077
+ * continues only when it is now open with the same address. Only the
9078
+ * verified record's agent is reopened: any other closed agent (a
9079
+ * superseded-wallet match, or a named agent with no verified record, also
9080
+ * when the accounts could not be read) refuses without a request;
9081
+ * - anything else refuses with nothing sent, before any progress event,
9082
+ * signature or callback. Every refusal carries `notSubmitted` and
9083
+ * `safeToFallback: false`, so no paid fallback runs.
9084
+ * A slot recorded unavailable (the active-agent limit) refuses at once with
9085
+ * no request. The reactivate goes through reactivateSlot, which shares one
9086
+ * request per slot and remembers a failure for the list-cache window, so
9087
+ * repeated deposits do not repeat it. A failed wallet read fails closed
9088
+ * (YIELDSEEKER_WALLET_UNVERIFIED, reason UNAVAILABLE), like the on-chain
9089
+ * gate. A reactivate that fails keeps its error code
9090
+ * (YIELDSEEKER_AGENT_CLOSED, or the mapped API error for a transient
9091
+ * failure). At the limit the slot is also recorded unavailable for the
9092
+ * session (see isSlotUnavailable). Session changes keep their own
9093
+ * NOT_CONNECTED error.
9094
+ */
9095
+ async assertAgentOpen(state, chainId, asset, context) {
9096
+ const generation = this.readGeneration;
9097
+ const agentId = context.agent.agentId;
9098
+ const agentWallet = context.wallet.walletAddress;
9099
+ const refusal = { notSubmitted: true, safeToFallback: false };
9100
+ const slot = this.slotKey(state, chainId, asset);
9101
+ const unavailable = this.unavailableSlots.get(slot);
9102
+ if (unavailable !== void 0) throw this.agentClosed(chainId, asset, agentId, unavailable, refusal);
9103
+ const readWallet = async () => {
9104
+ let fresh2;
9105
+ try {
9106
+ const answer = await this.walletRequest(
9107
+ state,
9108
+ chainId,
9109
+ this.agentPath(context, "wallet")
9110
+ );
9111
+ if (!answer?.agentWallet || !isAddress4(answer.agentWallet.walletAddress)) {
9112
+ throw this.invalidResponse("agent wallet");
9113
+ }
9114
+ fresh2 = answer.agentWallet;
9115
+ } catch (error) {
9116
+ this.assertSession(generation, chainId, asset);
9117
+ throw new OwneyError(
9118
+ "YIELDSEEKER_WALLET_UNVERIFIED",
9119
+ "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
9120
+ {
9121
+ ...refusal,
9122
+ reason: "UNAVAILABLE",
9123
+ agentWallet,
9124
+ asset,
9125
+ cause: error instanceof Error ? error.message : String(error)
9126
+ },
9127
+ this.id
9128
+ );
9129
+ }
9130
+ this.assertSession(generation, chainId, asset);
9131
+ return fresh2;
9132
+ };
9133
+ let fresh = await readWallet();
9134
+ let reopened = false;
9135
+ if (fresh.deactivatedDate) {
9136
+ this.forgetAgentWallet(agentId);
9137
+ const accounts = await this.agentAccounts(state, chainId);
9138
+ this.assertSession(generation, chainId, asset);
9139
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
9140
+ if (!verified || verified.providerAgentId !== agentId) {
9141
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "NOT_VERIFIED_AGENT" });
9142
+ }
9143
+ let result;
9144
+ try {
9145
+ result = await this.reactivateSlot(state, chainId, context.user, asset, agentId);
9146
+ } catch (error) {
9147
+ this.assertSession(generation, chainId, asset);
9148
+ const failure = error instanceof OwneyError ? error : this.mapApiError(error);
9149
+ if (failure.code === "YIELDSEEKER_AGENT_CLOSED") {
9150
+ const { providerCode, reason } = failure.details ?? {};
9151
+ throw this.agentClosed(
9152
+ chainId,
9153
+ asset,
9154
+ agentId,
9155
+ typeof providerCode === "string" ? providerCode : void 0,
9156
+ { ...refusal, ...typeof reason === "string" ? { reason } : {} }
9157
+ );
9158
+ }
9159
+ throw new OwneyError(
9160
+ failure.code,
9161
+ `Yieldseeker could not reopen the closed ${asset} agent. Nothing was sent. Please retry.`,
9162
+ { ...failure.details, ...refusal, cause: failure.message },
9163
+ failure.agentId
9164
+ );
9165
+ }
9166
+ this.assertSession(generation, chainId, asset);
9167
+ if (result.outcome === "limit") throw this.agentClosed(chainId, asset, agentId, result.providerCode, refusal);
9168
+ this.forgetAgentWallet(agentId);
9169
+ fresh = await readWallet();
9170
+ if (fresh.deactivatedDate) {
9171
+ this.rememberMissingSlot(
9172
+ slot,
9173
+ generation,
9174
+ this.agentClosed(chainId, asset, agentId, void 0, { reason: "STILL_DEACTIVATED" })
9175
+ );
9176
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "STILL_DEACTIVATED" });
9177
+ }
9178
+ reopened = true;
9179
+ }
9180
+ if (fresh.walletAddress.toLowerCase() !== agentWallet.toLowerCase()) {
9181
+ throw this.agentClosed(chainId, asset, agentId, void 0, { ...refusal, reason: "WALLET_CHANGED" });
9182
+ }
9183
+ return reopened ? { ...context, wallet: fresh } : context;
9184
+ }
8918
9185
  /**
8919
9186
  * Deposits go only to a wallet whose identity is verified on chain (factory
8920
9187
  * mapping, owner, base asset, FACTORY). The API key is public, so the wallet
@@ -9224,6 +9491,10 @@ var YieldseekerAgent = class {
9224
9491
  this.pendingSlotInvalidations.clear();
9225
9492
  this.knownContextKeys.clear();
9226
9493
  this.missingSlots.clear();
9494
+ this.closedSlots.clear();
9495
+ this.pendingReopens.clear();
9496
+ this.pendingReactivates.clear();
9497
+ this.unavailableSlots.clear();
9227
9498
  this.freshListReads.clear();
9228
9499
  this.balanceVaults.clear();
9229
9500
  this.pendingAgents.clear();
@@ -9251,11 +9522,43 @@ var YieldseekerAgent = class {
9251
9522
  this.planHistoryKeys.clear();
9252
9523
  this.lastLedgerRows.clear();
9253
9524
  }
9525
+ /**
9526
+ * Ready every asset's agent, `asset` first: a missing one is created and a
9527
+ * closed one reopened (2026-11-06). A slot Yieldseeker will never let the
9528
+ * user have (the agent limit, closed for good, missing with no way to
9529
+ * reopen) is rethrown with `details.permanent`, which refuses the connect.
9530
+ * A temporary failure (an API error or timeout) on another asset does not:
9531
+ * that slot answers again where it is needed. On the selected asset every
9532
+ * failure is thrown as before, without readying the rest, so a failed
9533
+ * sign-in never opens a second prompt.
9534
+ */
9254
9535
  async activateAgent(state, chainId, asset) {
9255
9536
  this.assertChain(chainId);
9256
9537
  const targetAsset = asset ?? "USDC";
9257
9538
  this.assertAsset(targetAsset);
9258
- await this.ensureAgent(state, chainId, targetAsset);
9539
+ const others = Object.keys(YIELDSEEKER_ASSET_METADATA).filter((each) => each !== targetAsset);
9540
+ for (const each of [targetAsset, ...others]) {
9541
+ try {
9542
+ await this.ensureAgent(state, chainId, each);
9543
+ } catch (error) {
9544
+ if (this.isSlotEmpty(error)) throw this.permanentFailure(error);
9545
+ const temporary = error instanceof OwneyError && (error.code === "AGENT_API_ERROR" || error.code === "AGENT_TIMEOUT");
9546
+ if (each === targetAsset || !temporary) throw error;
9547
+ debugLog("yieldseeker:connect", `${each}: agent not ready, connect continues`, {
9548
+ code: error.code,
9549
+ statusCode: error.details?.statusCode
9550
+ });
9551
+ }
9552
+ }
9553
+ }
9554
+ /** The same failure, marked as one that will not go away this session. */
9555
+ permanentFailure(error) {
9556
+ const message = error.message.replace(/^\[[^\]]*\](?:\[agent:[^\]]*\])?\s*/, "");
9557
+ return new OwneyError(error.code, message, { ...error.details, permanent: true }, this.id);
9558
+ }
9559
+ isSlotUnavailable(state, chainId, asset) {
9560
+ if (asset !== "USDC" && asset !== "WETH") return false;
9561
+ return this.unavailableSlots.has(this.slotKey(state, chainId, asset));
9259
9562
  }
9260
9563
  async deposit(state, chainId, amount, asset, depositCallback, onProgress, onBeforeSubmission) {
9261
9564
  this.assertChain(chainId);
@@ -9268,7 +9571,20 @@ var YieldseekerAgent = class {
9268
9571
  this.id
9269
9572
  );
9270
9573
  }
9271
- const context = await this.ensureAgent(state, chainId, asset);
9574
+ const selected = await this.ensureAgent(state, chainId, asset).catch((error) => {
9575
+ if (error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED") {
9576
+ const { agentId, providerCode, reason } = error.details ?? {};
9577
+ throw this.agentClosed(
9578
+ chainId,
9579
+ asset,
9580
+ typeof agentId === "string" ? agentId : "",
9581
+ typeof providerCode === "string" ? providerCode : void 0,
9582
+ { notSubmitted: true, safeToFallback: false, ...typeof reason === "string" ? { reason } : {} }
9583
+ );
9584
+ }
9585
+ throw error;
9586
+ });
9587
+ const context = await this.assertAgentOpen(state, chainId, asset, selected);
9272
9588
  await this.assertDepositWalletVerified(state, chainId, asset, context);
9273
9589
  const generation = this.readGeneration;
9274
9590
  const movement = this.snapshotMovement(state, chainId, context, BigInt(amount));
@@ -9458,15 +9774,14 @@ var YieldseekerAgent = class {
9458
9774
  if (timer) clearTimeout(timer);
9459
9775
  }
9460
9776
  };
9461
- const feeRateRead = amount === void 0 ? Promise.resolve(0) : boundedVerification(
9462
- (() => {
9463
- try {
9464
- return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9465
- } catch (error) {
9466
- return Promise.reject(error);
9467
- }
9468
- })().catch(() => void 0)
9469
- );
9777
+ const feeRateAnswer = amount === void 0 ? Promise.resolve(0) : (() => {
9778
+ try {
9779
+ return this.portfolioSnapshot(state, chainId, context, contextKey).read.then((value) => value.agentSnapshot.feeRateBps);
9780
+ } catch (error) {
9781
+ return Promise.reject(error);
9782
+ }
9783
+ })().catch(() => void 0);
9784
+ const feeRateRead = boundedVerification(feeRateAnswer);
9470
9785
  const positionsRead = this.readWithdrawalPositions(state, chainId, context);
9471
9786
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
9472
9787
  const agentWallet = getAddress6(context.wallet.walletAddress);
@@ -9776,9 +10091,10 @@ var YieldseekerAgent = class {
9776
10091
  }
9777
10092
  const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
9778
10093
  const availableForOwner = ownerFunds.available;
9779
- const feeRate = feeRateBps ?? 0;
9780
- const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9781
10094
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10095
+ const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
10096
+ this.assertSession(generation, chainId, asset);
10097
+ const maxFee = confirmedMovement && Number.isInteger(feeRate) && feeRate >= 0 && feeRate <= 1e3 ? (grossUnwound * BigInt(feeRate) + 9999n) / 10000n : 0n;
9782
10098
  if (availableForOwner === 0n || amount !== void 0 && shortfall > maxFee + confirmedUnwinds) {
9783
10099
  this.invalidateFundingRead(state, chainId, asset);
9784
10100
  if (amount === void 0 && positionsStatus !== "empty")
@@ -10032,7 +10348,7 @@ var YieldseekerAgent = class {
10032
10348
  positions.forEach((p) => vaults.set(p.vaultOption.address.toLowerCase(), p.vaultOption));
10033
10349
  const needsInventory = !proof.inventoryComplete;
10034
10350
  if (needsInventory || [...vaults.values()].some((option) => !option.provider)) {
10035
- const catalog = await this.loadVaultOptions(asset).catch(() => []);
10351
+ const catalog = await this.loadVaultOptions(asset, { includeUnavailable: true }).catch(() => []);
10036
10352
  const eligible = catalog.filter((o) => o.chainId === evidence.chainId && o.assetAddress?.toLowerCase() === metadata.address.toLowerCase() && isAddress4(o.address));
10037
10353
  if (needsInventory && !eligible.length) return unknown2("INVENTORY_INCOMPLETE");
10038
10354
  for (const option of eligible) {
@@ -10108,7 +10424,8 @@ var YieldseekerAgent = class {
10108
10424
  const hints = new Map(this.validateWithdrawalPositions(positions, chainId, context.asset).map((position2) => [position2.vaultOption.address.toLowerCase(), position2]));
10109
10425
  const historic = this.readCache.get(`historic:${key2}`)?.value?.position;
10110
10426
  const receivedAssets = new Set((historic?.movements ?? []).filter((movement) => movement.chainId === chainId && movement.agentWalletId === context.wallet.agentWalletId && movement.toAddress?.toLowerCase() === context.wallet.walletAddress.toLowerCase()).filter((movement) => typeof movement.assetAddress === "string").map((movement) => movement.assetAddress.toLowerCase()));
10111
- for (const option of this.vaultOptions.get(context.asset)?.value ?? []) {
10427
+ const cachedOptions = this.vaultOptions.get(vaultOptionsKey(context.asset, true)) ?? this.vaultOptions.get(vaultOptionsKey(context.asset, false));
10428
+ for (const option of cachedOptions?.value ?? []) {
10112
10429
  if (option.chainId !== chainId || typeof option.assetAddress !== "string" || option.assetAddress.toLowerCase() !== YIELDSEEKER_ASSET_METADATA[context.asset].address.toLowerCase() || !isAddress4(option.address) || !receivedAssets.has(option.address.toLowerCase()) || hints.has(option.address.toLowerCase())) continue;
10113
10430
  hints.set(option.address.toLowerCase(), {
10114
10431
  vaultOption: option,
@@ -10321,7 +10638,7 @@ var YieldseekerAgent = class {
10321
10638
  assertReadCurrent();
10322
10639
  return proof(true);
10323
10640
  }
10324
- const catalog = await this.loadVaultOptions(context.asset).catch(() => void 0);
10641
+ const catalog = await this.loadVaultOptions(context.asset, { includeUnavailable: true }).catch(() => void 0);
10325
10642
  assertReadCurrent();
10326
10643
  const eligible = /* @__PURE__ */ new Map();
10327
10644
  for (const option of catalog ?? []) {
@@ -10464,8 +10781,37 @@ var YieldseekerAgent = class {
10464
10781
  }
10465
10782
  return false;
10466
10783
  }
10784
+ /**
10785
+ * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10786
+ * it now instead of on its next 30-minute check. Yieldseeker decides whether
10787
+ * anything moves (the funding minimum, a deployed agent, no manual
10788
+ * withdrawal in the last hour). Uses the agent this session already knows
10789
+ * for the asset and the saved sign-in only: never prompts, never retries,
10790
+ * never throws.
10791
+ */
10792
+ async depositConfirmed(state, chainId, evidence) {
10793
+ try {
10794
+ const asset = String(evidence.token).toUpperCase();
10795
+ if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10796
+ return { notified: false, reason: "UNSUPPORTED" };
10797
+ const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10798
+ if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10799
+ return { notified: false, reason: "NO_AGENT" };
10800
+ if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
10801
+ await this.walletRequest(
10802
+ state,
10803
+ chainId,
10804
+ this.agentPath(context, "deposit-made"),
10805
+ { method: "POST", body: {}, promptless: true }
10806
+ );
10807
+ return { notified: true };
10808
+ } catch (error) {
10809
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
10810
+ }
10811
+ }
10467
10812
  async getFundingWallet(state, chainId, asset) {
10468
10813
  this.assertAsset(asset);
10814
+ this.throwIfSlotUnavailable(state, chainId, asset);
10469
10815
  const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10470
10816
  if (!context) throw new OwneyError("NOT_CONNECTED", "Reconnect the agent before recovering funding.");
10471
10817
  return context.wallet.walletAddress;
@@ -10526,7 +10872,7 @@ var YieldseekerAgent = class {
10526
10872
  });
10527
10873
  const catalog = await Promise.all(
10528
10874
  [...new Set(contexts.map((context) => context.asset))].map(
10529
- (contextAsset) => this.loadVaultOptions(contextAsset)
10875
+ (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
10530
10876
  )
10531
10877
  );
10532
10878
  const vaultAddresses = new Set(
@@ -10551,11 +10897,11 @@ var YieldseekerAgent = class {
10551
10897
  );
10552
10898
  }
10553
10899
  async getAgentApy(days, options) {
10554
- if (!this.supportsAgentApyPeriod(days)) {
10900
+ if (days === "14D") {
10555
10901
  throw new OwneyError(
10556
10902
  "AGENT_APY_PERIOD_UNSUPPORTED",
10557
10903
  `Yieldseeker does not provide a representative ${days} strategy APY.`,
10558
- { days, supportedDays: ["7D"] },
10904
+ { days, supportedDays: ["7D", "30D"] },
10559
10905
  this.id
10560
10906
  );
10561
10907
  }
@@ -10568,10 +10914,10 @@ var YieldseekerAgent = class {
10568
10914
  return { asset, stats: await this.loadAssetApyStats(asset) };
10569
10915
  })
10570
10916
  );
10571
- return mapYieldseekerAgentApy(values);
10917
+ return mapYieldseekerAgentApy(values, days);
10572
10918
  }
10573
10919
  supportsAgentApyPeriod(days) {
10574
- return days === "7D";
10920
+ return days === "7D" || days === "30D";
10575
10921
  }
10576
10922
  async loadAssetApyStats(asset) {
10577
10923
  const cached = this.assetApyStats.get(asset);
@@ -10583,7 +10929,7 @@ var YieldseekerAgent = class {
10583
10929
  `/chains/8453/assets/${metadata.address}/apy-stats?rulePreset=explorative`
10584
10930
  ).then((response) => {
10585
10931
  const stats = response?.assetApyStats;
10586
- if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d)) {
10932
+ if (!stats || stats.chainId !== 8453 || typeof stats.assetAddress !== "string" || stats.assetAddress.toLowerCase() !== metadata.address.toLowerCase() || stats.rulePreset !== "explorative" || typeof stats.expectedApy7d !== "number" || !Number.isFinite(stats.expectedApy7d) || typeof stats.expectedApy30d !== "number" || !Number.isFinite(stats.expectedApy30d)) {
10587
10933
  throw this.invalidResponse("asset APY statistics");
10588
10934
  }
10589
10935
  this.assetApyStats.set(asset, {
@@ -10595,27 +10941,321 @@ var YieldseekerAgent = class {
10595
10941
  this.pendingAssetApyStats.set(asset, request2);
10596
10942
  return request2;
10597
10943
  }
10598
- async loadVaultOptions(asset) {
10599
- const cached = this.vaultOptions.get(asset);
10944
+ /**
10945
+ * The deposit-time Pools step's catalogue: every vault Yieldseeker lists
10946
+ * for a new agent on `asset` on Base, grouped by provider (the provider is
10947
+ * both `protocolId` and `name`). Nothing is filtered on our side, on
10948
+ * liquidity, size or provider. `strategy` is accepted for the IAgent
10949
+ * contract and ignored.
10950
+ */
10951
+ async getPoolCatalog(params) {
10952
+ const asset = params.asset.toUpperCase();
10953
+ this.assertAsset(asset);
10954
+ const byProvider = /* @__PURE__ */ new Map();
10955
+ for (const vault of await this.loadVaultOptions(asset)) {
10956
+ const pools = byProvider.get(vault.provider) ?? [];
10957
+ pools.push({
10958
+ chainId: 8453,
10959
+ token: asset,
10960
+ name: vault.name,
10961
+ apy: apyAsPercent(vault.totalApy),
10962
+ tvlUsd: Number.isFinite(vault.totalDepositsUsd) ? vault.totalDepositsUsd : null,
10963
+ link: null,
10964
+ address: vault.address
10965
+ });
10966
+ byProvider.set(vault.provider, pools);
10967
+ }
10968
+ return [...byProvider].map(([provider, pools]) => ({
10969
+ protocolId: provider,
10970
+ name: provider,
10971
+ logo: null,
10972
+ pools
10973
+ }));
10974
+ }
10975
+ /**
10976
+ * The asset's vaults on Base. By default only those a new agent can use:
10977
+ * Yieldseeker leaves out the ones it has disabled (40acres and Moonwell
10978
+ * among them), gated or can't use, so the picker follows its list
10979
+ * (2026-11-04). `includeUnavailable` adds those back, for anything about
10980
+ * money an agent may still hold in one: withdrawals and activity.
10981
+ */
10982
+ async loadVaultOptions(asset, { includeUnavailable = false } = {}) {
10983
+ const key2 = vaultOptionsKey(asset, includeUnavailable);
10984
+ const cached = this.vaultOptions.get(key2);
10600
10985
  if (cached && cached.expiresAt > Date.now()) return cached.value;
10601
- const pending = this.pendingVaultOptions.get(asset);
10986
+ const pending = this.pendingVaultOptions.get(key2);
10602
10987
  if (pending) return pending;
10603
10988
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
10604
10989
  const request2 = this.api.request(
10605
- `/chains/8453/assets/${metadata.address}/vault-options`
10990
+ `/chains/8453/assets/${metadata.address}/vault-options${includeUnavailable ? "?shouldIncludeUnavailable=true" : ""}`
10606
10991
  ).then((response) => {
10607
10992
  if (!Array.isArray(response?.vaultOptions)) {
10608
10993
  throw this.invalidResponse("vault options");
10609
10994
  }
10610
- this.vaultOptions.set(asset, {
10995
+ this.vaultOptions.set(key2, {
10611
10996
  expiresAt: Date.now() + YIELDSEEKER_VAULT_OPTIONS_CACHE_MS,
10612
10997
  value: response.vaultOptions
10613
10998
  });
10614
10999
  return response.vaultOptions;
10615
- }).finally(() => this.pendingVaultOptions.delete(asset));
10616
- this.pendingVaultOptions.set(asset, request2);
11000
+ }).finally(() => this.pendingVaultOptions.delete(key2));
11001
+ this.pendingVaultOptions.set(key2, request2);
10617
11002
  return request2;
10618
11003
  }
11004
+ /**
11005
+ * Save the user's Yieldseeker picks as the agent's managed vault list, then
11006
+ * read the rules back before any money moves. Each asset has its own agent,
11007
+ * so each is saved on its own. `pools` and `availablePools` hold vault
11008
+ * addresses.
11009
+ *
11010
+ * - Only Base entries are ours. An asset with no picks whose entries showed
11011
+ * no vault is skipped and nothing is sent.
11012
+ * - Some vaults picked: the managed list names them. Saving it again
11013
+ * replaces it, so there is only ever one.
11014
+ * - None picked (vaults shown): the managed list names no vault, and the
11015
+ * rules must read back as an empty allow-list. Yieldseeker then keeps the
11016
+ * agent's money out of every vault, as Zyfai does with an empty pool list,
11017
+ * and the next Pools step reads "none". Only an agent that already exists
11018
+ * is written: one is never created just to hold "none".
11019
+ * - Every vault picked: the managed list is deleted, and no allow-list may
11020
+ * remain, so vaults Yieldseeker adds later are allowed too.
11021
+ * - A free-text allow-list we saved before the managed list existed is
11022
+ * deleted once the new state is written. A failed delete does not fail the
11023
+ * save; it is debug-logged, and the read-back decides.
11024
+ * - A read-back that differs puts the previous managed list back (or deletes
11025
+ * the one just created) and throws POOL_SELECTION_NOT_APPLIED. If putting
11026
+ * it back fails too, that is still the error thrown. An old free-text list
11027
+ * already deleted is not put back.
11028
+ * - An agent already holding the most active memories, none of them ours,
11029
+ * throws POOL_SELECTION_RULE_LIMIT before anything is written.
11030
+ *
11031
+ * Always Base, whichever chain the wallet is connected on.
11032
+ */
11033
+ async setPoolSelection(selection, state) {
11034
+ if (!state) {
11035
+ throw new OwneyError(
11036
+ "NOT_CONNECTED",
11037
+ "Connect a wallet before saving Yieldseeker pool picks.",
11038
+ void 0,
11039
+ this.id
11040
+ );
11041
+ }
11042
+ const byAsset = /* @__PURE__ */ new Map();
11043
+ for (const entry of selection.selections) {
11044
+ if (entry.chainId !== 8453) continue;
11045
+ this.assertAsset(entry.asset);
11046
+ const group = byAsset.get(entry.asset) ?? { picked: [], shown: [] };
11047
+ group.picked.push(...entry.pools);
11048
+ group.shown.push(...entry.availablePools);
11049
+ byAsset.set(entry.asset, group);
11050
+ }
11051
+ for (const [asset, group] of byAsset) {
11052
+ const picks = uniqueAddresses(group.picked);
11053
+ const shown = uniqueAddresses(group.shown);
11054
+ if (picks.length === 0 && shown.length === 0) continue;
11055
+ const picked = new Set(picks.map((address) => address.toLowerCase()));
11056
+ const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11057
+ await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11058
+ }
11059
+ }
11060
+ async savePoolPicks(state, asset, picks, everyVaultPicked) {
11061
+ const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11062
+ if (!context) {
11063
+ debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11064
+ return;
11065
+ }
11066
+ const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11067
+ const managed = active.find(isManagedVaultList);
11068
+ const legacy = active.filter(isLegacyPoolSelectionMemory);
11069
+ const writing = !everyVaultPicked;
11070
+ if (writing && !managed && active.length - legacy.length >= YIELDSEEKER_MAX_ACTIVE_MEMORIES) {
11071
+ throw new OwneyError(
11072
+ "POOL_SELECTION_RULE_LIMIT",
11073
+ `This Yieldseeker ${asset} agent already has ${active.length} active memories, the most it allows, so the pool selection could not be saved. Nothing was written.`,
11074
+ { asset, activeMemories: active.length, limit: YIELDSEEKER_MAX_ACTIVE_MEMORIES },
11075
+ this.id
11076
+ );
11077
+ }
11078
+ const content = writing ? await this.poolMemoryContent(asset, picks) : void 0;
11079
+ const change = { previous: managed, written: false };
11080
+ if (content === void 0) {
11081
+ if (managed) {
11082
+ await this.memoryRequest(state, context, `memories/${managed.agentMemoryId}/delete`, {
11083
+ method: "POST"
11084
+ });
11085
+ change.written = true;
11086
+ }
11087
+ } else {
11088
+ const answer = await this.memoryRequest(state, context, "memories", {
11089
+ method: "POST",
11090
+ body: { content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11091
+ });
11092
+ change.written = true;
11093
+ if (!managed && answer?.memory?.agentMemoryId) change.createdId = answer.memory.agentMemoryId;
11094
+ }
11095
+ await this.deleteLegacyPoolMemories(state, context, asset, legacy);
11096
+ let failure;
11097
+ try {
11098
+ const allowed = await this.readAllowList(state, context);
11099
+ const applied = content === void 0 ? allowed === void 0 : allowed !== void 0 && sameVaults(allowed, picks);
11100
+ if (!applied) failure = "ALLOW_LIST_MISMATCH";
11101
+ } catch {
11102
+ failure = "READ_BACK_FAILED";
11103
+ }
11104
+ if (!failure) return;
11105
+ const restored = await this.restorePoolMemory(state, context, change);
11106
+ throw new OwneyError(
11107
+ "POOL_SELECTION_NOT_APPLIED",
11108
+ `Yieldseeker did not apply the ${asset} pool selection (${failure}).${restored ? "" : " The previous selection could not be put back."} Nothing was funded.`,
11109
+ { asset, reason: failure, restored },
11110
+ this.id
11111
+ );
11112
+ }
11113
+ /**
11114
+ * Delete the free-text allow-lists we saved before the managed list existed.
11115
+ * Never throws: a list left behind is caught by the read-back. Logs no
11116
+ * sign-in token.
11117
+ */
11118
+ async deleteLegacyPoolMemories(state, context, asset, memories) {
11119
+ for (const memory of memories) {
11120
+ try {
11121
+ await this.memoryRequest(state, context, `memories/${memory.agentMemoryId}/delete`, {
11122
+ method: "POST"
11123
+ });
11124
+ } catch (error) {
11125
+ debugLog("yieldseeker:pools", `${asset}: an old pool memory could not be deleted`, {
11126
+ memoryId: memory.agentMemoryId,
11127
+ code: error instanceof OwneyError ? error.code : void 0,
11128
+ message: error instanceof Error ? error.message : void 0
11129
+ });
11130
+ }
11131
+ }
11132
+ }
11133
+ /**
11134
+ * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11135
+ * has no brackets. No picks names no vault.
11136
+ */
11137
+ async poolMemoryContent(asset, picks) {
11138
+ if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11139
+ const vaults = new Map(
11140
+ (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11141
+ );
11142
+ const entries = picks.map((pick) => {
11143
+ const vault = vaults.get(pick.toLowerCase());
11144
+ const address = vault?.address ?? pick;
11145
+ return vault?.name ? `${address} (${vault.name})` : address;
11146
+ });
11147
+ return `${YIELDSEEKER_POOL_MEMORY_PREFIX} ${entries.join(", ")}.`;
11148
+ }
11149
+ /** Undo a failed save of the managed list. Never throws: the caller reports the save's own failure. */
11150
+ async restorePoolMemory(state, context, change) {
11151
+ if (!change.written) return true;
11152
+ try {
11153
+ if (change.previous) {
11154
+ await this.memoryRequest(state, context, "memories", {
11155
+ method: "POST",
11156
+ body: { content: change.previous.content, managedRuleType: YIELDSEEKER_MANAGED_VAULT_RULE }
11157
+ });
11158
+ return true;
11159
+ }
11160
+ const ids = change.createdId ? [change.createdId] : (await this.listMemories(state, context)).filter((memory) => isActiveMemory(memory) && isManagedVaultList(memory)).map((memory) => memory.agentMemoryId);
11161
+ for (const id of ids) {
11162
+ await this.memoryRequest(state, context, `memories/${id}/delete`, { method: "POST" });
11163
+ }
11164
+ return true;
11165
+ } catch {
11166
+ return false;
11167
+ }
11168
+ }
11169
+ /**
11170
+ * What the user's Yieldseeker agents currently allow, as `SavedPoolSelection`
11171
+ * pairs: the allowed vault addresses under the provider each belongs to, for
11172
+ * the vaults a new agent can use. An agent with no allow-list adds nothing,
11173
+ * and no pairs at all means every shown vault is on. Reads never create an
11174
+ * agent, and always read Base. A read that fails throws, because "no
11175
+ * allow-list" would wrongly mean "everything".
11176
+ *
11177
+ * An allow-list naming none of the listed vaults (the saved "none", or vaults
11178
+ * Yieldseeker has since stopped listing) leaves the agent nowhere to go, so
11179
+ * it reports none chosen for its asset: a pair with empty `pools` for every
11180
+ * provider listing vaults for it. With no vault listed at all there is
11181
+ * nothing to name that by, and it throws: the rules still restrict the agent.
11182
+ *
11183
+ * `pairs` is accepted for the contract but does not trim the answer: cutting
11184
+ * a real allow-list down to the pairs asked about could leave none, and none
11185
+ * reads as every vault on.
11186
+ */
11187
+ async getPoolSelection(state, _chainId, params) {
11188
+ const byProvider = /* @__PURE__ */ new Map();
11189
+ for (const asset of new Set(params.assets)) {
11190
+ this.assertAsset(asset);
11191
+ const context = await this.findAgent(state, 8453, asset);
11192
+ if (!context) continue;
11193
+ const allowed = await this.readAllowList(state, context);
11194
+ if (allowed === void 0) continue;
11195
+ const options = await this.loadVaultOptions(asset);
11196
+ if (options.length === 0) {
11197
+ throw this.invalidResponse("pool selection", {
11198
+ reason: "vault-options lists no vault while an allow-list restricts the agent.",
11199
+ asset
11200
+ });
11201
+ }
11202
+ const vaults = new Map(options.map((vault) => [vault.address.toLowerCase(), vault]));
11203
+ const known = allowed.flatMap((address) => vaults.get(address.toLowerCase()) ?? []);
11204
+ if (known.length === 0) {
11205
+ for (const vault of options) {
11206
+ if (!byProvider.has(vault.provider)) byProvider.set(vault.provider, []);
11207
+ }
11208
+ continue;
11209
+ }
11210
+ for (const vault of known) {
11211
+ const pools = byProvider.get(vault.provider) ?? [];
11212
+ byProvider.set(vault.provider, uniqueAddresses([...pools, vault.address]));
11213
+ }
11214
+ }
11215
+ return {
11216
+ strategies: [],
11217
+ pairs: [...byProvider].map(([protocolId, pools]) => ({ protocolId, chainId: 8453, pools }))
11218
+ };
11219
+ }
11220
+ /**
11221
+ * The allow-list in the agent's rules: every `allowedVaultAddresses` on an
11222
+ * `ignored_vault` user rule. Undefined when no rule has one, which allows
11223
+ * every vault; an empty list allows none. A response that does not have the
11224
+ * expected shape throws rather than reading as no allow-list.
11225
+ */
11226
+ async readAllowList(state, context) {
11227
+ const rules = await this.memoryRequest(
11228
+ state,
11229
+ context,
11230
+ "memories/effective-rules"
11231
+ );
11232
+ if (!Array.isArray(rules?.userRules)) throw this.invalidResponse("effective rules");
11233
+ let allowed;
11234
+ for (const rule of rules.userRules) {
11235
+ if (rule?.ruleType !== "ignored_vault") continue;
11236
+ const list = rule.ruleConfig?.allowedVaultAddresses;
11237
+ if (list === void 0 || list === null) continue;
11238
+ if (!Array.isArray(list) || list.some((address) => typeof address !== "string")) {
11239
+ throw this.invalidResponse("effective rules");
11240
+ }
11241
+ allowed = [...allowed ?? [], ...list];
11242
+ }
11243
+ return allowed;
11244
+ }
11245
+ async listMemories(state, context) {
11246
+ const response = await this.memoryRequest(state, context, "memories");
11247
+ if (!Array.isArray(response?.memories)) throw this.invalidResponse("memories");
11248
+ return response.memories;
11249
+ }
11250
+ /** A memory call for an agent, on Base whichever chain the wallet is on. */
11251
+ async memoryRequest(state, context, suffix, options = {}) {
11252
+ try {
11253
+ return await this.providerRequest(state, 8453, this.agentPath(context, suffix), options);
11254
+ } catch (error) {
11255
+ if (error instanceof OwneyError) throw error;
11256
+ throw this.mapRequestFailure(error);
11257
+ }
11258
+ }
10619
11259
  userKey(state, chainId) {
10620
11260
  return `${state.walletAddress.toLowerCase()}:${chainId}`;
10621
11261
  }
@@ -10668,6 +11308,7 @@ var YieldseekerAgent = class {
10668
11308
  this.agentContexts.set(slot, context);
10669
11309
  this.pendingSlotInvalidations.delete(slot);
10670
11310
  this.missingSlots.delete(slot);
11311
+ this.closedSlots.delete(slot);
10671
11312
  }
10672
11313
  assertSession(generation, chainId, asset) {
10673
11314
  if (this.readGeneration !== generation) {
@@ -10779,8 +11420,10 @@ var YieldseekerAgent = class {
10779
11420
  * highest-priority set of `priorities` (index 0 first). Hinted agentIds are
10780
11421
  * resolved first and a hinted top-priority match ends the search; then other
10781
11422
  * listed agents, at most YIELDSEEKER_WALLET_MATCH_LIMIT wallets in total.
11423
+ * A candidate whose wallet shows it closed (deactivated) never ranks, and its
11424
+ * agentId is added to `closed`.
10782
11425
  */
10783
- async agentWithWallet(state, chainId, user, agents, asset, priorities, hints) {
11426
+ async agentWithWallet(state, chainId, user, agents, asset, priorities, hints, closed) {
10784
11427
  const fitting = /* @__PURE__ */ new Map();
10785
11428
  for (const agent of agents) {
10786
11429
  if (this.agentFits(agent, chainId, asset) && !fitting.has(agent.agentId)) fitting.set(agent.agentId, agent);
@@ -10802,6 +11445,10 @@ var YieldseekerAgent = class {
10802
11445
  failure ??= { error: result.reason };
10803
11446
  continue;
10804
11447
  }
11448
+ if (result.value.wallet.deactivatedDate) {
11449
+ closed?.add(result.value.agent.agentId);
11450
+ continue;
11451
+ }
10805
11452
  const wallet = result.value.wallet.walletAddress.toLowerCase();
10806
11453
  const rank = priorities.findIndex((wallets) => wallets.has(wallet));
10807
11454
  if (rank >= 0 && (!best || rank < best.rank)) best = { rank, agent: result.value.agent };
@@ -10816,32 +11463,213 @@ var YieldseekerAgent = class {
10816
11463
  }
10817
11464
  /**
10818
11465
  * chooseAgent, re-reading a cached list once (bypassing its cache) when the
10819
- * verified agent is missing. A slot still missing after that re-read is
10820
- * remembered for the list cache window, so later reads fail from the cached
10821
- * list without another re-read.
11466
+ * verified agent is missing. Still missing, Yieldseeker may have closed
11467
+ * (deactivated) it: the verified record's agent is reactivated and selected
11468
+ * from a fresh list, by the verified wallet only (never created). A slot
11469
+ * that still fails is remembered with its error for the list cache window,
11470
+ * so later reads fail without another re-read or reactivate. A slot
11471
+ * Yieldseeker will not reopen because of its active-agent limit throws
11472
+ * YIELDSEEKER_SLOT_UNAVAILABLE, here and for the rest of the session, with
11473
+ * no request.
10822
11474
  */
10823
11475
  async chooseAgentRefreshing(state, chainId, user, agents, accounts, asset) {
11476
+ this.throwIfSlotUnavailable(state, chainId, asset);
10824
11477
  try {
10825
11478
  return await this.chooseAgent(state, chainId, user, agents, accounts, asset);
10826
11479
  } catch (error) {
10827
11480
  if (!this.isAgentMissing(error)) throw error;
10828
11481
  const slot = this.slotKey(state, chainId, asset);
10829
- if (this.isSlotMissing(slot)) throw error;
11482
+ this.throwIfSlotMissing(slot);
10830
11483
  const generation = this.readGeneration;
10831
11484
  const fresh = await this.listAgents(state, chainId, user, true);
10832
11485
  this.assertSession(generation, chainId, asset);
11486
+ let missing;
10833
11487
  try {
10834
11488
  return await this.chooseAgent(state, chainId, user, fresh, accounts, asset);
10835
11489
  } catch (retryError) {
10836
- if (this.isAgentMissing(retryError) && this.readGeneration === generation) {
10837
- this.missingSlots.set(slot, Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS);
11490
+ if (!this.isAgentMissing(retryError)) throw retryError;
11491
+ missing = retryError;
11492
+ }
11493
+ const verified = this.slotAccounts(accounts, chainId, asset).find((account) => account.status === "verified");
11494
+ const agentId = verified?.providerAgentId;
11495
+ if (!verified || !agentId) {
11496
+ this.rememberMissingSlot(slot, generation, missing);
11497
+ throw missing;
11498
+ }
11499
+ this.throwIfSlotMissing(slot);
11500
+ let reopened;
11501
+ try {
11502
+ reopened = await this.reopenAgent(state, chainId, user, asset, agentId);
11503
+ this.assertSession(generation, chainId, asset);
11504
+ } catch (reopenError) {
11505
+ this.rememberMissingSlot(slot, generation, reopenError);
11506
+ throw reopenError;
11507
+ }
11508
+ try {
11509
+ const agent = await this.agentWithWallet(
11510
+ state,
11511
+ chainId,
11512
+ user,
11513
+ reopened,
11514
+ asset,
11515
+ [/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()])],
11516
+ [agentId]
11517
+ );
11518
+ if (agent) return agent;
11519
+ throw this.agentMissing(chainId, asset, agentId);
11520
+ } catch (reopenedError) {
11521
+ if (this.isAgentMissing(reopenedError)) this.rememberMissingSlot(slot, generation, reopenedError);
11522
+ throw reopenedError;
11523
+ }
11524
+ }
11525
+ }
11526
+ throwIfSlotUnavailable(state, chainId, asset) {
11527
+ const providerCode = this.unavailableSlots.get(this.slotKey(state, chainId, asset));
11528
+ if (providerCode !== void 0) throw this.slotUnavailable(chainId, asset, providerCode);
11529
+ }
11530
+ /**
11531
+ * Rethrow the error a slot's lookup failed with while the slot is still
11532
+ * marked, or for the session when Yieldseeker will never reopen its agent.
11533
+ * A remembered rate limit is rethrown with the time left on its marker as
11534
+ * its retry delay (`retryAfterSeconds`): no new attempt is made before then,
11535
+ * so a caller that waits it out retries once instead of every few seconds.
11536
+ */
11537
+ throwIfSlotMissing(slot) {
11538
+ const closed = this.closedSlots.get(slot);
11539
+ if (closed) throw closed;
11540
+ const missing = this.missingSlots.get(slot);
11541
+ if (!missing || missing.until <= Date.now()) return;
11542
+ const { error } = missing;
11543
+ if (!(error instanceof OwneyError) || rateLimitDelay(error) === void 0) throw error;
11544
+ const prefix = error.agentId ? `[${error.code}][agent:${error.agentId}] ` : `[${error.code}] `;
11545
+ const rethrown = new OwneyError(
11546
+ error.code,
11547
+ error.message.startsWith(prefix) ? error.message.slice(prefix.length) : error.message,
11548
+ { ...error.details, retryAfterSeconds: Math.ceil((missing.until - Date.now()) / 1e3) },
11549
+ error.agentId
11550
+ );
11551
+ this.rethrownSlotFailures.set(rethrown, error);
11552
+ throw rethrown;
11553
+ }
11554
+ /**
11555
+ * Remember a slot's failed lookup or reactivate for the list-cache window.
11556
+ * A sign-in failure is not remembered (the wallet's rejection,
11557
+ * AGENT_AUTH_FAILED, NOT_CONNECTED): it says nothing about the slot, and
11558
+ * remembered it would refuse the next sign-in, even one the user starts,
11559
+ * with no request for the whole window.
11560
+ */
11561
+ rememberMissingSlot(slot, generation, error) {
11562
+ if (this.readGeneration !== generation) return;
11563
+ if (isWalletRejection(error) || error instanceof OwneyError && (error.code === "AGENT_AUTH_FAILED" || error.code === "NOT_CONNECTED")) return;
11564
+ this.missingSlots.set(slot, { until: Date.now() + YIELDSEEKER_AGENT_LIST_CACHE_MS, error });
11565
+ }
11566
+ /**
11567
+ * Reactivate the slot's verified agent, then read the list bypassing its
11568
+ * cache, with a read sent after the reactivate answered. Concurrent lookups
11569
+ * of one slot share one reopen. Resolves to the fresh list. At the
11570
+ * active-agent limit the slot is recorded unavailable and this throws
11571
+ * YIELDSEEKER_SLOT_UNAVAILABLE.
11572
+ */
11573
+ reopenAgent(state, chainId, user, asset, agentId) {
11574
+ const slot = this.slotKey(state, chainId, asset);
11575
+ const pending = this.pendingReopens.get(slot);
11576
+ if (pending) return pending;
11577
+ const generation = this.readGeneration;
11578
+ const request2 = (async () => {
11579
+ const result = await this.reactivateSlot(state, chainId, user, asset, agentId);
11580
+ this.assertSession(generation, chainId, asset);
11581
+ if (result.outcome === "limit") throw this.slotUnavailable(chainId, asset, result.providerCode);
11582
+ this.forgetAgentWallet(agentId);
11583
+ this.missingSlots.delete(slot);
11584
+ await this.freshListReads.get(this.agentListKey(state, chainId))?.catch(() => void 0);
11585
+ this.assertSession(generation, chainId, asset);
11586
+ const fresh = await this.listAgents(state, chainId, user, true);
11587
+ this.assertSession(generation, chainId, asset);
11588
+ return fresh;
11589
+ })().finally(() => {
11590
+ if (this.pendingReopens.get(slot) === request2) this.pendingReopens.delete(slot);
11591
+ });
11592
+ this.pendingReopens.set(slot, request2);
11593
+ return request2;
11594
+ }
11595
+ /**
11596
+ * The one way to reactivate a slot's agent, for the slot lookup (reopenAgent)
11597
+ * and the pre-deposit check (assertAgentOpen), so a slot costs at most one
11598
+ * reactivate per list-cache window:
11599
+ * - a slot recorded unavailable (the limit) answers "limit" with no request;
11600
+ * - concurrent callers share one request;
11601
+ * - a failed reactivate (closed code, rate limit, timeout, 5xx...) is
11602
+ * remembered as the slot's failure for the list-cache window (missingSlots)
11603
+ * and rethrown to later callers with no request; a closed code
11604
+ * (closedSlots) for the session; a sign-in failure is not remembered;
11605
+ * - the limit is recorded in unavailableSlots only while the session is
11606
+ * unchanged, so a disconnect during the request is not undone by its late
11607
+ * answer.
11608
+ */
11609
+ async reactivateSlot(state, chainId, user, asset, agentId) {
11610
+ const slot = this.slotKey(state, chainId, asset);
11611
+ const limit = this.unavailableSlots.get(slot);
11612
+ if (limit !== void 0) return { outcome: "limit", providerCode: limit };
11613
+ const key2 = `${slot}:${agentId}`;
11614
+ const pending = this.pendingReactivates.get(key2);
11615
+ if (pending) return pending;
11616
+ this.throwIfSlotMissing(slot);
11617
+ const generation = this.readGeneration;
11618
+ const request2 = (async () => {
11619
+ try {
11620
+ const result = await this.reactivateAgent(state, chainId, user, asset, agentId);
11621
+ if (result.outcome === "limit" && this.readGeneration === generation) {
11622
+ this.unavailableSlots.set(slot, result.providerCode);
10838
11623
  }
10839
- throw retryError;
11624
+ return result;
11625
+ } catch (error) {
11626
+ if (this.readGeneration === generation && error instanceof OwneyError && error.code === "YIELDSEEKER_AGENT_CLOSED" && typeof error.details?.providerCode === "string" && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(error.details.providerCode)) {
11627
+ this.closedSlots.set(slot, error);
11628
+ }
11629
+ this.rememberMissingSlot(slot, generation, error);
11630
+ throw error;
11631
+ }
11632
+ })().finally(() => {
11633
+ if (this.pendingReactivates.get(key2) === request2) this.pendingReactivates.delete(key2);
11634
+ });
11635
+ this.pendingReactivates.set(key2, request2);
11636
+ return request2;
11637
+ }
11638
+ /**
11639
+ * Ask Yieldseeker to reopen a closed (deactivated) agent, with the user's
11640
+ * Yieldseeker sign-in. AGENT_NOT_DEACTIVATED (already open, e.g. reopened
11641
+ * by another tab) counts as reopened; the active-agent limit is an outcome,
11642
+ * not an error. An agent that cannot come back throws
11643
+ * YIELDSEEKER_AGENT_CLOSED; any other failure (rate limit, timeout, network,
11644
+ * 5xx, an unknown code) throws the mapped API error.
11645
+ */
11646
+ async reactivateAgent(state, chainId, user, asset, agentId) {
11647
+ try {
11648
+ await this.providerRequest(
11649
+ state,
11650
+ chainId,
11651
+ `/users/${user.userId}/agents/${encodeURIComponent(agentId)}/reactivate`,
11652
+ { method: "POST", body: {} }
11653
+ );
11654
+ return { outcome: "reopened" };
11655
+ } catch (error) {
11656
+ if (error instanceof OwneyError) throw error;
11657
+ const providerCode = error instanceof YieldseekerApiError ? error.providerCode : void 0;
11658
+ if (providerCode === "AGENT_NOT_DEACTIVATED") return { outcome: "reopened" };
11659
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_LIMIT_CODES.has(providerCode)) {
11660
+ return { outcome: "limit", providerCode };
11661
+ }
11662
+ if (providerCode !== void 0 && YIELDSEEKER_REACTIVATE_CLOSED_CODES.has(providerCode)) {
11663
+ throw this.agentClosed(chainId, asset, agentId, providerCode);
10840
11664
  }
11665
+ throw this.mapRequestFailure(error);
10841
11666
  }
10842
11667
  }
10843
- isSlotMissing(slot) {
10844
- return (this.missingSlots.get(slot) ?? 0) > Date.now();
11668
+ /** Drop the cached and in-flight wallet contexts of one agent, in every slot. */
11669
+ forgetAgentWallet(agentId) {
11670
+ const ofAgent = (key2) => key2.split(":").slice(3).join(":") === agentId;
11671
+ for (const key2 of [...this.walletContexts.keys()]) if (ofAgent(key2)) this.walletContexts.delete(key2);
11672
+ for (const key2 of [...this.pendingWalletContexts.keys()]) if (ofAgent(key2)) this.pendingWalletContexts.delete(key2);
10845
11673
  }
10846
11674
  /**
10847
11675
  * The agent that serves deposits and withdrawals for a slot (Ruling 23):
@@ -10849,7 +11677,8 @@ var YieldseekerAgent = class {
10849
11677
  * whatever its name; the stored agentId is only a hint;
10850
11678
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
10851
11679
  * 3. else the fitting agent named "owney" (first use, migration, or a
10852
- * verified wallet that is not a fitting listed agent);
11680
+ * verified wallet that is not a fitting listed agent), unless step 1/2
11681
+ * read its wallet and it is closed (deactivated): that agent is not listed;
10853
11682
  * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
10854
11683
  * create); without one, undefined (the caller may create).
10855
11684
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
@@ -10860,6 +11689,7 @@ var YieldseekerAgent = class {
10860
11689
  const slot = this.slotAccounts(accounts, chainId, asset);
10861
11690
  const verified = slot.find((account) => account.status === "verified");
10862
11691
  const superseded = slot.filter((account) => account.status === "superseded");
11692
+ const closed = /* @__PURE__ */ new Set();
10863
11693
  if (verified || superseded.length) {
10864
11694
  const priorities = [];
10865
11695
  if (verified) priorities.push(/* @__PURE__ */ new Set([verified.agentWallet.toLowerCase()]));
@@ -10873,11 +11703,12 @@ var YieldseekerAgent = class {
10873
11703
  agents,
10874
11704
  asset,
10875
11705
  priorities,
10876
- [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)]
11706
+ [verified?.providerAgentId, ...superseded.map((account) => account.providerAgentId)],
11707
+ closed
10877
11708
  );
10878
11709
  if (match) return match;
10879
11710
  }
10880
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset));
11711
+ const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
10881
11712
  if (named) return named;
10882
11713
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
10883
11714
  return void 0;
@@ -10893,6 +11724,39 @@ var YieldseekerAgent = class {
10893
11724
  this.id
10894
11725
  );
10895
11726
  }
11727
+ slotUnavailable(chainId, asset, providerCode) {
11728
+ return new OwneyError(
11729
+ "YIELDSEEKER_SLOT_UNAVAILABLE",
11730
+ `Yieldseeker has no ${asset} agent for this account this session: it will not reopen the closed agent (${providerCode}).`,
11731
+ { rpcSource: "agent-api", chainId, asset, providerCode },
11732
+ this.id
11733
+ );
11734
+ }
11735
+ /** The slot has no usable agent: missing, at Yieldseeker's agent limit, or closed for good. */
11736
+ isSlotEmpty(error) {
11737
+ return error instanceof OwneyError && (error.code === "YIELDSEEKER_AGENT_MISSING" || error.code === "YIELDSEEKER_SLOT_UNAVAILABLE" || error.code === "YIELDSEEKER_AGENT_CLOSED");
11738
+ }
11739
+ /**
11740
+ * The slot's lookup failed through the missing-agent / reopen path and was
11741
+ * remembered with this very error, even a transient one (429, 5xx, timeout),
11742
+ * or with the copy of it a remembered rate limit is rethrown as. Compares
11743
+ * the remembered error, not its expiry, so it holds however long the rest
11744
+ * of the read takes.
11745
+ */
11746
+ isMarkedSlotFailure(slot, error) {
11747
+ const marker = this.missingSlots.get(slot);
11748
+ if (!marker) return false;
11749
+ return marker.error === error || typeof error === "object" && error !== null && this.rethrownSlotFailures.get(error) === marker.error;
11750
+ }
11751
+ /** providerCode is absent when Yieldseeker named none (the agent stayed closed after a reopen). */
11752
+ agentClosed(chainId, asset, agentId, providerCode, extra) {
11753
+ return new OwneyError(
11754
+ "YIELDSEEKER_AGENT_CLOSED",
11755
+ `Yieldseeker closed the ${asset} agent for this account and it cannot be reopened${providerCode ? ` (${providerCode})` : ""}.`,
11756
+ { rpcSource: "agent-api", chainId, asset, agentId, ...providerCode ? { providerCode } : {}, ...extra },
11757
+ this.id
11758
+ );
11759
+ }
10896
11760
  /**
10897
11761
  * Fire-and-forget: record which agent serves this slot. Never awaited on the
10898
11762
  * funds path and never throws; once per agent wallet and deployment state
@@ -10982,7 +11846,7 @@ var YieldseekerAgent = class {
10982
11846
  } catch (error) {
10983
11847
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
10984
11848
  if (error instanceof OwneyError) throw error;
10985
- throw this.mapApiError(error);
11849
+ throw this.mapRequestFailure(error);
10986
11850
  }
10987
11851
  let created;
10988
11852
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
@@ -11003,7 +11867,7 @@ var YieldseekerAgent = class {
11003
11867
  } catch (createError) {
11004
11868
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
11005
11869
  if (canRetry) continue;
11006
- throw this.mapApiError(createError);
11870
+ throw this.mapRequestFailure(createError);
11007
11871
  }
11008
11872
  }
11009
11873
  user = created?.user ?? null;
@@ -11060,6 +11924,7 @@ var YieldseekerAgent = class {
11060
11924
  return context;
11061
11925
  }
11062
11926
  async resolveAgent(state, chainId, asset, createIfMissing) {
11927
+ this.throwIfSlotUnavailable(state, chainId, asset);
11063
11928
  const generation = this.readGeneration;
11064
11929
  const accountsRead = this.agentAccounts(state, chainId);
11065
11930
  const user = await this.resolveUser(state, chainId);
@@ -11102,7 +11967,7 @@ var YieldseekerAgent = class {
11102
11967
  );
11103
11968
  } catch (error) {
11104
11969
  const conflict = error instanceof YieldseekerApiError && error.status === 409 && error.routing && YIELDSEEKER_CREATE_CONFLICT_CODES.has(error.routing.code) ? error.routing : void 0;
11105
- if (!conflict) throw this.mapApiError(error);
11970
+ if (!conflict) throw this.mapRequestFailure(error);
11106
11971
  this.assertSession(generation, chainId, asset);
11107
11972
  return this.adoptConflictingAgent(
11108
11973
  state,
@@ -11195,10 +12060,11 @@ var YieldseekerAgent = class {
11195
12060
  const agent = await this.chooseAgentRefreshing(state, chainId, user, agents, accounts, asset);
11196
12061
  if (agent) selected.set(asset, agent);
11197
12062
  } catch (error) {
11198
- if (assetFilter || !this.isAgentMissing(error)) throw error;
12063
+ if (assetFilter) throw error;
12064
+ if (!this.isSlotEmpty(error) && !this.isMarkedSlotFailure(this.slotKey(state, chainId, asset), error)) throw error;
11199
12065
  missing.push(error);
11200
12066
  missingAssets?.add(asset);
11201
- console.warn(`[owney-sdk] Yieldseeker ${asset} agent is missing:`, error);
12067
+ console.warn(`[owney-sdk] Yieldseeker ${asset} agent is unavailable:`, error);
11202
12068
  }
11203
12069
  }));
11204
12070
  this.assertSession(generation, chainId);
@@ -11833,6 +12699,7 @@ var YieldseekerAgent = class {
11833
12699
  try {
11834
12700
  return await this.providerRequest(state, chainId, path, options);
11835
12701
  } catch (error) {
12702
+ if (isWalletRejection(error)) throw error;
11836
12703
  const mapped = this.mapApiError(error);
11837
12704
  const delay = read2 ? rateLimitDelay(mapped) : void 0;
11838
12705
  if (delay !== void 0 && this.readGeneration === generation) {
@@ -11887,6 +12754,16 @@ var YieldseekerAgent = class {
11887
12754
  }
11888
12755
  }
11889
12756
  }
12757
+ /**
12758
+ * mapApiError for a request that may have opened the Yieldseeker sign-in
12759
+ * prompt (providerRequest signs when no sign-in is saved, and again when
12760
+ * Yieldseeker refuses one). The wallet's rejection, the user cancelling that
12761
+ * prompt, is returned unchanged: the client and the app must see the user's
12762
+ * cancel (no further prompt, no retry), never a provider failure.
12763
+ */
12764
+ mapRequestFailure(error) {
12765
+ return isWalletRejection(error) ? error : this.mapApiError(error);
12766
+ }
11890
12767
  mapApiError(error) {
11891
12768
  if (!(error instanceof YieldseekerApiError)) {
11892
12769
  return new OwneyError(
@@ -12477,6 +13354,8 @@ var FALLBACK_WRAP_GAS = 50000n;
12477
13354
  var APPROVE_GAS = 60000n;
12478
13355
  var GAS_SAFETY = 2n;
12479
13356
  var MIN_WALLET_GAS_PRICE = 3000000000n;
13357
+ var WRAP_WATCH_INTERVAL_MS = 4e3;
13358
+ var WRAP_PROMPT_TIMEOUT_MS = 5 * 60 * 1e3;
12480
13359
  async function wrapNative(deps, options) {
12481
13360
  const { chainId, wrapper, nativeSymbol, requested } = options;
12482
13361
  const balance = await deps.readNativeBalance();
@@ -12534,16 +13413,90 @@ async function wrapNative(deps, options) {
12534
13413
  }
12535
13414
  );
12536
13415
  }
13416
+ let baseline;
13417
+ if (deps.readWrappedBalance) {
13418
+ try {
13419
+ baseline = await deps.readWrappedBalance();
13420
+ } catch (error) {
13421
+ debugLog("owney-sdk", "wrap: balance read failed, not watching", {
13422
+ message: error instanceof Error ? error.message : String(error)
13423
+ });
13424
+ }
13425
+ }
12537
13426
  await deps.ensureChain(chainId);
12538
13427
  debugLog("owney-sdk", "wrap: sending deposit()", {
12539
13428
  wrapper,
12540
13429
  value: wrapped.toString()
12541
13430
  });
12542
- const txHash = await deps.sendTransaction(
12543
- { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
12544
- options.onSubmitted
12545
- );
12546
- return { wrapped, txHash };
13431
+ let notified = false;
13432
+ const notify2 = (hash2) => {
13433
+ if (notified) return;
13434
+ notified = true;
13435
+ options.onSubmitted?.(hash2);
13436
+ };
13437
+ const outcome = await new Promise((resolve, reject) => {
13438
+ let done = false;
13439
+ let timer;
13440
+ const finish = (settle) => {
13441
+ if (done) return;
13442
+ done = true;
13443
+ clearTimeout(timer);
13444
+ settle();
13445
+ };
13446
+ timer = setTimeout(
13447
+ () => finish(
13448
+ () => reject(
13449
+ new OwneyError(
13450
+ "SWAP_WALLET_PROMPT_TIMEOUT",
13451
+ // Hedged on purpose: a wallet that never answered may still have
13452
+ // sent it, and wrapping again would wrap twice.
13453
+ `Your wallet didn't answer the request to wrap your ${nativeSymbol}. Check your wallet before trying again \u2014 if the wrap went through, your funds are there as wrapped ${nativeSymbol}.`,
13454
+ { chainId, prompt: "wrap", timeoutMs: WRAP_PROMPT_TIMEOUT_MS }
13455
+ )
13456
+ )
13457
+ ),
13458
+ WRAP_PROMPT_TIMEOUT_MS
13459
+ );
13460
+ deps.sendTransaction(
13461
+ { to: wrapper, data: WRAP_SELECTOR, value: wrapped.toString() },
13462
+ (hash2) => {
13463
+ clearTimeout(timer);
13464
+ notify2(hash2);
13465
+ }
13466
+ ).then(
13467
+ (txHash) => finish(() => resolve({ txHash })),
13468
+ (error) => finish(() => reject(error))
13469
+ );
13470
+ if (baseline !== void 0 && deps.readWrappedBalance) {
13471
+ const read2 = deps.readWrappedBalance;
13472
+ const target = baseline + wrapped;
13473
+ const sleep4 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
13474
+ void (async () => {
13475
+ while (!done) {
13476
+ await sleep4(WRAP_WATCH_INTERVAL_MS);
13477
+ if (done) return;
13478
+ try {
13479
+ if (await read2() >= target) {
13480
+ debugLog(
13481
+ "owney-sdk",
13482
+ "wrap: landed on chain before the wallet answered"
13483
+ );
13484
+ finish(() => {
13485
+ notify2();
13486
+ resolve({});
13487
+ });
13488
+ return;
13489
+ }
13490
+ } catch {
13491
+ }
13492
+ }
13493
+ })();
13494
+ }
13495
+ });
13496
+ return {
13497
+ wrapped,
13498
+ ...outcome.txHash ? { txHash: outcome.txHash } : {}
13499
+ };
12547
13500
  }
12548
13501
  function requireWrapper(quote) {
12549
13502
  const wrapper = quote.wrappedNative;
@@ -14101,9 +15054,40 @@ function aggregateApyHistory(agentApys) {
14101
15054
  const total = points.reduce((sum, p) => sum + p.historicalBalance.amount, 0);
14102
15055
  if (total <= 0 || !Number.isFinite(total)) return [];
14103
15056
  const apy = points.reduce((sum, p) => sum + p.apy * (p.historicalBalance.amount / total), 0);
14104
- return Number.isFinite(apy) ? [{ date, apy }] : [];
15057
+ if (!Number.isFinite(apy)) return [];
15058
+ const incentives = aggregateIncentives(points, total);
15059
+ return [{ date, apy, ...incentives.length > 0 ? { incentives } : {} }];
14105
15060
  });
14106
15061
  }
15062
+ function incentiveKey(incentive) {
15063
+ return JSON.stringify([
15064
+ incentive.source,
15065
+ incentive.agentId,
15066
+ incentive.opportunityId,
15067
+ [...incentive.campaignIds].sort()
15068
+ ]);
15069
+ }
15070
+ function aggregateIncentives(points, totalBalance) {
15071
+ const byProgram = /* @__PURE__ */ new Map();
15072
+ for (const point of points) {
15073
+ const weight = point.historicalBalance.amount / totalBalance;
15074
+ for (const incentive of point.incentives ?? []) {
15075
+ if (!Number.isFinite(incentive.apr) || !Number.isFinite(incentive.apyContribution)) continue;
15076
+ const key2 = incentiveKey(incentive);
15077
+ const existing = byProgram.get(key2);
15078
+ if (existing) {
15079
+ existing.apyContribution += incentive.apyContribution * weight;
15080
+ } else {
15081
+ byProgram.set(key2, {
15082
+ ...incentive,
15083
+ campaignIds: [...incentive.campaignIds],
15084
+ apyContribution: incentive.apyContribution * weight
15085
+ });
15086
+ }
15087
+ }
15088
+ }
15089
+ return [...byProgram.values()];
15090
+ }
14107
15091
  function aggregateApyByChainAndAsset(agentApys, agentBalances) {
14108
15092
  const sums = {};
14109
15093
  const weights = {};
@@ -14915,6 +15899,123 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
14915
15899
  }
14916
15900
  }
14917
15901
 
15902
+ // src/lib/walletconnect-switch.ts
15903
+ var WALLET_SWITCH_TIMEOUT_MS = 12e4;
15904
+ var HOLD_CHAIN_MS = 15e3;
15905
+ var MAX_RESENDS = 2;
15906
+ var holds = /* @__PURE__ */ new Map();
15907
+ function parseChainId(raw2) {
15908
+ if (typeof raw2 === "number") return raw2;
15909
+ if (typeof raw2 !== "string") return void 0;
15910
+ const ref = raw2.split(":").pop() ?? raw2;
15911
+ const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
15912
+ return Number.isFinite(id) ? id : void 0;
15913
+ }
15914
+ function walletConnectCore(provider) {
15915
+ const p = provider;
15916
+ const core = p?.signer ?? p;
15917
+ if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
15918
+ return null;
15919
+ }
15920
+ const peer = core.session.peer?.metadata?.name ?? "";
15921
+ if (!/metamask/i.test(peer)) return null;
15922
+ return core;
15923
+ }
15924
+ async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
15925
+ const core = walletConnectCore(provider);
15926
+ if (!core) return false;
15927
+ holds.get(core.session.topic)?.();
15928
+ await requestSwitch(core, provider, chainId, timeoutMs);
15929
+ holdChain(core, provider, chainId);
15930
+ return true;
15931
+ }
15932
+ async function requestSwitch(core, provider, chainId, timeoutMs) {
15933
+ const current = Number(
15934
+ await provider.request({ method: "eth_chainId" })
15935
+ );
15936
+ const hexChainId = `0x${chainId.toString(16)}`;
15937
+ let timer;
15938
+ try {
15939
+ await Promise.race([
15940
+ core.client.request({
15941
+ topic: core.session.topic,
15942
+ chainId: `eip155:${current}`,
15943
+ request: {
15944
+ method: "wallet_switchEthereumChain",
15945
+ params: [{ chainId: hexChainId }]
15946
+ }
15947
+ }),
15948
+ new Promise((_, reject) => {
15949
+ timer = setTimeout(
15950
+ () => reject(
15951
+ new Error("The wallet did not answer the network switch in time")
15952
+ ),
15953
+ timeoutMs
15954
+ );
15955
+ })
15956
+ ]);
15957
+ } finally {
15958
+ clearTimeout(timer);
15959
+ }
15960
+ try {
15961
+ core.setDefaultChain(`eip155:${chainId}`);
15962
+ } catch {
15963
+ }
15964
+ }
15965
+ function holdChain(core, provider, chainId) {
15966
+ if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
15967
+ return;
15968
+ }
15969
+ let resends = 0;
15970
+ const listener = (raw2) => {
15971
+ const reported = parseChainId(raw2);
15972
+ debugLog("wc-switch", "wallet reported chain", {
15973
+ reported,
15974
+ holding: chainId,
15975
+ resends
15976
+ });
15977
+ if (reported === void 0 || reported === chainId) return;
15978
+ if (resends >= MAX_RESENDS) return;
15979
+ resends += 1;
15980
+ void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
15981
+ (error) => debugLog("wc-switch", "re-switch failed", {
15982
+ error: error instanceof Error ? error.message : String(error)
15983
+ })
15984
+ );
15985
+ };
15986
+ const release = () => {
15987
+ clearTimeout(timer);
15988
+ core.removeListener?.("chainChanged", listener);
15989
+ if (holds.get(core.session.topic) === release) {
15990
+ holds.delete(core.session.topic);
15991
+ }
15992
+ };
15993
+ const timer = setTimeout(release, HOLD_CHAIN_MS);
15994
+ core.on("chainChanged", listener);
15995
+ holds.set(core.session.topic, release);
15996
+ }
15997
+ function withWalletConnectSwitch(provider) {
15998
+ if (!walletConnectCore(provider)) return provider;
15999
+ const target = provider;
16000
+ const request2 = async (args) => {
16001
+ if (args?.method !== "wallet_switchEthereumChain") {
16002
+ return target.request(args);
16003
+ }
16004
+ const [param] = args.params ?? [];
16005
+ const chainId = Number.parseInt(param?.chainId ?? "", 16);
16006
+ if (!Number.isFinite(chainId)) return target.request(args);
16007
+ await switchWalletConnectChain(target, chainId);
16008
+ return null;
16009
+ };
16010
+ return new Proxy(target, {
16011
+ get(obj, prop) {
16012
+ if (prop === "request") return request2;
16013
+ const value = Reflect.get(obj, prop, obj);
16014
+ return typeof value === "function" ? value.bind(obj) : value;
16015
+ }
16016
+ });
16017
+ }
16018
+
14918
16019
  // src/lib/sponsored-calls-deposit.ts
14919
16020
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
14920
16021
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -15185,6 +16286,14 @@ var OwneySDK = class {
15185
16286
  * withdraw, but they are excluded from new deposits / activations.
15186
16287
  */
15187
16288
  disabledAgents = /* @__PURE__ */ new Set();
16289
+ /**
16290
+ * Agents whose sign-in the user cancelled this session (the wallet rejected
16291
+ * the prompt), keyed by chain. Until the app ends the session they are read
16292
+ * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
16293
+ * the user cancelled. A later successful activation of the agent removes
16294
+ * it, and `disconnect()` or a different wallet's `connect()` clears the map.
16295
+ */
16296
+ declinedSignIns = /* @__PURE__ */ new Map();
15188
16297
  state = null;
15189
16298
  connectionRevision = 0;
15190
16299
  disconnectingAgents = null;
@@ -15220,6 +16329,8 @@ var OwneySDK = class {
15220
16329
  * session started: true when it armed the refresh, false when its deadline
15221
16330
  * had passed (it only dropped the cache and forced one snapshot read). */
15222
16331
  recoveredFundingReads = /* @__PURE__ */ new Map();
16332
+ /** Confirmed deposits already announced to their agent (`depositConfirmed`), bounded. */
16333
+ announcedDeposits = /* @__PURE__ */ new Set();
15223
16334
  fundingBalanceChecks = /* @__PURE__ */ new WeakMap();
15224
16335
  activationChecks = /* @__PURE__ */ new Map();
15225
16336
  // Protect the SDK entry point as well as the mini-app hook. This owns only
@@ -15475,10 +16586,15 @@ var OwneySDK = class {
15475
16586
  }
15476
16587
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
15477
16588
  this.clearConnectionState();
16589
+ if (replacingOwner) this.declinedSignIns.clear();
15478
16590
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
15479
16591
  if (revision !== this.connectionRevision)
15480
16592
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
15481
- this.state = { provider, walletAddress, chainId: null };
16593
+ this.state = {
16594
+ provider: withWalletConnectSwitch(provider),
16595
+ walletAddress,
16596
+ chainId: null
16597
+ };
15482
16598
  }
15483
16599
  /**
15484
16600
  * Disconnect from all agents and clear connection state.
@@ -15487,6 +16603,7 @@ var OwneySDK = class {
15487
16603
  async disconnect() {
15488
16604
  ++this.connectionRevision;
15489
16605
  this.clearConnectionState();
16606
+ this.declinedSignIns.clear();
15490
16607
  await this.disconnectAgents();
15491
16608
  }
15492
16609
  clearConnectionState() {
@@ -15516,6 +16633,44 @@ var OwneySDK = class {
15516
16633
  isAgentDisabled(agentId) {
15517
16634
  return this.disabledAgents.has(agentId);
15518
16635
  }
16636
+ /**
16637
+ * True when `id` takes no new deposits on this chain and asset this
16638
+ * session: its adapter reports no agent for the slot.
16639
+ */
16640
+ isAgentUnavailable(id, chainId, asset) {
16641
+ if (asset === void 0) return false;
16642
+ return this.state !== null && this.agents.get(id)?.isSlotUnavailable?.(this.state, chainId, asset) === true;
16643
+ }
16644
+ /**
16645
+ * The agents that take no new deposits on this chain and asset this
16646
+ * session, so the app can show them as unavailable: each agent whose
16647
+ * provider has no agent for this slot. They stay withdrawable.
16648
+ */
16649
+ getUnavailableAgentIds(chainId, asset) {
16650
+ return [...this.agents.keys()].filter((id) => this.isAgentUnavailable(id, chainId, asset));
16651
+ }
16652
+ /**
16653
+ * The adapter reports no agent for this chain and asset this session (see
16654
+ * `IAgent.isSlotUnavailable`): there is nothing there to withdraw, so a
16655
+ * withdrawal without an explicit agent leaves it out instead of failing its
16656
+ * leg.
16657
+ */
16658
+ hasNoAgentForSlot(agent, state, chainId, asset) {
16659
+ return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
16660
+ }
16661
+ /**
16662
+ * The state an agent's reads use. An agent whose sign-in the user cancelled
16663
+ * on the connection chain this session is read from a saved sign-in only,
16664
+ * as `offChainPortfolioAgents` reads: a read that would need a wallet
16665
+ * prompt fails for that agent instead of reopening the prompt the user
16666
+ * cancelled. A later successful activation of the agent, or `disconnect()`,
16667
+ * lifts it.
16668
+ */
16669
+ readStateFor(agentId, state) {
16670
+ const chainId = state.chainId;
16671
+ if (state.promptless === true || chainId === null) return state;
16672
+ return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
16673
+ }
15519
16674
  /**
15520
16675
  * Check if the SDK has an active connection state.
15521
16676
  * @returns `true` if `connect()` has been called and `disconnect()` has not
@@ -15732,10 +16887,14 @@ var OwneySDK = class {
15732
16887
  * connection chain, then the off-chain ones on their own chain. */
15733
16888
  portfolioReads(state, chainId) {
15734
16889
  return [
15735
- ...[...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })),
15736
- ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0] }))
16890
+ ...this.activeReads(state, chainId),
16891
+ ...this.offChainPortfolioAgents(state).map(({ agent, state: readState, chainIds }) => ({ id: agent.id, agent, state: readState, chainId: chainIds[0], offChain: true }))
15737
16892
  ];
15738
16893
  }
16894
+ /** The active agents, each with the state its reads use (`readStateFor`). */
16895
+ activeReads(state, chainId) {
16896
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
16897
+ }
15739
16898
  /**
15740
16899
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
15741
16900
  * throws — it degrades to null — so this cannot break activation.
@@ -15859,7 +17018,7 @@ var OwneySDK = class {
15859
17018
  */
15860
17019
  async getAvailableAgents(options = {}) {
15861
17020
  await this.ensureAgentsInitialized();
15862
- const { chainId, asset, includeDisabled = false } = options;
17021
+ const { chainId, asset, includeDisabled = false, includeUnavailable = false } = options;
15863
17022
  const available = [];
15864
17023
  for (const [id, agent] of this.agents) {
15865
17024
  const isEnabled = !this.isAgentDisabled(id);
@@ -15875,6 +17034,9 @@ var OwneySDK = class {
15875
17034
  continue;
15876
17035
  }
15877
17036
  }
17037
+ if (chainId !== void 0 && !includeUnavailable && !includeDisabled && this.isAgentUnavailable(id, chainId, asset)) {
17038
+ continue;
17039
+ }
15878
17040
  available.push({
15879
17041
  id,
15880
17042
  isEnabled,
@@ -15894,8 +17056,17 @@ var OwneySDK = class {
15894
17056
  * that support the given chainId (incompatible agents are silently skipped).
15895
17057
  * If provided, ALL specified agents must support the chainId or the call
15896
17058
  * throws before activating any agent.
17059
+ * @param options - Optional. `asset` limits setup to that asset;
17060
+ * `onAgentsSelected` fires once reads can start.
17061
+ * @throws Activation stops at the first agent that fails, and the caller
17062
+ * should end the session. `AGENT_ACTIVATION_PARTIAL_FAILURE` when an
17063
+ * earlier agent activated; `walletRejected` in its details means the user
17064
+ * rejected a signature. `AGENT_ACTIVATION_BLOCKED` when the agent can
17065
+ * never be readied (`details.permanent`). Otherwise the agent's own error
17066
+ * is thrown as is. Until it signs in, an agent whose signature the user
17067
+ * rejected is read from a saved sign-in only and opens no prompt.
15897
17068
  */
15898
- async activateAgent(chainId, agentId, asset) {
17069
+ async activateAgent(chainId, agentId, options = {}) {
15899
17070
  const state = this.requireState();
15900
17071
  await this.ensureAgentsInitialized();
15901
17072
  this.assertActivationSession(state);
@@ -15932,7 +17103,8 @@ var OwneySDK = class {
15932
17103
  this.activeAgents.add(id);
15933
17104
  }
15934
17105
  state.chainId = chainId;
15935
- await this.activateAgentsInTurn(agents, state, chainId, asset);
17106
+ options.onAgentsSelected?.();
17107
+ await this.activateAgentsInTurn(agents, state, chainId, options.asset);
15936
17108
  return;
15937
17109
  }
15938
17110
  const compatible = [...this.agents.values()].filter(
@@ -15950,10 +17122,11 @@ var OwneySDK = class {
15950
17122
  this.activeAgents.add(agent.id);
15951
17123
  }
15952
17124
  state.chainId = chainId;
17125
+ options.onAgentsSelected?.();
15953
17126
  const enabledCompatible = compatible.filter(
15954
17127
  (agent) => !this.isAgentDisabled(agent.id)
15955
17128
  );
15956
- await this.activateAgentsInTurn(enabledCompatible, state, chainId, asset);
17129
+ await this.activateAgentsInTurn(enabledCompatible, state, chainId, options.asset);
15957
17130
  }
15958
17131
  assertActivationSession(state) {
15959
17132
  if (this.state !== state) {
@@ -15973,12 +17146,17 @@ var OwneySDK = class {
15973
17146
  * Serializing costs no real wall-clock: the user can only approve one prompt
15974
17147
  * at a time anyway.
15975
17148
  *
15976
- * Stop at the first failure so a canceled sign-in does not open another
15977
- * agent's wallet prompt. Report any earlier successes for diagnostics; the
15978
- * app discards the session when the complete sign-in does not succeed.
17149
+ * Stop at the first failure (2026-11-06): a connect needs every agent, so
17150
+ * no later agent's wallet prompt opens for a sign-in that already failed.
17151
+ * When an earlier agent activated, the partial failure reports it, and
17152
+ * `walletRejected` tells the app the user canceled; the app ends the
17153
+ * session either way. When none activated, the agent's own error is thrown.
17154
+ * A failure the provider marks `permanent` is thrown as
17155
+ * `AGENT_ACTIVATION_BLOCKED`.
15979
17156
  */
15980
17157
  async activateAgentsInTurn(agents, state, chainId, asset) {
15981
17158
  let firstError = null;
17159
+ let walletRejected = false;
15982
17160
  const activatedAgentIds = [];
15983
17161
  const failedAgents = [];
15984
17162
  for (const agent of agents) {
@@ -15989,6 +17167,7 @@ var OwneySDK = class {
15989
17167
  await this.applyOrgPolicyTo(agent, state, chainId);
15990
17168
  this.assertActivationSession(state);
15991
17169
  activatedAgentIds.push(agent.id);
17170
+ this.declinedSignIns.get(chainId)?.delete(agent.id);
15992
17171
  } catch (error) {
15993
17172
  this.assertActivationSession(state);
15994
17173
  const message = error !== null && typeof error === "object" && "message" in error && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "No activation error message was returned.";
@@ -15998,15 +17177,28 @@ var OwneySDK = class {
15998
17177
  message,
15999
17178
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
16000
17179
  });
16001
- if (firstError === null) {
16002
- firstError = error;
16003
- } else {
16004
- console.error(`activateAgent(${agent.id}) failed:`, error);
17180
+ firstError = error;
17181
+ if (this.isUserRejectedWithdrawal(error)) {
17182
+ walletRejected = true;
17183
+ const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
17184
+ declined.add(agent.id);
17185
+ this.declinedSignIns.set(chainId, declined);
16005
17186
  }
16006
17187
  break;
16007
17188
  }
16008
17189
  }
16009
17190
  if (firstError === null) return;
17191
+ if (failedAgents.some(({ details }) => details?.permanent === true)) {
17192
+ throw new OwneyError(
17193
+ "AGENT_ACTIVATION_BLOCKED",
17194
+ failedAgents.map(({ agentId, message }) => `${this.formatAgentName(agentId)} activation failed: ${message}`).join(" "),
17195
+ {
17196
+ activatedAgentIds,
17197
+ failedAgentIds: failedAgents.map(({ agentId }) => agentId),
17198
+ failures: failedAgents
17199
+ }
17200
+ );
17201
+ }
16010
17202
  if (activatedAgentIds.length === 0) throw firstError;
16011
17203
  const failedAgentIds = failedAgents.map(({ agentId }) => agentId);
16012
17204
  const activeNames = activatedAgentIds.map(this.formatAgentName).join(", ");
@@ -16016,7 +17208,7 @@ var OwneySDK = class {
16016
17208
  throw new OwneyError(
16017
17209
  "AGENT_ACTIVATION_PARTIAL_FAILURE",
16018
17210
  `${activeNames} activated. ${failureMessages}`,
16019
- { activatedAgentIds, failedAgentIds, failures: failedAgents }
17211
+ { activatedAgentIds, failedAgentIds, failures: failedAgents, ...walletRejected ? { walletRejected: true } : {} }
16020
17212
  );
16021
17213
  }
16022
17214
  /**
@@ -16031,6 +17223,10 @@ var OwneySDK = class {
16031
17223
  * all shares into one signature; custom callbacks still run once per agent.
16032
17224
  * @param options.agentId - Optional explicit target. Otherwise split equally,
16033
17225
  * or fund remaining agents when a recovery deposit cannot meet every minimum.
17226
+ * @param options.excludeAgentIds - Agents that must receive nothing. The rest
17227
+ * split the whole amount under their own minimums. Throws
17228
+ * `ALL_AGENTS_EXCLUDED` when none is left or `agentId` is listed. Ignored
17229
+ * when resuming a signed batch.
16034
17230
  * @returns {OwneyDepositResult} for a single agent, or {OwneyMultiDepositResult} with per-agent results
16035
17231
  */
16036
17232
  async deposit(options) {
@@ -16059,6 +17255,7 @@ var OwneySDK = class {
16059
17255
  const submitted = !!(evidence.txHash || evidence.userOpHash || evidence.callsId || evidence.depositSubmission === "started");
16060
17256
  if (leg) ledgerOp?.leg(submitted ? { ...leg, rail: ledgerRail(evidence.agentId) } : leg);
16061
17257
  if (leg?.status === "confirmed") this.ledgerProviderSamples(ledgerOp, evidence, "deposit");
17258
+ this.announceDepositConfirmed(state, chainId, evidence, ledgerOp);
16062
17259
  } catch {
16063
17260
  }
16064
17261
  };
@@ -16094,6 +17291,8 @@ var OwneySDK = class {
16094
17291
  const state = this.requireState();
16095
17292
  const chainId = options.chainId ?? this.requireChainId();
16096
17293
  const activatedChain = state.chainId;
17294
+ const excludeAgentIds = options.resumeTxHash || options.resumeSavedBatch ? void 0 : options.excludeAgentIds;
17295
+ this.assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds);
16097
17296
  let checkpointFailure;
16098
17297
  let checkpointFailedEvidence = [];
16099
17298
  const checkpoint2 = options.onBeforeSubmission ? async (evidence) => {
@@ -16190,11 +17389,11 @@ var OwneySDK = class {
16190
17389
  const batchTransfer2 = getDepositBatchTransfer(effectiveCallback);
16191
17390
  if (!batchTransfer2) throw invalid2();
16192
17391
  const result = await runAgentDepositBatch(chainId, legs, batchTransfer2).catch((error) => {
16193
- if (error instanceof OwneyError && error.code === "YIELDSEEKER_WALLET_UNVERIFIED")
17392
+ if (error instanceof OwneyError && (error.code === "YIELDSEEKER_WALLET_UNVERIFIED" || error.code === "YIELDSEEKER_AGENT_CLOSED" || error.details?.notSubmitted === true))
16194
17393
  throw new OwneyError(
16195
17394
  error.code,
16196
- "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier.",
16197
- { ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
17395
+ error.code === "YIELDSEEKER_WALLET_UNVERIFIED" ? "We could not verify your Yieldseeker wallet on-chain, so the saved deposit was not re-sent. It may already have been submitted earlier." : "The saved deposit was not re-sent. It may already have been submitted earlier.",
17396
+ { cause: error.message, ...error.details, notSubmitted: false, safeToFallback: false, resumeTxHash: options.resumeTxHash },
16198
17397
  error.agentId
16199
17398
  );
16200
17399
  throw error;
@@ -16232,7 +17431,7 @@ var OwneySDK = class {
16232
17431
  this.validateChainHasAgents(chainId);
16233
17432
  const eligibleAgents = this.getEligibleAgents(chainId, asset, {
16234
17433
  excludeDisabled: true
16235
- });
17434
+ }).filter((agent) => !excludeAgentIds?.includes(agent.id));
16236
17435
  const prospectiveShare = totalAmount / BigInt(eligibleAgents.length);
16237
17436
  const meetsEveryMinimum = eligibleAgents.every((agent) => prospectiveShare >= this.getMinDepositAmount(agent, chainId, asset));
16238
17437
  const exemptFlags = meetsEveryMinimum ? eligibleAgents.map(() => false) : await Promise.all(eligibleAgents.map((agent) => this.hasExistingBalance(agent, state, chainId, asset, true)));
@@ -16380,7 +17579,7 @@ var OwneySDK = class {
16380
17579
  }
16381
17580
  try {
16382
17581
  if (!depositCallback && appObserves && !options.resumeTxHash) {
16383
- const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).map((agent) => agent.id);
17582
+ const ids = agentId ? [agentId] : this.getEligibleAgents(chainId, asset).filter((agent) => !excludeAgentIds?.includes(agent.id)).map((agent) => agent.id);
16384
17583
  for (const id of ids) {
16385
17584
  const evidence = [...prepared.values()].find((value) => value.agentId === id);
16386
17585
  const rejected = error instanceof OwneyError && error.details?.notSubmitted === true;
@@ -16480,6 +17679,29 @@ var OwneySDK = class {
16480
17679
  }
16481
17680
  }
16482
17681
  }
17682
+ /**
17683
+ * Refuses a new deposit that `excludeAgentIds` leaves with nobody to fund:
17684
+ * the explicit `agentId` is listed, or every agent that can take this asset
17685
+ * on this chain (and is not disabled) is. A no-op without a list, so a deposit
17686
+ * without exclusions is exactly as it was. Reads no provider.
17687
+ */
17688
+ assertDepositAgentsRemain(chainId, asset, agentId, excludeAgentIds) {
17689
+ if (!excludeAgentIds?.length) return;
17690
+ const refuse = (message) => new OwneyError(
17691
+ "ALL_AGENTS_EXCLUDED",
17692
+ message,
17693
+ { phase: "prepare", rejectedBeforeSubmission: true }
17694
+ );
17695
+ if (agentId) {
17696
+ if (excludeAgentIds.includes(agentId))
17697
+ throw refuse(`Agent "${agentId}" is excluded from this deposit. No deposit was submitted.`);
17698
+ return;
17699
+ }
17700
+ this.validateChainHasAgents(chainId);
17701
+ const remaining = this.getEligibleAgents(chainId, asset, { excludeDisabled: true }).filter((agent) => !excludeAgentIds.includes(agent.id));
17702
+ if (remaining.length === 0)
17703
+ throw refuse(`Every agent that can take ${asset} on chain ${chainId} is excluded from this deposit. No deposit was submitted.`);
17704
+ }
16483
17705
  getMinDepositAmount(agent, chainId, asset) {
16484
17706
  const chainAssets = agent.supportedAssets.find(
16485
17707
  (sa) => sa.chainId === chainId
@@ -16634,9 +17856,15 @@ var OwneySDK = class {
16634
17856
  );
16635
17857
  }
16636
17858
  }
17859
+ /**
17860
+ * The agents that support this asset on this chain. `excludeDisabled` is for
17861
+ * new deposits: it also leaves out the agents unavailable for this slot this
17862
+ * session (see `getUnavailableAgentIds`). Without it, withdrawals and deposit
17863
+ * recovery still see every agent that may hold funds.
17864
+ */
16637
17865
  getEligibleAgents(chainId, asset, opts) {
16638
17866
  const eligible = [...this.agents.values()].filter((agent) => {
16639
- if (opts?.excludeDisabled && this.isAgentDisabled(agent.id)) {
17867
+ if (opts?.excludeDisabled && (this.isAgentDisabled(agent.id) || this.isAgentUnavailable(agent.id, chainId, asset))) {
16640
17868
  return false;
16641
17869
  }
16642
17870
  const chainAssets = agent.supportedAssets.find(
@@ -16664,20 +17892,13 @@ var OwneySDK = class {
16664
17892
  return approvalOrder || left.index - right.index;
16665
17893
  }).map(({ agent }) => agent);
16666
17894
  }
17895
+ /**
17896
+ * The user cancelled a wallet prompt, for any agent: see isWalletRejection.
17897
+ * That includes an agent error that kept the rejection only as text in
17898
+ * `details.cause`.
17899
+ */
16667
17900
  isUserRejectedWithdrawal(error) {
16668
- let current = error;
16669
- const seen = /* @__PURE__ */ new Set();
16670
- while (current && typeof current === "object" && !seen.has(current)) {
16671
- seen.add(current);
16672
- const candidate = current;
16673
- if (candidate.code === 4001 || candidate.code === "4001" || candidate.code === "ACTION_REJECTED") return true;
16674
- const message = [candidate.message, candidate.shortMessage].filter((value) => typeof value === "string").join(" ");
16675
- if (/user (?:rejected|denied)|rejected by user|request rejected/i.test(message)) {
16676
- return true;
16677
- }
16678
- current = candidate.cause;
16679
- }
16680
- return false;
17901
+ return isWalletRejection(error);
16681
17902
  }
16682
17903
  captureReadScope(requestedChain) {
16683
17904
  const original = this.requireState();
@@ -16778,6 +17999,7 @@ var OwneySDK = class {
16778
17999
  if (isFullYieldseekerWithdrawal(transaction, { ...evidence, agentWallet }, token.address, receipt))
16779
18000
  verified = inspectFundingReceipt(receipt, { ...evidence, agentWallet, intendedAmount: "MAX" }, token.address, direction);
16780
18001
  }
18002
+ if (direction === "deposit") this.announceDepositConfirmed(state, chainId, verified);
16781
18003
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}`;
16782
18004
  if (options.refreshBalance !== false && (verified.transfer === "confirmed" || verified.transfer === "failed" && verified.confirmedAmount === "0") && !this.recoveredFundingReads.has(key2)) {
16783
18005
  agent.invalidateFundingRead?.(state, chainId, evidence.token, options.balanceRefreshUntil, evidence.txHash);
@@ -16786,6 +18008,33 @@ var OwneySDK = class {
16786
18008
  }
16787
18009
  return verified;
16788
18010
  }
18011
+ /**
18012
+ * Tells the agent, once per confirmed deposit transfer, that its deposit
18013
+ * landed (`IAgent.depositConfirmed`), and records the outcome on the
18014
+ * deposit's ledger operation when there is one. In the background: never
18015
+ * throws and never delays the deposit. A missed notice only leaves the
18016
+ * provider on its own schedule.
18017
+ */
18018
+ announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18019
+ try {
18020
+ if (evidence.transfer !== "confirmed") return;
18021
+ const agent = this.agents.get(evidence.agentId);
18022
+ const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
18023
+ if (!agent?.depositConfirmed || !movement) return;
18024
+ const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
18025
+ if (this.announcedDeposits.has(key2)) return;
18026
+ this.announcedDeposits.add(key2);
18027
+ if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18028
+ const legKey = `agent:${evidence.agentId}`;
18029
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18030
+ try {
18031
+ ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18032
+ } catch {
18033
+ }
18034
+ });
18035
+ } catch {
18036
+ }
18037
+ }
16789
18038
  noteFundingRefresh(key2, armed) {
16790
18039
  this.recoveredFundingReads.delete(key2);
16791
18040
  this.recoveredFundingReads.set(key2, armed);
@@ -17274,6 +18523,14 @@ var OwneySDK = class {
17274
18523
  return hash2;
17275
18524
  },
17276
18525
  ensureChain: (id) => this.ensureSwapChain(id),
18526
+ // Over HTTP, so a wallet that broadcast the wrap without telling the
18527
+ // page cannot also hide that it landed (ROUT-726).
18528
+ readWrappedBalance: () => publicClient.readContract({
18529
+ address: wrapper.address,
18530
+ abi: ERC20_ALLOWANCE_ABI,
18531
+ functionName: "balanceOf",
18532
+ args: [walletAddress]
18533
+ }),
17277
18534
  // Read through the same public client as every other sizing input, so
17278
18535
  // a wallet sitting on the wrong chain cannot answer for this one.
17279
18536
  readAllowance: (token, spender) => publicClient.readContract({
@@ -17719,8 +18976,17 @@ var OwneySDK = class {
17719
18976
  * second half of `swapAndDeposit` on its own. Cleared only once the deposit
17720
18977
  * has actually gone through — a failure here leaves the record in place so it
17721
18978
  * can be offered again rather than silently dropped.
18979
+ *
18980
+ * The record does not remember `excludeAgentIds`, on purpose: the caller must
18981
+ * pass the CURRENT list, because the user's choice may have changed since the
18982
+ * swap (a deposit reads it fresh each time). Without it, a record with no
18983
+ * `agentId` splits across every eligible agent. When the list leaves nobody to
18984
+ * fund (or names the record's own agent) it throws `ALL_AGENTS_EXCLUDED`
18985
+ * before the wallet is touched and keeps the record.
18986
+ *
18987
+ * @param options.excludeAgentIds - See `DepositOptions.excludeAgentIds`.
17722
18988
  */
17723
- async completePendingDeposit(id) {
18989
+ async completePendingDeposit(id, options = {}) {
17724
18990
  const entry = listPendingDeposits().find((p) => p.id === id);
17725
18991
  if (!entry) {
17726
18992
  throw new OwneyError(
@@ -17729,6 +18995,12 @@ var OwneySDK = class {
17729
18995
  { id }
17730
18996
  );
17731
18997
  }
18998
+ this.assertDepositAgentsRemain(
18999
+ entry.chainId,
19000
+ entry.symbol,
19001
+ entry.agentId,
19002
+ options.excludeAgentIds
19003
+ );
17732
19004
  await this.ensureSwapChain(entry.chainId);
17733
19005
  const token = entry.symbol === "WETH" ? SPONSORED_WETH_BY_CHAIN[entry.chainId] : void 0;
17734
19006
  const amount = token ? await this.settleSwapDepositAmount(
@@ -17741,6 +19013,7 @@ var OwneySDK = class {
17741
19013
  amount,
17742
19014
  asset: entry.symbol,
17743
19015
  ...entry.agentId ? { agentId: entry.agentId } : {},
19016
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
17744
19017
  // The swap's own funding-ledger operation; older records have none.
17745
19018
  ...typeof entry.operationId === "string" ? { operationId: entry.operationId } : {},
17746
19019
  ...typeof entry.batchId === "string" ? { batchId: entry.batchId } : {}
@@ -17969,6 +19242,7 @@ var OwneySDK = class {
17969
19242
  async swapAndDeposit(options) {
17970
19243
  const state = this.requireState();
17971
19244
  options.assertCurrent?.();
19245
+ this.assertDepositAgentsRemain(options.to.chainId, options.to.symbol, options.agentId, options.excludeAgentIds);
17972
19246
  if (options.agentId) {
17973
19247
  this.validateAssetSupport(
17974
19248
  this.getAgent(options.agentId),
@@ -18070,6 +19344,7 @@ var OwneySDK = class {
18070
19344
  amount,
18071
19345
  asset: options.to.symbol,
18072
19346
  ...options.agentId ? { agentId: options.agentId } : {},
19347
+ ...options.excludeAgentIds ? { excludeAgentIds: options.excludeAgentIds } : {},
18073
19348
  ...options.onDepositProgress ? { onProgress: options.onDepositProgress } : {},
18074
19349
  ...options.onBeforeDepositSubmission ? { onBeforeSubmission: options.onBeforeDepositSubmission } : {},
18075
19350
  ...options.assertCurrent ? { assertSubmissionCurrent: options.assertCurrent } : {},
@@ -18609,7 +19884,7 @@ var OwneySDK = class {
18609
19884
  "A withdrawal request is already running.",
18610
19885
  { chainId, asset: options.asset, phase: "prepare", rejectedBeforeSubmission: true }
18611
19886
  );
18612
- const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id));
19887
+ const ids = options.agentId ? [options.agentId] : this.getActiveAgentIds().filter((id) => !options.excludeAgentIds?.includes(id) && !this.hasNoAgentForSlot(this.agents.get(id), state, chainId, options.asset));
18613
19888
  const attempted = /* @__PURE__ */ new Set();
18614
19889
  this.withdrawalSubmissions.add(submissionKey);
18615
19890
  let ledgerOp;
@@ -19080,6 +20355,8 @@ var OwneySDK = class {
19080
20355
  progress({ ...evidence, transfer: "failed", delivery: "failed" });
19081
20356
  if (serverLegs.size && requested2 === void 0 && agent.withdrawalRequiresWalletApproval && error instanceof OwneyError && error.code === "WITHDRAW_INSUFFICIENT_BALANCE" && error.details?.available === "0" && evidence.transfer === "failed" && !evidence.txHash && !evidence.userOpHash && !evidence.callsId)
19082
20357
  ledgerLeg?.(evidence, "WITHDRAW_INSUFFICIENT_BALANCE");
20358
+ else if (error instanceof OwneyError && /^[A-Z0-9_]{1,64}$/.test(error.code) && evidence.transfer === "failed" && !evidence.withdrawalRequest?.failure && !(requested2 === void 0 && error.code === "WITHDRAW_INSUFFICIENT_BALANCE"))
20359
+ ledgerLeg?.(evidence, error.code);
19083
20360
  settled({ settled: "threw", evidence });
19084
20361
  throw error;
19085
20362
  }
@@ -19187,7 +20464,7 @@ var OwneySDK = class {
19187
20464
  serverLegs.set(planned.agentId, leg);
19188
20465
  }
19189
20466
  };
19190
- const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id));
20467
+ const eligibleAgents = this.getEligibleAgents(chainId, asset).filter((agent) => !options.excludeAgentIds?.includes(agent.id) && !this.hasNoAgentForSlot(agent, state, chainId, asset));
19191
20468
  const withdrawalAgents = this.orderAgentsForWithdrawal(eligibleAgents);
19192
20469
  if (!amount) {
19193
20470
  const results2 = {};
@@ -19587,9 +20864,10 @@ var OwneySDK = class {
19587
20864
  }
19588
20865
  async getBalances(agentId, options) {
19589
20866
  if (agentId) {
19590
- const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20867
+ const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19591
20868
  const asset = options?.asset;
19592
20869
  const agent = this.getAgent(agentId);
20870
+ const state = this.readStateFor(agentId, scope);
19593
20871
  const result = await this.readAgent(
19594
20872
  agent,
19595
20873
  "balances",
@@ -19620,10 +20898,10 @@ var OwneySDK = class {
19620
20898
  async readAggregatedBalances(options, portfolio = false) {
19621
20899
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
19622
20900
  const asset = options?.asset;
19623
- const readBalance = (read2) => read2.state === state ? this.readAgent(
20901
+ const readBalance = (read2) => !read2.offChain ? this.readAgent(
19624
20902
  read2.agent,
19625
20903
  "balances",
19626
- () => asset ? read2.agent.getBalances(state, chainId, asset) : read2.agent.getBalances(state, chainId),
20904
+ () => asset ? read2.agent.getBalances(read2.state, chainId, asset) : read2.agent.getBalances(read2.state, chainId),
19627
20905
  asset ? { asset } : null
19628
20906
  ) : this.readAgent(
19629
20907
  read2.agent,
@@ -19633,7 +20911,7 @@ var OwneySDK = class {
19633
20911
  );
19634
20912
  let totalBalance = 0;
19635
20913
  const results = {};
19636
- const entries = portfolio ? this.portfolioReads(state, chainId).map((read2) => [read2.id, read2]) : [...this.getActiveAgents()].map(([id, agent]) => [id, { id, agent, state, chainId }]);
20914
+ const entries = (portfolio ? this.portfolioReads(state, chainId) : this.activeReads(state, chainId)).map((read2) => [read2.id, read2]);
19637
20915
  const balanceResults = await Promise.allSettled(
19638
20916
  entries.map(async ([id, read2]) => {
19639
20917
  const { agent } = read2;
@@ -19688,10 +20966,11 @@ var OwneySDK = class {
19688
20966
  const chainId = this.requireChainId();
19689
20967
  if (agentId) {
19690
20968
  const agent = this.getAgent(agentId);
20969
+ const readState = this.readStateFor(agentId, state);
19691
20970
  return this.readAgent(
19692
20971
  agent,
19693
20972
  "earnings",
19694
- () => agent.getEarnings(state, chainId)
20973
+ () => agent.getEarnings(readState, chainId)
19695
20974
  );
19696
20975
  }
19697
20976
  return this.aggregateEarnings(
@@ -19700,7 +20979,7 @@ var OwneySDK = class {
19700
20979
  read2.agent,
19701
20980
  "earnings",
19702
20981
  () => read2.agent.getEarnings(read2.state, read2.chainId),
19703
- read2.state === state ? null : { chainId: read2.chainId }
20982
+ read2.offChain ? { chainId: read2.chainId } : null
19704
20983
  )
19705
20984
  );
19706
20985
  }
@@ -19711,13 +20990,13 @@ var OwneySDK = class {
19711
20990
  async refreshEarnings(agentId) {
19712
20991
  const state = this.requireState();
19713
20992
  const chainId = this.requireChainId();
19714
- const refreshAgent = ({ agent, state: readState, chainId: readChain }) => this.readAgent(
20993
+ const refreshAgent = ({ agent, state: readState, chainId: readChain, offChain }) => this.readAgent(
19715
20994
  agent,
19716
20995
  agent.refreshEarnings ? "refreshEarnings" : "earnings",
19717
20996
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
19718
- readState === state ? null : { chainId: readChain }
20997
+ offChain ? { chainId: readChain } : null
19719
20998
  );
19720
- if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state, chainId });
20999
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
19721
21000
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
19722
21001
  }
19723
21002
  async aggregateEarnings(entries, read2) {
@@ -19785,7 +21064,7 @@ var OwneySDK = class {
19785
21064
  for (const agent of agents) {
19786
21065
  for (const legChainId of chainIds) {
19787
21066
  if (agentRunsOn(agent, legChainId))
19788
- legs.push({ agent, legChainId, legState: state });
21067
+ legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
19789
21068
  }
19790
21069
  }
19791
21070
  if (!agentId) {
@@ -19825,22 +21104,21 @@ var OwneySDK = class {
19825
21104
  assets: []
19826
21105
  };
19827
21106
  }
21107
+ const readState = this.readStateFor(agentId, state);
19828
21108
  return this.readAgent(
19829
21109
  agent,
19830
21110
  "dailyEarnings",
19831
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21111
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
19832
21112
  { days, tokenSymbol }
19833
21113
  );
19834
21114
  }
19835
- const entries = [...this.getActiveAgents().entries()].filter(
19836
- ([, agent]) => agent.getDailyEarnings
19837
- );
21115
+ const entries = this.activeReads(state, chainId).filter(({ agent }) => agent.getDailyEarnings);
19838
21116
  const settled = await Promise.allSettled(
19839
21117
  entries.map(
19840
- ([, agent]) => this.readAgent(
21118
+ ({ agent, state: readState }) => this.readAgent(
19841
21119
  agent,
19842
21120
  "dailyEarnings",
19843
- () => agent.getDailyEarnings(state, chainId, days, tokenSymbol),
21121
+ () => agent.getDailyEarnings(readState, chainId, days, tokenSymbol),
19844
21122
  { days, tokenSymbol }
19845
21123
  )
19846
21124
  )
@@ -19889,7 +21167,7 @@ var OwneySDK = class {
19889
21167
  `Agent ${agent.id} does not support pool customization`
19890
21168
  );
19891
21169
  }
19892
- await agent.setPoolSelection(params.selection);
21170
+ await agent.setPoolSelection(params.selection, this.state ?? void 0);
19893
21171
  }
19894
21172
  /**
19895
21173
  * The pool selection saved on the user's account (ROUT-650), so the Pools
@@ -19912,6 +21190,15 @@ var OwneySDK = class {
19912
21190
  assets: params.assets
19913
21191
  });
19914
21192
  }
21193
+ /**
21194
+ * The agents a person can customize pools for: registered, enabled, and
21195
+ * able to list a pool catalogue. Waits for agent initialization, so an agent
21196
+ * the organization disabled is known and left out.
21197
+ */
21198
+ async getPoolCustomizationAgents() {
21199
+ await this.ensureAgentsInitialized();
21200
+ return [...this.agents].filter(([id, agent]) => !this.isAgentDisabled(id) && typeof agent.getPoolCatalog === "function").map(([id]) => id).sort();
21201
+ }
19915
21202
  async getAccountApy({
19916
21203
  agentId,
19917
21204
  days,
@@ -19923,17 +21210,23 @@ var OwneySDK = class {
19923
21210
  const scopeChainId = scope === "all" ? null : scope;
19924
21211
  if (agentId) {
19925
21212
  const agent = this.getAgent(agentId);
19926
- return this.readAgent(
21213
+ const readState = this.readStateFor(agentId, state);
21214
+ const accountApy = await this.readAgent(
19927
21215
  agent,
19928
21216
  "accountApy",
19929
- () => agent.getAccountApy(state, chainId, days, tokenSymbol, scopeChainId),
21217
+ () => agent.getAccountApy(readState, chainId, days, tokenSymbol, scopeChainId),
19930
21218
  { days, tokenSymbol, scopeChainId }
19931
21219
  );
21220
+ return this.enrichApyHistory(
21221
+ accountApy,
21222
+ agentId,
21223
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21224
+ tokenSymbol
21225
+ );
19932
21226
  }
19933
- const entries = scopeChainId === void 0 ? [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state, chainId })) : this.portfolioReads(state, chainId).filter((read2) => read2.state === state || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
21227
+ const entries = scopeChainId === void 0 ? this.activeReads(state, chainId) : this.portfolioReads(state, chainId).filter((read2) => !read2.offChain || scopeChainId === null || agentRunsOn(read2.agent, scopeChainId));
19934
21228
  const reads = await Promise.all(
19935
- entries.map(async ({ id, agent, state: readState, chainId: readChain }) => {
19936
- const offChain = readState !== state;
21229
+ entries.map(async ({ id, agent, state: readState, chainId: readChain, offChain = false }) => {
19937
21230
  const pair = Promise.all([
19938
21231
  this.readAgent(
19939
21232
  agent,
@@ -19965,7 +21258,12 @@ var OwneySDK = class {
19965
21258
  const balanceResults = reads.flatMap((read2) => read2 ? [[read2[0], read2[2]]] : []);
19966
21259
  const results = {};
19967
21260
  for (const [id, apy] of apyResults) {
19968
- results[id] = apy;
21261
+ results[id] = await this.enrichApyHistory(
21262
+ apy,
21263
+ id,
21264
+ scopeChainId === null ? void 0 : scopeChainId ?? chainId,
21265
+ tokenSymbol
21266
+ );
19969
21267
  }
19970
21268
  const balances = {};
19971
21269
  for (const [id, bal] of balanceResults) {
@@ -19995,6 +21293,36 @@ var OwneySDK = class {
19995
21293
  history
19996
21294
  };
19997
21295
  }
21296
+ async enrichApyHistory(accountApy, agentId, chainId, tokenSymbol) {
21297
+ const history = accountApy.history;
21298
+ if (agentId !== "zyfai" || chainId === void 0 || !tokenSymbol || !history?.length) return accountApy;
21299
+ const incentives = await fetchApyIncentives(
21300
+ this.apiKey,
21301
+ {
21302
+ walletAddress: accountApy.walletAddress,
21303
+ agentId,
21304
+ chainId,
21305
+ asset: tokenSymbol,
21306
+ from: history[0].date,
21307
+ to: history[history.length - 1].date
21308
+ },
21309
+ this.routingApiBaseUrl
21310
+ );
21311
+ if (incentives.length === 0) return accountApy;
21312
+ const byDate = /* @__PURE__ */ new Map();
21313
+ for (const { date, ...incentive } of incentives) {
21314
+ const entries = byDate.get(date) ?? [];
21315
+ entries.push(incentive);
21316
+ byDate.set(date, entries);
21317
+ }
21318
+ return {
21319
+ ...accountApy,
21320
+ history: history.map((point) => {
21321
+ const pointIncentives = byDate.get(point.date);
21322
+ return pointIncentives?.length ? { ...point, incentives: pointIncentives } : point;
21323
+ })
21324
+ };
21325
+ }
19998
21326
  /**
19999
21327
  * Get transaction history for a specific agent, or all agents.
20000
21328
  *
@@ -20022,7 +21350,7 @@ var OwneySDK = class {
20022
21350
  for (const agent of agents) {
20023
21351
  for (const legChainId of chainIds) {
20024
21352
  if (agentRunsOn(agent, legChainId))
20025
- legs.push({ agentId: agent.id, chainId: legChainId, legState: state2 });
21353
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
20026
21354
  }
20027
21355
  }
20028
21356
  if (!agentId) {
@@ -20066,7 +21394,8 @@ var OwneySDK = class {
20066
21394
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
20067
21395
  if (agentId) {
20068
21396
  const agent = this.getAgent(agentId);
20069
- const page = await this.readAgent(agent, "history", () => agent.getHistory(state, chainId, filters), filters);
21397
+ const readState = this.readStateFor(agentId, state);
21398
+ const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
20070
21399
  assertCurrent();
20071
21400
  return page;
20072
21401
  }
@@ -20080,10 +21409,11 @@ var OwneySDK = class {
20080
21409
  }
20081
21410
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
20082
21411
  try {
21412
+ const readState = this.readStateFor(agent.id, state);
20083
21413
  const page = await this.readAgent(
20084
21414
  agent,
20085
21415
  "history",
20086
- () => agent.getHistory(state, chainId, agentFilters),
21416
+ () => agent.getHistory(readState, chainId, agentFilters),
20087
21417
  agentFilters
20088
21418
  );
20089
21419
  return { agentId: agent.id, page };
@@ -20141,20 +21471,20 @@ var OwneySDK = class {
20141
21471
  const chainId = this.requireChainId();
20142
21472
  if (agentId) {
20143
21473
  const agent = this.getAgent(agentId);
21474
+ const readState = this.readStateFor(agentId, state);
20144
21475
  return this.readAgent(
20145
21476
  agent,
20146
21477
  "profile",
20147
- () => agent.getUserProfile(state, chainId)
21478
+ () => agent.getUserProfile(readState, chainId)
20148
21479
  );
20149
21480
  }
20150
21481
  const results = {};
20151
- const entries = [...this.getActiveAgents().entries()];
20152
21482
  const profileResults = await Promise.all(
20153
- entries.map(async ([id, agent]) => {
21483
+ this.activeReads(state, chainId).map(async ({ id, agent, state: readState }) => {
20154
21484
  const p = await this.readAgent(
20155
21485
  agent,
20156
21486
  "profile",
20157
- () => agent.getUserProfile(state, chainId)
21487
+ () => agent.getUserProfile(readState, chainId)
20158
21488
  );
20159
21489
  return [id, p];
20160
21490
  })
@@ -20364,10 +21694,11 @@ var OwneySDK = class {
20364
21694
  const entries = [...activeAgents.entries()];
20365
21695
  const balanceResults = await Promise.allSettled(
20366
21696
  entries.map(async ([id, agent]) => {
21697
+ const readState = this.readStateFor(id, state);
20367
21698
  const b = await this.readAgent(
20368
21699
  agent,
20369
21700
  "balances",
20370
- () => agent.getBalances(state, chainId)
21701
+ () => agent.getBalances(readState, chainId)
20371
21702
  );
20372
21703
  return [id, b.positions ?? []];
20373
21704
  })
@@ -20649,5 +21980,6 @@ export {
20649
21980
  saveWithdrawSwap,
20650
21981
  setOwneyDebug,
20651
21982
  subscribeWithdrawSwaps,
21983
+ switchWalletConnectChain,
20652
21984
  updateWithdrawSwap
20653
21985
  };