@owney/sdk 0.7.32-beta.11 → 0.7.32-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -246,10 +246,10 @@ function tokenBatchClear(key2, expected) {
246
246
  }
247
247
  function keys() {
248
248
  if (typeof window === "undefined") return [...memory.keys()];
249
- const storage9 = window.localStorage;
249
+ const storage11 = window.localStorage;
250
250
  return Array.from(
251
- { length: storage9.length },
252
- (_, i) => storage9.key(i)
251
+ { length: storage11.length },
252
+ (_, i) => storage11.key(i)
253
253
  ).filter((key2) => key2 !== null);
254
254
  }
255
255
  function pending(message = "The saved deposit could not be verified. Its existing transactions remain pending.") {
@@ -1389,6 +1389,46 @@ async function fetchProviderSnapshot(input) {
1389
1389
  }
1390
1390
  }
1391
1391
 
1392
+ // src/lib/announced-deposits.ts
1393
+ var KEY = "owney.announced-deposits.v1";
1394
+ var TTL_MS = 7 * 24 * 60 * 6e4;
1395
+ var MAX_ENTRIES = 256;
1396
+ var storage = () => {
1397
+ if (typeof window === "undefined") return null;
1398
+ try {
1399
+ return window.localStorage;
1400
+ } catch {
1401
+ return null;
1402
+ }
1403
+ };
1404
+ function load(now) {
1405
+ const entries = /* @__PURE__ */ new Map();
1406
+ try {
1407
+ const raw2 = storage()?.getItem(KEY);
1408
+ const parsed = raw2 ? JSON.parse(raw2) : null;
1409
+ if (parsed && typeof parsed === "object") {
1410
+ for (const [key2, at] of Object.entries(parsed)) {
1411
+ if (typeof at === "number" && Number.isFinite(at)) entries.set(key2, Math.max(entries.get(key2) ?? 0, at));
1412
+ }
1413
+ }
1414
+ } catch {
1415
+ }
1416
+ for (const [key2, at] of entries) if (at + TTL_MS <= now) entries.delete(key2);
1417
+ return entries;
1418
+ }
1419
+ function wasDepositAnnounced(key2, now = Date.now()) {
1420
+ return load(now).has(key2);
1421
+ }
1422
+ function rememberAnnouncedDeposit(key2, now = Date.now()) {
1423
+ const entries = load(now);
1424
+ entries.set(key2, now);
1425
+ const kept = [...entries].sort((a, b) => a[1] - b[1]).slice(-MAX_ENTRIES);
1426
+ try {
1427
+ storage()?.setItem(KEY, JSON.stringify(Object.fromEntries(kept)));
1428
+ } catch {
1429
+ }
1430
+ }
1431
+
1392
1432
  // src/lib/earnings-hold.ts
1393
1433
  var EARNINGS_HOLD_CAP_MS = 24 * 60 * 6e4;
1394
1434
  var REFRESH_INDEX_WINDOW_MS = 60 * 6e4;
@@ -1683,7 +1723,7 @@ var SnapshotHistory = class {
1683
1723
  };
1684
1724
 
1685
1725
  // src/lib/funding-ledger.ts
1686
- var SDK_VERSION = "0.7.32-beta.11";
1726
+ var SDK_VERSION = "0.7.32-beta.12";
1687
1727
  var SCOPE2 = "funding-ledger";
1688
1728
  var REQUEST_TIMEOUT_MS2 = 5e3;
1689
1729
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -2352,7 +2392,7 @@ function releaseWithdrawalReservationHold(cfg, operationId, holderToken, reason,
2352
2392
  return track(holderRequest(cfg, operationId, "release", compact2({ holderToken, agents, reason }), RELEASE_RETRY_DELAYS_MS));
2353
2393
  }
2354
2394
  var memoryTokens = /* @__PURE__ */ new Map();
2355
- function storage() {
2395
+ function storage2() {
2356
2396
  try {
2357
2397
  const store = globalThis.localStorage;
2358
2398
  return store && typeof store.getItem === "function" ? store : null;
@@ -2376,7 +2416,7 @@ function saveHolderToken(operationId, holderToken, hardExpiresAt = Date.now() +
2376
2416
  const entry = { token: holderToken, hardExpiresAt };
2377
2417
  memoryTokens.set(key2, entry);
2378
2418
  try {
2379
- storage()?.setItem(key2, JSON.stringify(entry));
2419
+ storage2()?.setItem(key2, JSON.stringify(entry));
2380
2420
  } catch {
2381
2421
  }
2382
2422
  }
@@ -2384,7 +2424,7 @@ function loadHolderToken(operationId, now = Date.now()) {
2384
2424
  const key2 = STORAGE_PREFIX + operationId.toLowerCase();
2385
2425
  let entry;
2386
2426
  try {
2387
- entry = parseStored(storage()?.getItem(key2));
2427
+ entry = parseStored(storage2()?.getItem(key2));
2388
2428
  } catch {
2389
2429
  }
2390
2430
  entry ??= memoryTokens.get(key2);
@@ -2399,14 +2439,14 @@ function deleteHolderToken(operationId) {
2399
2439
  const key2 = STORAGE_PREFIX + operationId.toLowerCase();
2400
2440
  memoryTokens.delete(key2);
2401
2441
  try {
2402
- storage()?.removeItem(key2);
2442
+ storage2()?.removeItem(key2);
2403
2443
  } catch {
2404
2444
  }
2405
2445
  }
2406
2446
  function sweepHolderTokens(now = Date.now()) {
2407
2447
  for (const [key2, entry] of memoryTokens) if (entry.hardExpiresAt <= now) memoryTokens.delete(key2);
2408
2448
  try {
2409
- const store = storage();
2449
+ const store = storage2();
2410
2450
  if (!store) return;
2411
2451
  const keys2 = [];
2412
2452
  for (let i = 0; i < store.length; i++) {
@@ -4267,7 +4307,7 @@ init_errors();
4267
4307
 
4268
4308
  // src/agents/zyfai/zyfai.auth-cache.ts
4269
4309
  var KEY_PREFIX = "owney.zyfai.session";
4270
- var storage2 = () => {
4310
+ var storage3 = () => {
4271
4311
  if (typeof window === "undefined") return null;
4272
4312
  try {
4273
4313
  return window.localStorage;
@@ -4324,7 +4364,7 @@ var readLegacySession = (store, address) => {
4324
4364
  var readSession = (address, _chainId) => {
4325
4365
  if (typeof window === "undefined") return null;
4326
4366
  const key2 = buildKey(address);
4327
- const store = storage2();
4367
+ const store = storage3();
4328
4368
  let raw2 = null;
4329
4369
  try {
4330
4370
  raw2 = store?.getItem(key2) ?? null;
@@ -4358,7 +4398,7 @@ var writeSession = (address, _chainId, session) => {
4358
4398
  if (typeof window === "undefined") return;
4359
4399
  const key2 = buildKey(address);
4360
4400
  memorySessions.set(key2, session);
4361
- const store = storage2();
4401
+ const store = storage3();
4362
4402
  try {
4363
4403
  store?.setItem(key2, JSON.stringify(session));
4364
4404
  } catch {
@@ -4367,7 +4407,7 @@ var writeSession = (address, _chainId, session) => {
4367
4407
  var clearSession = (address, _chainId) => {
4368
4408
  const key2 = buildKey(address);
4369
4409
  memorySessions.delete(key2);
4370
- const store = storage2();
4410
+ const store = storage3();
4371
4411
  try {
4372
4412
  store?.removeItem(key2);
4373
4413
  } catch {
@@ -4863,6 +4903,8 @@ async function withPaidRpcDiagnostics(operation, chainId, rpcMethod, agentId) {
4863
4903
  var ERC7579_IS_MODULE_INSTALLED_ABI = (0, import_viem10.parseAbi)([
4864
4904
  "function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
4865
4905
  ]);
4906
+ var ZYFAI_SIGN_IN_REQUIRED_MESSAGE = "No Zyfai sign-in is available without a prompt.";
4907
+ var isSignInFailure = (error) => error instanceof OwneyError && error.code === "AGENT_AUTH_FAILED";
4866
4908
  var WETH_ADDRESS_BY_CHAIN = {
4867
4909
  8453: "0x4200000000000000000000000000000000000006",
4868
4910
  42161: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
@@ -4977,6 +5019,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4977
5019
  }
4978
5020
  ];
4979
5021
  sdk;
5022
+ signInRefusedListener;
4980
5023
  connectedAddress = null;
4981
5024
  connectedChainId = null;
4982
5025
  smartWalletCache = /* @__PURE__ */ new Map();
@@ -4991,6 +5034,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
4991
5034
  reportedAccounts = /* @__PURE__ */ new Set();
4992
5035
  connectAuthPromise = null;
4993
5036
  connectAuthScope = null;
5037
+ /** Whether `connectAuthPromise` is a read's connect, which never signs. */
5038
+ connectAuthPromptless = false;
5039
+ /** Vendor clients that may not sign in: one connecting for a read, and one
5040
+ * whose session a read dropped (the next connect replaces it). Their sign-in
5041
+ * uses the saved session or fails. */
5042
+ promptlessSdks = /* @__PURE__ */ new WeakSet();
4994
5043
  connectionGeneration = 0;
4995
5044
  sdkHasConnected = false;
4996
5045
  rpcUrls;
@@ -5171,6 +5220,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5171
5220
  return;
5172
5221
  }
5173
5222
  }
5223
+ if (this.promptlessSdks.has(sdk)) throw this.signInRequired();
5174
5224
  await original();
5175
5225
  const newAddress = internals.walletClient?.account?.address;
5176
5226
  const newChainId = internals.currentChainId ?? 0;
@@ -5216,18 +5266,35 @@ var ZyfaiAgent = class _ZyfaiAgent {
5216
5266
  if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === chainId) return false;
5217
5267
  return readSession(state.walletAddress, chainId) === null;
5218
5268
  }
5219
- /** Light connect: SIWE auth only. Re-auths if chain changed. */
5269
+ /** A read (promptless state) needs a sign-in it may not ask for. */
5270
+ signInRequired() {
5271
+ return new OwneyError(
5272
+ "AGENT_AUTH_FAILED",
5273
+ ZYFAI_SIGN_IN_REQUIRED_MESSAGE,
5274
+ { reason: "ZYFAI_SIGN_IN_REQUIRED" },
5275
+ this.id
5276
+ );
5277
+ }
5278
+ /**
5279
+ * Light connect: SIWE auth only. Re-auths if chain changed. Under a
5280
+ * promptless state (a read) it connects with the saved session only and
5281
+ * never opens the wallet's sign-in prompt: with no saved session it fails
5282
+ * at once with `ZYFAI_SIGN_IN_REQUIRED`.
5283
+ */
5220
5284
  async connectAuth(state, chainId) {
5221
5285
  const validChainId = isValidChainId(chainId);
5222
5286
  const owner = state.walletAddress.toLowerCase();
5223
5287
  const scope = `${owner}:${validChainId}`;
5288
+ const promptless = state.promptless === true;
5224
5289
  if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === validChainId) {
5225
5290
  return;
5226
5291
  }
5227
5292
  if (this.connectAuthPromise && this.connectAuthScope === scope) {
5228
- await this.connectAuthPromise;
5293
+ if (this.connectAuthPromptless && !promptless) await this.connectAuthPromise.catch(() => void 0);
5294
+ else await this.connectAuthPromise;
5229
5295
  return this.connectAuth(state, chainId);
5230
5296
  }
5297
+ if (promptless && readSession(state.walletAddress, validChainId) === null) throw this.signInRequired();
5231
5298
  if (this.sdkHasConnected || this.connectedAddress) this.sdk = this.createSdk();
5232
5299
  this.sdkHasConnected = true;
5233
5300
  const executionSdk = this.sdk;
@@ -5240,7 +5307,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
5240
5307
  const address = await this.connectAccountWithRetry(
5241
5308
  state.provider,
5242
5309
  validChainId,
5243
- executionSdk
5310
+ executionSdk,
5311
+ promptless
5244
5312
  );
5245
5313
  if (generation !== this.connectionGeneration || address.toLowerCase() !== owner)
5246
5314
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while connecting Zyfai.", void 0, this.id);
@@ -5249,12 +5317,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5249
5317
  })();
5250
5318
  this.connectAuthPromise = pending2;
5251
5319
  this.connectAuthScope = scope;
5320
+ this.connectAuthPromptless = promptless;
5252
5321
  try {
5253
5322
  await pending2;
5254
5323
  } finally {
5255
5324
  if (this.connectAuthPromise === pending2) {
5256
5325
  this.connectAuthPromise = null;
5257
5326
  this.connectAuthScope = null;
5327
+ this.connectAuthPromptless = false;
5258
5328
  }
5259
5329
  }
5260
5330
  }
@@ -5267,19 +5337,86 @@ var ZyfaiAgent = class _ZyfaiAgent {
5267
5337
  * which does not separate a revoked JWT from a misconfigured API key; we
5268
5338
  * retry once either way, and if the second attempt still fails the original
5269
5339
  * error propagates.
5340
+ *
5341
+ * `promptless` (a read): the saved session only. The patched
5342
+ * `authenticateUser` will not fall back to the SIWE prompt for this client,
5343
+ * and a refused session is dropped without a retry
5344
+ * (`dropRefusedReadSession`); the next sign-in is the user's.
5270
5345
  */
5271
- async connectAccountWithRetry(provider, chainId, executionSdk = this.sdk) {
5346
+ async connectAccountWithRetry(provider, chainId, executionSdk = this.sdk, promptless = false) {
5347
+ if (promptless) this.promptlessSdks.add(executionSdk);
5272
5348
  try {
5273
- return await executionSdk.connectAccount(provider, chainId);
5349
+ const address = await executionSdk.connectAccount(provider, chainId);
5350
+ this.promptlessSdks.delete(executionSdk);
5351
+ return address;
5274
5352
  } catch (error) {
5275
5353
  const message = error instanceof Error ? error.message : String(error);
5276
5354
  if (!message.toLowerCase().includes("unauthorized")) throw error;
5277
5355
  const internals = executionSdk;
5278
5356
  const address = internals.walletClient?.account?.address;
5357
+ if (promptless) throw this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
5279
5358
  if (address) clearSession(address, chainId);
5280
5359
  return await executionSdk.connectAccount(provider, chainId);
5281
5360
  }
5282
5361
  }
5362
+ setSignInRefusedListener(listener) {
5363
+ this.signInRefusedListener = listener;
5364
+ }
5365
+ /** A saved session was dropped because Zyfai refused it (not during connect). */
5366
+ tellSignInRefused() {
5367
+ try {
5368
+ this.signInRefusedListener?.();
5369
+ } catch {
5370
+ }
5371
+ }
5372
+ /**
5373
+ * Zyfai refused the session a read used (HTTP 401): the one place a read
5374
+ * drops a refused session. The saved session is cleared unless it was
5375
+ * renewed meanwhile, and the client stops using its token and may no longer
5376
+ * sign in, so no read reuses the session or signs in again: reads now need
5377
+ * a sign-in (`ensureReadSession` sees no live session), and the next one is
5378
+ * the user's (connect, deposit, withdraw), on a new client. Returns the
5379
+ * read's error.
5380
+ */
5381
+ dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
5382
+ debugLog("zyfai:auth", "a read's session was refused; dropped without signing in again", { refusal });
5383
+ if (owner && typeof authToken === "string") {
5384
+ let dropped = false;
5385
+ if (readSession(owner, 0)?.token === authToken) {
5386
+ clearSession(owner, 0);
5387
+ dropped = true;
5388
+ }
5389
+ const internals = executionSdk;
5390
+ if (internals.httpClient.authToken === authToken) {
5391
+ dropped = true;
5392
+ internals.httpClient.clearAuthToken();
5393
+ internals.authenticatedUserId = null;
5394
+ this.promptlessSdks.add(executionSdk);
5395
+ if (executionSdk === this.sdk && this.connectedAddress?.toLowerCase() === owner.toLowerCase())
5396
+ this.connectedChainId = null;
5397
+ }
5398
+ if (dropped) this.tellSignInRefused();
5399
+ }
5400
+ return this.signInRequired();
5401
+ }
5402
+ /**
5403
+ * One data call of a read, on `executionSdk`. Under a promptless state a
5404
+ * session Zyfai refuses (`isZyfaiSessionRejected`) is dropped
5405
+ * (`dropRefusedReadSession`) and the read fails with
5406
+ * `ZYFAI_SIGN_IN_REQUIRED`, never signing in again.
5407
+ */
5408
+ async readCall(state, call, executionSdk = this.sdk) {
5409
+ const authToken = executionSdk.httpClient?.authToken;
5410
+ try {
5411
+ return await call();
5412
+ } catch (error) {
5413
+ const message = error instanceof Error ? error.message : String(error);
5414
+ if (state.promptless !== true || error instanceof OwneyError) throw error;
5415
+ if (message.includes(ZYFAI_SIGN_IN_REQUIRED_MESSAGE)) throw this.signInRequired();
5416
+ if (!isZyfaiSessionRejected(message)) throw error;
5417
+ throw this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
5418
+ }
5419
+ }
5283
5420
  /**
5284
5421
  * Reconnect if the Zyfai connection was torn down behind our back: a
5285
5422
  * chain/account switch fires the provider's `accountsChanged` →
@@ -5317,6 +5454,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5317
5454
  internals.httpClient.clearAuthToken();
5318
5455
  internals.authenticatedUserId = null;
5319
5456
  this.connectedChainId = null;
5457
+ this.tellSignInRefused();
5320
5458
  }
5321
5459
  /**
5322
5460
  * Sync newly-available protocols onto an existing user's profile at wallet
@@ -5368,11 +5506,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5368
5506
  * per chain, in parallel) cancel each other's sign-in. Funding keeps
5369
5507
  * `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
5370
5508
  * so a later reconnect cannot leave the caller without an address.
5509
+ * The client reads under a promptless state, so with no live session this
5510
+ * connects from the saved one or fails without a prompt (`connectAuth`).
5371
5511
  */
5372
5512
  async ensureReadSession(state, chainId) {
5373
5513
  const owner = state.walletAddress?.toLowerCase();
5374
5514
  if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
5375
- if (!owner || this.connectedAddress?.toLowerCase() !== owner) await this.connectAuth(state, chainId);
5515
+ if (!owner || this.connectedAddress?.toLowerCase() !== owner || this.connectedChainId === null)
5516
+ await this.connectAuth(state, chainId);
5376
5517
  }
5377
5518
  /** `ensureReadSession`, then the owner it verified, read in the same turn. */
5378
5519
  async connectForRead(state, chainId) {
@@ -5406,7 +5547,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5406
5547
  return pending2;
5407
5548
  }
5408
5549
  // --- IAgent: Connection lifecycle ---
5409
- async disconnect() {
5550
+ async disconnect(options) {
5410
5551
  const executionSdk = this.sdk;
5411
5552
  this.connectionGeneration++;
5412
5553
  this.earningsGeneration++;
@@ -5419,7 +5560,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5419
5560
  this.holdActiveScopes.clear();
5420
5561
  this.pendingRegistrations.clear();
5421
5562
  this.lastGoodEarnings.clear();
5422
- if (this.connectedAddress && this.connectedChainId !== null) {
5563
+ if (!options?.keepSignIns && this.connectedAddress && this.connectedChainId !== null) {
5423
5564
  clearSession(this.connectedAddress, this.connectedChainId);
5424
5565
  }
5425
5566
  this.connectedAddress = null;
@@ -5797,13 +5938,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5797
5938
  Promise.all(
5798
5939
  params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
5799
5940
  try {
5800
- const current = await this.sdk.getSelectedPools(
5941
+ const current = await this.readCall(state, () => this.sdk.getSelectedPools(
5801
5942
  protocolId,
5802
5943
  chainId2
5803
- );
5944
+ ));
5804
5945
  if (current.autoselect) return null;
5805
5946
  return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
5806
- } catch {
5947
+ } catch (error) {
5948
+ if (isSignInFailure(error)) throw error;
5807
5949
  return null;
5808
5950
  }
5809
5951
  })
@@ -5811,9 +5953,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5811
5953
  Promise.all(
5812
5954
  params.assets.map(async (asset) => {
5813
5955
  try {
5814
- const current = await this.sdk.getUserDetails(asset);
5956
+ const current = await this.readCall(state, () => this.sdk.getUserDetails(asset));
5815
5957
  return current.strategy ? { asset, strategy: current.strategy } : null;
5816
- } catch {
5958
+ } catch (error) {
5959
+ if (isSignInFailure(error)) throw error;
5817
5960
  return null;
5818
5961
  }
5819
5962
  })
@@ -7206,7 +7349,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7206
7349
  const requestedAt = Date.now();
7207
7350
  const generation = this.earningsGeneration;
7208
7351
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
7209
- const raw2 = await this.sdk.getPortfolio(this.getAddress());
7352
+ const raw2 = await this.readCall(state, () => this.sdk.getPortfolio(this.getAddress()));
7210
7353
  debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
7211
7354
  const balance = mapBalances(raw2, validChainId, smartWallet);
7212
7355
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
@@ -7268,7 +7411,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7268
7411
  async getEarnings(state, chainId) {
7269
7412
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
7270
7413
  const key2 = this.earningsKey(state, chainId, smartWallet);
7271
- const raw2 = await this.readEarnings(key2, smartWallet);
7414
+ const raw2 = await this.readCall(state, () => this.readEarnings(key2, smartWallet));
7272
7415
  const held = await this.holdEarnings(state, chainId, smartWallet, key2, raw2);
7273
7416
  if (held.active) void this.refreshEarnings(state, chainId).catch(() => void 0);
7274
7417
  return mapEarnings(held.value, smartWallet);
@@ -7419,7 +7562,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7419
7562
  if (existing) return existing;
7420
7563
  const pending2 = (async () => {
7421
7564
  const recent = this.earningsSnapshot;
7422
- const current = recent?.key === key2 && Date.now() - recent.at < 5e3 ? recent.raw : await this.readEarnings(key2, smartWallet);
7565
+ const current = recent?.key === key2 && Date.now() - recent.at < 5e3 ? recent.raw : await this.readCall(state, () => this.readEarnings(key2, smartWallet), executionSdk);
7423
7566
  const lastCheck = current.data.lastCheckTimestamp ? Date.parse(current.data.lastCheckTimestamp) : Number.NaN;
7424
7567
  const mapped = mapEarnings(current, smartWallet);
7425
7568
  const held = await this.holdEarnings(state, chainId, smartWallet, key2, current);
@@ -7433,7 +7576,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7433
7576
  if (isFresh && !negative || !canCalculate)
7434
7577
  return held.active ? mapEarnings(held.value, smartWallet) : mapped;
7435
7578
  this.earningsCalculationAttempts.set(calculationKey, now);
7436
- const earnings = await executionSdk.calculateOnchainEarnings(smartWallet);
7579
+ const earnings = await this.readCall(state, () => executionSdk.calculateOnchainEarnings(smartWallet), executionSdk);
7437
7580
  assertCurrent();
7438
7581
  this.earningsSnapshot = { key: key2, raw: earnings, at: Date.now() };
7439
7582
  const recalculated = await this.holdEarnings(state, chainId, smartWallet, key2, earnings);
@@ -7448,7 +7591,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7448
7591
  }
7449
7592
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
7450
7593
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
7451
- const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
7594
+ const raw2 = await this.readCall(state, () => this.sdk.getDailyApyHistory(smartWallet, days));
7452
7595
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
7453
7596
  const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
7454
7597
  return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
@@ -7458,10 +7601,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
7458
7601
  const start = new Date(
7459
7602
  Date.now() - (DayFilterMapping[days] + 1) * 864e5
7460
7603
  );
7461
- const raw2 = await this.sdk.getDailyEarnings(
7604
+ const raw2 = await this.readCall(state, () => this.sdk.getDailyEarnings(
7462
7605
  smartWallet,
7463
7606
  start.toISOString().slice(0, 10)
7464
- );
7607
+ ));
7465
7608
  return mapDailyEarnings(raw2, chainId, tokenSymbol);
7466
7609
  }
7467
7610
  /**
@@ -7505,7 +7648,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7505
7648
  const matched = [];
7506
7649
  let backendExhausted = false;
7507
7650
  for (let i = 0; i < MAX_BACKEND_CALLS && matched.length < limit; i++) {
7508
- const raw2 = await this.sdk.getHistory(smartWallet, validChainId, {
7651
+ const raw2 = await this.readCall(state, () => this.sdk.getHistory(smartWallet, validChainId, {
7509
7652
  limit: backendPageSize,
7510
7653
  offset,
7511
7654
  fromDate: options?.fromDate,
@@ -7515,7 +7658,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7515
7658
  // relevant entries instead of spending its budget on the other
7516
7659
  // asset's rows and handing back a page that filters to nothing.
7517
7660
  assetType
7518
- });
7661
+ }));
7519
7662
  raw2.data.forEach((entry, idx) => {
7520
7663
  if (entry.chainId === validChainId) {
7521
7664
  matched.push({ entry, rawIdx: offset + idx });
@@ -7551,7 +7694,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7551
7694
  }
7552
7695
  async getUserProfile(state, chainId) {
7553
7696
  await this.ensureReadSession(state, chainId);
7554
- const raw2 = await this.sdk.getUserDetails();
7697
+ const raw2 = await this.readCall(state, () => this.sdk.getUserDetails());
7555
7698
  debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
7556
7699
  asset: "USDC (default \u2014 no asset passed)",
7557
7700
  splitting: raw2.splitting,
@@ -7644,7 +7787,7 @@ var INVALIDATED_KEY_PREFIXES = [
7644
7787
  "owney.yieldseeker.session.v3",
7645
7788
  "owney.yieldseeker.session.v4"
7646
7789
  ];
7647
- var storage3 = () => {
7790
+ var storage4 = () => {
7648
7791
  if (typeof window === "undefined") return null;
7649
7792
  try {
7650
7793
  return window.localStorage;
@@ -7678,7 +7821,7 @@ var isValidSession = (session) => {
7678
7821
  var readYieldseekerSession = (address, chainId) => {
7679
7822
  if (typeof window === "undefined") return null;
7680
7823
  const key2 = buildKey2(address, chainId);
7681
- const store = storage3();
7824
+ const store = storage4();
7682
7825
  clearInvalidatedSessions(store, address, chainId);
7683
7826
  let raw2 = null;
7684
7827
  try {
@@ -7710,7 +7853,7 @@ var writeYieldseekerSession = (address, chainId, token) => {
7710
7853
  if (!isValidSession(session)) return;
7711
7854
  const key2 = buildKey2(address, chainId);
7712
7855
  memorySessions2.set(key2, session);
7713
- const store = storage3();
7856
+ const store = storage4();
7714
7857
  try {
7715
7858
  store?.setItem(key2, JSON.stringify(session));
7716
7859
  } catch {
@@ -7719,7 +7862,7 @@ var writeYieldseekerSession = (address, chainId, token) => {
7719
7862
  var clearYieldseekerSession = (address, chainId) => {
7720
7863
  const key2 = buildKey2(address, chainId);
7721
7864
  memorySessions2.delete(key2);
7722
- const store = storage3();
7865
+ const store = storage4();
7723
7866
  clearInvalidatedSessions(store, address, chainId);
7724
7867
  try {
7725
7868
  store?.removeItem(key2);
@@ -7831,12 +7974,21 @@ var YieldseekerAuth = class {
7831
7974
  return this.getToken(state, chainId);
7832
7975
  }
7833
7976
  /** Drop a proof the provider refused, without signing a new one: a
7834
- * promptless read cannot renew it, and must stop offering it. */
7977
+ * promptless read cannot renew it, and must stop offering it. Returns
7978
+ * whether it dropped anything: false when the proof was already dropped or
7979
+ * replaced meanwhile. */
7835
7980
  discardToken(state, chainId, rejectedToken) {
7836
7981
  const key2 = this.key(state, chainId);
7837
- if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
7838
- if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken)
7982
+ let dropped = false;
7983
+ if (this.tokens.get(key2) === rejectedToken) {
7984
+ this.tokens.delete(key2);
7985
+ dropped = true;
7986
+ }
7987
+ if (readYieldseekerSession(state.walletAddress, chainId) === rejectedToken) {
7839
7988
  clearYieldseekerSession(state.walletAddress, chainId);
7989
+ dropped = true;
7990
+ }
7991
+ return dropped;
7840
7992
  }
7841
7993
  isReusable(token, state, chainId) {
7842
7994
  try {
@@ -7852,6 +8004,12 @@ var YieldseekerAuth = class {
7852
8004
  return false;
7853
8005
  }
7854
8006
  }
8007
+ /** Drops what this instance holds in memory; saved sign-ins in storage stay. */
8008
+ forgetInMemory() {
8009
+ this.tokens.clear();
8010
+ this.pending.clear();
8011
+ this.scopes.clear();
8012
+ }
7855
8013
  clear(state, chainId) {
7856
8014
  if (!state || chainId === void 0) {
7857
8015
  for (const scope of this.scopes.values()) {
@@ -7896,9 +8054,9 @@ var YieldseekerAuth = class {
7896
8054
 
7897
8055
  // src/agents/yieldseeker/yieldseeker.identity-cache.ts
7898
8056
  var KEY_PREFIX3 = "owney.yieldseeker.identity.v1";
7899
- var YIELDSEEKER_IDENTITY_TTL_MS = 24 * 60 * 60 * 1e3;
8057
+ var YIELDSEEKER_IDENTITY_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
7900
8058
  var memoryIdentities = /* @__PURE__ */ new Map();
7901
- var storage4 = () => {
8059
+ var storage5 = () => {
7902
8060
  if (typeof window === "undefined") return null;
7903
8061
  try {
7904
8062
  return window.localStorage;
@@ -7915,7 +8073,7 @@ function valid(value, walletAddress, chainId, now) {
7915
8073
  function readYieldseekerIdentity(walletAddress, chainId, now = Date.now()) {
7916
8074
  if (typeof window === "undefined") return null;
7917
8075
  const key2 = keyFor(walletAddress, chainId);
7918
- const store = storage4();
8076
+ const store = storage5();
7919
8077
  let parsed = null;
7920
8078
  try {
7921
8079
  const raw2 = store?.getItem(key2);
@@ -7947,7 +8105,7 @@ function writeYieldseekerIdentity(walletAddress, chainId, userId, now = Date.now
7947
8105
  const key2 = keyFor(walletAddress, chainId);
7948
8106
  memoryIdentities.set(key2, identity);
7949
8107
  try {
7950
- storage4()?.setItem(key2, JSON.stringify(identity));
8108
+ storage5()?.setItem(key2, JSON.stringify(identity));
7951
8109
  } catch {
7952
8110
  }
7953
8111
  }
@@ -7955,9 +8113,41 @@ function clearYieldseekerIdentity(walletAddress, chainId) {
7955
8113
  const key2 = keyFor(walletAddress, chainId);
7956
8114
  memoryIdentities.delete(key2);
7957
8115
  try {
7958
- storage4()?.removeItem(key2);
8116
+ storage5()?.removeItem(key2);
8117
+ } catch {
8118
+ }
8119
+ }
8120
+
8121
+ // src/agents/yieldseeker/yieldseeker.login-cooldown.ts
8122
+ var KEY2 = "owney.yieldseeker.login-cooldown.v1";
8123
+ var YIELDSEEKER_LOGIN_COOLDOWN_FLOOR_MS = 3 * 6e4;
8124
+ var memoryUntil = 0;
8125
+ var storage6 = () => {
8126
+ if (typeof window === "undefined") return null;
8127
+ try {
8128
+ return window.localStorage;
8129
+ } catch {
8130
+ return null;
8131
+ }
8132
+ };
8133
+ function readYieldseekerLoginCooldown(now = Date.now()) {
8134
+ let until = memoryUntil;
8135
+ try {
8136
+ const stored = Number(storage6()?.getItem(KEY2));
8137
+ if (Number.isSafeInteger(stored) && stored > until) until = stored;
8138
+ } catch {
8139
+ }
8140
+ return until > now ? until : void 0;
8141
+ }
8142
+ function startYieldseekerLoginCooldown(retryAfterMs, now = Date.now()) {
8143
+ const wait3 = Math.max(YIELDSEEKER_LOGIN_COOLDOWN_FLOOR_MS, Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
8144
+ const until = Math.max(readYieldseekerLoginCooldown(now) ?? 0, now + wait3);
8145
+ memoryUntil = until;
8146
+ try {
8147
+ storage6()?.setItem(KEY2, String(until));
7959
8148
  } catch {
7960
8149
  }
8150
+ return until;
7961
8151
  }
7962
8152
 
7963
8153
  // src/agents/yieldseeker/yieldseeker.client.ts
@@ -9613,6 +9803,12 @@ function generateYieldseekerUsername() {
9613
9803
  const suffix = globalThis.crypto.randomUUID().replaceAll("-", "").slice(0, YIELDSEEKER_USERNAME_RANDOM_LENGTH).toLowerCase();
9614
9804
  return `${YIELDSEEKER_USERNAME_PREFIX}${suffix}`;
9615
9805
  }
9806
+ function isSignInRateLimit(error) {
9807
+ return error instanceof YieldseekerApiError && error.status === 429;
9808
+ }
9809
+ function isWalletAlreadyRegistered(error) {
9810
+ return error instanceof YieldseekerApiError && error.providerCode.toUpperCase() === "USER_WALLET_EXISTS";
9811
+ }
9616
9812
  function isUsernameConflict(error) {
9617
9813
  if (!(error instanceof YieldseekerApiError)) return false;
9618
9814
  const code = error.providerCode.toUpperCase();
@@ -9760,6 +9956,15 @@ var YieldseekerAgent = class {
9760
9956
  balanceContexts = /* @__PURE__ */ new WeakMap();
9761
9957
  balanceVaults = /* @__PURE__ */ new Map();
9762
9958
  users = /* @__PURE__ */ new Map();
9959
+ /**
9960
+ * Agent wallets (lowercase) this page started releasing vault funds from for
9961
+ * a withdrawal, and when. Until the payout is done the released money sits
9962
+ * in the agent wallet, so no deposit notice may go out (it would be
9963
+ * reinvested). The ledger shows the same once it lists the withdrawal.
9964
+ */
9965
+ releasingWallets = /* @__PURE__ */ new Map();
9966
+ /** One login (and, for a new wallet, one create) per wallet and chain at a time. */
9967
+ pendingUsers = /* @__PURE__ */ new Map();
9763
9968
  pendingAgents = /* @__PURE__ */ new Map();
9764
9969
  pendingWalletContexts = /* @__PURE__ */ new Map();
9765
9970
  readCache = /* @__PURE__ */ new Map();
@@ -9786,6 +9991,7 @@ var YieldseekerAgent = class {
9786
9991
  // or while the ledger read is null, settlement and earnings are as before.
9787
9992
  ledgerAccess;
9788
9993
  accountRefusedListener;
9994
+ signInRefusedListener;
9789
9995
  ledgerReads = /* @__PURE__ */ new Map();
9790
9996
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9791
9997
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -10081,16 +10287,16 @@ var YieldseekerAgent = class {
10081
10287
  this.rememberWalletStatus(versionKey, status);
10082
10288
  return { txHash: hash2, status };
10083
10289
  };
10084
- let storage9;
10290
+ let storage11;
10085
10291
  try {
10086
- storage9 = typeof window === "undefined" ? void 0 : window.localStorage;
10292
+ storage11 = typeof window === "undefined" ? void 0 : window.localStorage;
10087
10293
  } catch {
10088
- storage9 = void 0;
10294
+ storage11 = void 0;
10089
10295
  }
10090
10296
  const clearRecordedUpgrade = () => {
10091
10297
  this.pendingUpgrades.delete(pendingKey2);
10092
10298
  try {
10093
- storage9?.removeItem(pendingKey2);
10299
+ storage11?.removeItem(pendingKey2);
10094
10300
  } catch {
10095
10301
  this.pendingUpgrades.set(pendingKey2, null);
10096
10302
  }
@@ -10113,7 +10319,7 @@ var YieldseekerAgent = class {
10113
10319
  throw pendingUpgrade(hash2);
10114
10320
  }
10115
10321
  };
10116
- if (!storage9 && (gasMode === "sponsored" || before.ownerPath === "smart"))
10322
+ if (!storage11 && (gasMode === "sponsored" || before.ownerPath === "smart"))
10117
10323
  throw new OwneyError(
10118
10324
  "SPONSOR_REQUEST_FAILED",
10119
10325
  "Upgrade status cannot be saved in this browser.",
@@ -10122,14 +10328,14 @@ var YieldseekerAgent = class {
10122
10328
  );
10123
10329
  let prior = null;
10124
10330
  try {
10125
- const saved = this.pendingUpgrades.has(pendingKey2) ? JSON.stringify(this.pendingUpgrades.get(pendingKey2)) : storage9?.getItem(pendingKey2);
10331
+ const saved = this.pendingUpgrades.has(pendingKey2) ? JSON.stringify(this.pendingUpgrades.get(pendingKey2)) : storage11?.getItem(pendingKey2);
10126
10332
  try {
10127
10333
  prior = JSON.parse(saved ?? "null");
10128
10334
  } catch {
10129
10335
  prior = { callsId: void 0 };
10130
10336
  }
10131
10337
  } catch {
10132
- if (gasMode === "paid" && before.ownerPath === "eoa") storage9 = void 0;
10338
+ if (gasMode === "paid" && before.ownerPath === "eoa") storage11 = void 0;
10133
10339
  else throw new OwneyError(
10134
10340
  "SPONSOR_REQUEST_FAILED",
10135
10341
  "Upgrade status cannot be read in this browser.",
@@ -10223,9 +10429,9 @@ var YieldseekerAgent = class {
10223
10429
  asset: YIELDSEEKER_ASSET_METADATA[asset].address,
10224
10430
  callData: data,
10225
10431
  onPending: (pending2) => {
10226
- const current = this.pendingUpgrades.has(pendingKey2) ? this.pendingUpgrades.get(pendingKey2) : JSON.parse(storage9.getItem(pendingKey2) ?? "null");
10432
+ const current = this.pendingUpgrades.has(pendingKey2) ? this.pendingUpgrades.get(pendingKey2) : JSON.parse(storage11.getItem(pendingKey2) ?? "null");
10227
10433
  const next = { startedAt: Date.now(), ...current, ...pending2 };
10228
- storage9.setItem(pendingKey2, JSON.stringify(next));
10434
+ storage11.setItem(pendingKey2, JSON.stringify(next));
10229
10435
  this.pendingUpgrades.delete(pendingKey2);
10230
10436
  }
10231
10437
  });
@@ -10249,8 +10455,8 @@ var YieldseekerAgent = class {
10249
10455
  const pending2 = { txHash: hash2 };
10250
10456
  this.pendingUpgrades.set(pendingKey2, pending2);
10251
10457
  try {
10252
- if (storage9) {
10253
- storage9.setItem(pendingKey2, JSON.stringify(pending2));
10458
+ if (storage11) {
10459
+ storage11.setItem(pendingKey2, JSON.stringify(pending2));
10254
10460
  this.pendingUpgrades.delete(pendingKey2);
10255
10461
  }
10256
10462
  } catch {
@@ -10271,14 +10477,18 @@ var YieldseekerAgent = class {
10271
10477
  clearRecordedUpgrade();
10272
10478
  return confirmed;
10273
10479
  }
10274
- async disconnect() {
10480
+ async disconnect(options) {
10275
10481
  this.withdrawalVersionCache.clear();
10276
10482
  this.pendingWalletStatus.clear();
10277
10483
  this.readGeneration += 1;
10278
- this.auth.clear();
10279
- for (const key2 of this.users.keys()) {
10280
- const [walletAddress, chainId] = key2.split(":");
10281
- clearYieldseekerIdentity(walletAddress, Number(chainId));
10484
+ if (options?.keepSignIns) {
10485
+ this.auth.forgetInMemory();
10486
+ } else {
10487
+ this.auth.clear();
10488
+ for (const key2 of this.users.keys()) {
10489
+ const [walletAddress, chainId] = key2.split(":");
10490
+ clearYieldseekerIdentity(walletAddress, Number(chainId));
10491
+ }
10282
10492
  }
10283
10493
  this.users.clear();
10284
10494
  this.agentContexts.clear();
@@ -10872,6 +11082,7 @@ var YieldseekerAgent = class {
10872
11082
  const unwind = async (position2, assetsRaw) => {
10873
11083
  this.assertSession(generation, chainId, asset);
10874
11084
  assertOperation?.();
11085
+ this.releasingWallets.set(context.wallet.walletAddress.toLowerCase(), Date.now());
10875
11086
  let unwindTransactionHash;
10876
11087
  try {
10877
11088
  const response = await this.walletRequest(
@@ -11667,7 +11878,9 @@ var YieldseekerAgent = class {
11667
11878
  * left idle. While it has not, Yieldseeker is told again, up to
11668
11879
  * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
11669
11880
  * limit) is sent again after a wait. Within an hour of a withdrawal it is
11670
- * told once, since nothing can move yet. Uses the agent this session already
11881
+ * told once, since nothing can move yet. While a withdrawal from the agent
11882
+ * wallet is under way it is not told at all: its released funds wait in that
11883
+ * wallet for the payout, and a notice would reinvest them (ROUT-790). Uses the agent this session already
11671
11884
  * knows for the asset and the saved sign-in only: never prompts, never
11672
11885
  * throws. Each call is reported through `onNotice`.
11673
11886
  */
@@ -11684,6 +11897,8 @@ var YieldseekerAgent = class {
11684
11897
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11685
11898
  const generation = this.readGeneration;
11686
11899
  const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11900
+ if (await this.withdrawalUnderWay(state, chainId, slotAsset, context))
11901
+ return { notified: false, reason: "WITHDRAWAL_IN_PROGRESS" };
11687
11902
  const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11688
11903
  let notified = false;
11689
11904
  let reason = "NOT_ALLOCATED";
@@ -11774,6 +11989,19 @@ var YieldseekerAgent = class {
11774
11989
  * confirmed withdrawal, if that is still ahead; null when there was none in
11775
11990
  * the last hour or the ledger cannot say.
11776
11991
  */
11992
+ /**
11993
+ * A withdrawal from this agent wallet that has started but not finished,
11994
+ * within the last hour: released by this page, or listed on the ledger with
11995
+ * the agent's leg still created, submitted or unknown. Older unfinished rows
11996
+ * do not count, so a stuck record cannot hold deposits back for good.
11997
+ */
11998
+ async withdrawalUnderWay(state, chainId, asset, context) {
11999
+ const wallet = context.wallet.walletAddress.toLowerCase();
12000
+ const since = Date.now() - YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
12001
+ if ((this.releasingWallets.get(wallet) ?? 0) > since) return true;
12002
+ const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
12003
+ return (rows ?? []).some((row) => (row.kind === "withdraw" || row.kind === "withdraw_swap") && Date.parse(row.createdAt) > since && row.legs.some((leg) => leg.legKey === `agent:${this.id}` && !leg.closed && ["created", "submitted", "unknown"].includes(leg.status) && (leg.agentWallet === null || leg.agentWallet.toLowerCase() === wallet)));
12004
+ }
11777
12005
  async withdrawalCooldownEnd(state, chainId, asset, context) {
11778
12006
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11779
12007
  const wallet = context.wallet.walletAddress.toLowerCase();
@@ -12889,6 +13117,29 @@ var YieldseekerAgent = class {
12889
13117
  this.users.set(key2, persisted);
12890
13118
  return persisted;
12891
13119
  }
13120
+ const pending2 = this.pendingUsers.get(key2);
13121
+ if (pending2) return pending2;
13122
+ const request2 = this.signInUser(state, chainId);
13123
+ this.pendingUsers.set(key2, request2);
13124
+ try {
13125
+ return await request2;
13126
+ } finally {
13127
+ if (this.pendingUsers.get(key2) === request2) this.pendingUsers.delete(key2);
13128
+ }
13129
+ }
13130
+ /**
13131
+ * `login-with-wallet`, and `POST /users` for a wallet without an account.
13132
+ * Both draw on Yieldseeker's per-IP sign-in allowance, which all our users
13133
+ * share: while a 429's pause lasts nothing is sent, and a new 429 starts one.
13134
+ */
13135
+ async signInUser(state, chainId) {
13136
+ const key2 = this.userKey(state, chainId);
13137
+ const pausedUntil = readYieldseekerLoginCooldown();
13138
+ if (pausedUntil !== void 0) throw this.signInRateLimited(pausedUntil);
13139
+ const limited = (error) => {
13140
+ const retryAfter = error instanceof YieldseekerApiError ? rateLimitDelay({ status: error.status, fields: error.responseFields }) : rateLimitDelay(error);
13141
+ throw this.signInRateLimited(startYieldseekerLoginCooldown(retryAfter));
13142
+ };
12892
13143
  const walletAddress = (0, import_viem17.getAddress)(state.walletAddress);
12893
13144
  const generation = this.readGeneration;
12894
13145
  let user = null;
@@ -12906,11 +13157,13 @@ var YieldseekerAgent = class {
12906
13157
  });
12907
13158
  }
12908
13159
  } catch (error) {
13160
+ if (isSignInRateLimit(error)) limited(error);
12909
13161
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
12910
13162
  if (error instanceof OwneyError) throw error;
12911
13163
  throw this.mapRequestFailure(error);
12912
13164
  }
12913
13165
  let created;
13166
+ let registeredMeanwhile = false;
12914
13167
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
12915
13168
  try {
12916
13169
  created = await this.providerRequest(
@@ -12927,12 +13180,32 @@ var YieldseekerAgent = class {
12927
13180
  );
12928
13181
  break;
12929
13182
  } catch (createError) {
13183
+ if (isSignInRateLimit(createError)) limited(createError);
13184
+ if (isWalletAlreadyRegistered(createError)) {
13185
+ registeredMeanwhile = true;
13186
+ break;
13187
+ }
12930
13188
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
12931
13189
  if (canRetry) continue;
12932
13190
  throw this.mapRequestFailure(createError);
12933
13191
  }
12934
13192
  }
12935
13193
  user = created?.user ?? null;
13194
+ if (registeredMeanwhile) {
13195
+ try {
13196
+ const login = await this.providerRequest(
13197
+ state,
13198
+ chainId,
13199
+ "/users/login-with-wallet",
13200
+ { method: "POST", body: { walletAddress } }
13201
+ );
13202
+ user = login?.user ?? null;
13203
+ } catch (loginError) {
13204
+ if (isSignInRateLimit(loginError)) limited(loginError);
13205
+ if (loginError instanceof OwneyError) throw loginError;
13206
+ throw this.mapRequestFailure(loginError);
13207
+ }
13208
+ }
12936
13209
  }
12937
13210
  if (!user || !/^[a-zA-Z0-9_-]{1,128}$/.test(user.userId)) {
12938
13211
  throw this.invalidResponse("wallet identity");
@@ -12943,6 +13216,19 @@ var YieldseekerAgent = class {
12943
13216
  writeYieldseekerIdentity(state.walletAddress, chainId, resolved.userId);
12944
13217
  return resolved;
12945
13218
  }
13219
+ signInRateLimited(until) {
13220
+ return new OwneyError(
13221
+ "AGENT_RATE_LIMITED",
13222
+ "Too many sign-in attempts right now. Please wait before trying again.",
13223
+ {
13224
+ reason: "YIELDSEEKER_SIGN_IN_RATE_LIMITED",
13225
+ statusCode: 429,
13226
+ retryAt: until,
13227
+ retryAfterSeconds: Math.max(0, Math.ceil((until - Date.now()) / 1e3))
13228
+ },
13229
+ this.id
13230
+ );
13231
+ }
12946
13232
  forgetUser(state, chainId) {
12947
13233
  this.users.delete(this.userKey(state, chainId));
12948
13234
  clearYieldseekerIdentity(state.walletAddress, chainId);
@@ -13424,6 +13710,9 @@ var YieldseekerAgent = class {
13424
13710
  setAccountRefusedListener(listener) {
13425
13711
  this.accountRefusedListener = listener;
13426
13712
  }
13713
+ setSignInRefusedListener(listener) {
13714
+ this.signInRefusedListener = listener;
13715
+ }
13427
13716
  setFundingLedgerAccess(access) {
13428
13717
  this.ledgerAccess = access;
13429
13718
  this.ledgerReads.clear();
@@ -13817,7 +14106,13 @@ var YieldseekerAgent = class {
13817
14106
  if (error.providerCode === "NO_USER") throw error;
13818
14107
  if (!error.isAuthenticationError) throw error;
13819
14108
  if (promptless) {
13820
- this.auth.discardToken(state, chainId, signature);
14109
+ const dropped = this.auth.discardToken(state, chainId, signature);
14110
+ if (dropped) {
14111
+ try {
14112
+ this.signInRefusedListener?.();
14113
+ } catch {
14114
+ }
14115
+ }
13821
14116
  throw error;
13822
14117
  }
13823
14118
  signature = await this.auth.refreshToken(state, chainId, signature);
@@ -14930,7 +15225,7 @@ function runSameChainOrder(deps, options) {
14930
15225
 
14931
15226
  // src/lib/swap/swap.secret-store.ts
14932
15227
  var KEY_PREFIX4 = "owney.swap.order";
14933
- var storage5 = () => {
15228
+ var storage7 = () => {
14934
15229
  if (typeof window === "undefined") return null;
14935
15230
  try {
14936
15231
  return window.localStorage;
@@ -14940,7 +15235,7 @@ var storage5 = () => {
14940
15235
  };
14941
15236
  var keyFor2 = (orderHash) => `${KEY_PREFIX4}.${orderHash}`;
14942
15237
  function saveOrder(order) {
14943
- const store = storage5();
15238
+ const store = storage7();
14944
15239
  if (!store) return false;
14945
15240
  try {
14946
15241
  const value = JSON.stringify(order);
@@ -14951,7 +15246,7 @@ function saveOrder(order) {
14951
15246
  }
14952
15247
  }
14953
15248
  function loadOrder(orderHash) {
14954
- const store = storage5();
15249
+ const store = storage7();
14955
15250
  if (!store) return null;
14956
15251
  try {
14957
15252
  const raw2 = store.getItem(keyFor2(orderHash));
@@ -14966,7 +15261,7 @@ function loadOrder(orderHash) {
14966
15261
  }
14967
15262
  }
14968
15263
  function clearOrder(orderHash) {
14969
- const store = storage5();
15264
+ const store = storage7();
14970
15265
  if (!store) return;
14971
15266
  try {
14972
15267
  store.removeItem(keyFor2(orderHash));
@@ -14974,7 +15269,7 @@ function clearOrder(orderHash) {
14974
15269
  }
14975
15270
  }
14976
15271
  function listOrders(_now = Date.now()) {
14977
- const store = storage5();
15272
+ const store = storage7();
14978
15273
  if (!store) return [];
14979
15274
  const out = [];
14980
15275
  try {
@@ -15782,7 +16077,7 @@ async function buildErc2612Permit(reads, input) {
15782
16077
  // src/lib/swap/swap.withdraw-swap.ts
15783
16078
  var KEY_PREFIX5 = "owney.swap.withdraw";
15784
16079
  var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
15785
- var storage6 = () => {
16080
+ var storage8 = () => {
15786
16081
  if (typeof window === "undefined") return null;
15787
16082
  try {
15788
16083
  return window.localStorage;
@@ -15807,7 +16102,7 @@ var notify = () => {
15807
16102
  }
15808
16103
  };
15809
16104
  function saveWithdrawSwap(record2) {
15810
- const store = storage6();
16105
+ const store = storage8();
15811
16106
  if (!store) return false;
15812
16107
  try {
15813
16108
  const current = store.getItem(keyFor3(record2.orderHash));
@@ -15821,7 +16116,7 @@ function saveWithdrawSwap(record2) {
15821
16116
  return true;
15822
16117
  }
15823
16118
  function updateWithdrawSwap(orderHash, patch) {
15824
- const store = storage6();
16119
+ const store = storage8();
15825
16120
  if (!store) return;
15826
16121
  try {
15827
16122
  const raw2 = store.getItem(keyFor3(orderHash));
@@ -15838,7 +16133,7 @@ function updateWithdrawSwap(orderHash, patch) {
15838
16133
  notify();
15839
16134
  }
15840
16135
  function clearWithdrawSwap(orderHash) {
15841
- const store = storage6();
16136
+ const store = storage8();
15842
16137
  if (!store) return;
15843
16138
  try {
15844
16139
  const raw2 = store.getItem(keyFor3(orderHash));
@@ -15852,7 +16147,7 @@ function clearWithdrawSwap(orderHash) {
15852
16147
  notify();
15853
16148
  }
15854
16149
  function listWithdrawSwaps(now = Date.now(), includeDismissed = false) {
15855
- const store = storage6();
16150
+ const store = storage8();
15856
16151
  if (!store) return [];
15857
16152
  const out = [];
15858
16153
  try {
@@ -15889,7 +16184,7 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
15889
16184
  // src/lib/swap/swap.pending-deposit.ts
15890
16185
  var KEY_PREFIX6 = "owney.swap.pending-deposit";
15891
16186
  var MAX_AGE_MS2 = 24 * 60 * 60 * 1e3;
15892
- var storage7 = () => {
16187
+ var storage9 = () => {
15893
16188
  if (typeof window === "undefined") return null;
15894
16189
  try {
15895
16190
  return window.localStorage;
@@ -15899,7 +16194,7 @@ var storage7 = () => {
15899
16194
  };
15900
16195
  var keyFor4 = (id) => `${KEY_PREFIX6}.${id}`;
15901
16196
  function savePendingDeposit(entry) {
15902
- const store = storage7();
16197
+ const store = storage9();
15903
16198
  if (!store) return;
15904
16199
  try {
15905
16200
  store.setItem(keyFor4(entry.id), JSON.stringify(entry));
@@ -15908,7 +16203,7 @@ function savePendingDeposit(entry) {
15908
16203
  }
15909
16204
  }
15910
16205
  function clearPendingDeposit(id) {
15911
- const store = storage7();
16206
+ const store = storage9();
15912
16207
  if (!store) return;
15913
16208
  try {
15914
16209
  store.removeItem(keyFor4(id));
@@ -15917,7 +16212,7 @@ function clearPendingDeposit(id) {
15917
16212
  }
15918
16213
  }
15919
16214
  function listPendingDeposits(now = Date.now()) {
15920
- const store = storage7();
16215
+ const store = storage9();
15921
16216
  if (!store) return [];
15922
16217
  const out = [];
15923
16218
  try {
@@ -17415,15 +17710,8 @@ var OwneySDK = class {
17415
17710
  */
17416
17711
  disabledAgents = /* @__PURE__ */ new Set();
17417
17712
  accountRefusedListeners = /* @__PURE__ */ new Set();
17713
+ signInRefusedListeners = /* @__PURE__ */ new Set();
17418
17714
  signInProgressListeners = /* @__PURE__ */ new Set();
17419
- /**
17420
- * Agents whose sign-in the user cancelled this session (the wallet rejected
17421
- * the prompt), keyed by chain. Until the app ends the session they are read
17422
- * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
17423
- * the user cancelled. A later successful activation of the agent removes
17424
- * it, and `disconnect()` or a different wallet's `connect()` clears the map.
17425
- */
17426
- declinedSignIns = /* @__PURE__ */ new Map();
17427
17715
  state = null;
17428
17716
  connectionRevision = 0;
17429
17717
  disconnectingAgents = null;
@@ -17630,7 +17918,7 @@ var OwneySDK = class {
17630
17918
  read: async () => {
17631
17919
  const state = this.state;
17632
17920
  if (!state || state.walletAddress.toLowerCase() !== owner) return null;
17633
- const sample = await agent.providerEarningsSample(state, evidence.chainId);
17921
+ const sample = await agent.providerEarningsSample(this.readStateFor(state), evidence.chainId);
17634
17922
  return sample ? { ...sample, observedAt: (/* @__PURE__ */ new Date()).toISOString() } : null;
17635
17923
  },
17636
17924
  emit: (data) => op.event?.("provider.sample", data)
@@ -17649,6 +17937,19 @@ var OwneySDK = class {
17649
17937
  this.accountRefusedListeners.delete(listener);
17650
17938
  };
17651
17939
  }
17940
+ /**
17941
+ * Listens for an agent dropping a saved sign-in its server refused, outside
17942
+ * connect (a read or a withdrawal found it refused). The agent will not
17943
+ * sign in again by itself; the next sign-in is the user's. Not fired where a
17944
+ * refused sign-in is renewed (connect, deposit). Returns the unsubscribe
17945
+ * function.
17946
+ */
17947
+ onSignInRefused(listener) {
17948
+ this.signInRefusedListeners.add(listener);
17949
+ return () => {
17950
+ this.signInRefusedListeners.delete(listener);
17951
+ };
17952
+ }
17652
17953
  /**
17653
17954
  * Listens for the sign-ins a connect asks for (`SignInProgress`): which
17654
17955
  * agents will ask the wallet to sign in, and each one as it starts and ends,
@@ -17662,6 +17963,28 @@ var OwneySDK = class {
17662
17963
  this.signInProgressListeners.delete(listener);
17663
17964
  };
17664
17965
  }
17966
+ /**
17967
+ * The agents that would ask the wallet to sign in on `chainId` right now:
17968
+ * enabled agents on that chain whose `needsSignIn` says yes. One with no
17969
+ * such check counts as no; one that throws counts as yes, so an unknown
17970
+ * answer never lets the app retry quietly into a prompt. Never prompts and
17971
+ * never calls the network. Empty before connect.
17972
+ */
17973
+ signInsNeeded(chainId) {
17974
+ const state = this.state;
17975
+ if (state === null) return [];
17976
+ const needed = [];
17977
+ for (const [id, agent] of this.agents) {
17978
+ if (this.isAgentDisabled(id)) continue;
17979
+ if (!agent.supportedChainIds.includes(chainId)) continue;
17980
+ try {
17981
+ if (agent.needsSignIn?.(state, chainId) === true) needed.push(id);
17982
+ } catch {
17983
+ needed.push(id);
17984
+ }
17985
+ }
17986
+ return needed;
17987
+ }
17665
17988
  /**
17666
17989
  * The sign-ins this connect asks for: the agents whose `needsSignIn` says
17667
17990
  * yes now (one that throws counts as no). Each is announced at its first
@@ -17719,6 +18042,14 @@ var OwneySDK = class {
17719
18042
  }
17720
18043
  }
17721
18044
  });
18045
+ agent.setSignInRefusedListener?.(() => {
18046
+ for (const listener of [...this.signInRefusedListeners]) {
18047
+ try {
18048
+ listener(agent.id);
18049
+ } catch {
18050
+ }
18051
+ }
18052
+ });
17722
18053
  }
17723
18054
  /**
17724
18055
  * Funding-ledger read access handed to agents for earnings holds. Reads only
@@ -17798,7 +18129,6 @@ var OwneySDK = class {
17798
18129
  }
17799
18130
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
17800
18131
  this.clearConnectionState();
17801
- if (replacingOwner) this.declinedSignIns.clear();
17802
18132
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
17803
18133
  if (revision !== this.connectionRevision)
17804
18134
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
@@ -17812,11 +18142,10 @@ var OwneySDK = class {
17812
18142
  * Disconnect from all agents and clear connection state.
17813
18143
  * After calling this, `connect()` must be called again before using agent methods.
17814
18144
  */
17815
- async disconnect() {
18145
+ async disconnect(options) {
17816
18146
  ++this.connectionRevision;
17817
18147
  this.clearConnectionState();
17818
- this.declinedSignIns.clear();
17819
- await this.disconnectAgents();
18148
+ await this.disconnectAgents(options);
17820
18149
  }
17821
18150
  clearConnectionState() {
17822
18151
  this.state = null;
@@ -17828,9 +18157,9 @@ var OwneySDK = class {
17828
18157
  this.cachedWethSponsoredCallback = null;
17829
18158
  this.cachedSponsoredCallsCallbacks.clear();
17830
18159
  }
17831
- disconnectAgents() {
18160
+ disconnectAgents(options) {
17832
18161
  if (this.disconnectingAgents) return this.disconnectingAgents;
17833
- const pending2 = Promise.allSettled([...this.agents.values()].map(async (agent) => agent.disconnect())).then((results) => {
18162
+ const pending2 = Promise.allSettled([...this.agents.values()].map(async (agent) => agent.disconnect(options))).then((results) => {
17834
18163
  const failure = results.find((result) => result.status === "rejected");
17835
18164
  if (failure?.status === "rejected") throw failure.reason;
17836
18165
  });
@@ -17871,17 +18200,14 @@ var OwneySDK = class {
17871
18200
  return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
17872
18201
  }
17873
18202
  /**
17874
- * The state an agent's reads use. An agent whose sign-in the user cancelled
17875
- * on the connection chain this session is read from a saved sign-in only,
17876
- * as `offChainPortfolioAgents` reads: a read that would need a wallet
17877
- * prompt fails for that agent instead of reopening the prompt the user
17878
- * cancelled. A later successful activation of the agent, or `disconnect()`,
17879
- * lifts it.
18203
+ * The state every agent read uses: promptless, so a read uses a saved
18204
+ * sign-in only and never opens a wallet prompt. A read that would need one
18205
+ * fails for that agent instead; the app keeps the last known value and
18206
+ * retries later. Only connect/activation and user actions (deposit,
18207
+ * withdraw) may ask the wallet to sign in, and they use the plain state.
17880
18208
  */
17881
- readStateFor(agentId, state) {
17882
- const chainId = state.chainId;
17883
- if (state.promptless === true || chainId === null) return state;
17884
- return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
18209
+ readStateFor(state) {
18210
+ return state.promptless === true ? state : { ...state, promptless: true };
17885
18211
  }
17886
18212
  /**
17887
18213
  * Check if the SDK has an active connection state.
@@ -18105,7 +18431,7 @@ var OwneySDK = class {
18105
18431
  }
18106
18432
  /** The active agents, each with the state its reads use (`readStateFor`). */
18107
18433
  activeReads(state, chainId) {
18108
- return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(id, state), chainId }));
18434
+ return [...this.getActiveAgents()].map(([id, agent]) => ({ id, agent, state: this.readStateFor(state), chainId }));
18109
18435
  }
18110
18436
  /**
18111
18437
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
@@ -18391,12 +18717,7 @@ var OwneySDK = class {
18391
18717
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
18392
18718
  });
18393
18719
  firstError = error;
18394
- if (this.isUserRejectedWithdrawal(error)) {
18395
- walletRejected = true;
18396
- const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
18397
- declined.add(agent.id);
18398
- this.declinedSignIns.set(chainId, declined);
18399
- }
18720
+ if (this.isUserRejectedWithdrawal(error)) walletRejected = true;
18400
18721
  };
18401
18722
  for (const agent of agents) {
18402
18723
  if (!agent.checkAccount) continue;
@@ -18423,7 +18744,6 @@ var OwneySDK = class {
18423
18744
  await this.applyOrgPolicyTo(agent, state, chainId);
18424
18745
  this.assertActivationSession(state);
18425
18746
  activatedAgentIds.push(agent.id);
18426
- this.declinedSignIns.get(chainId)?.delete(agent.id);
18427
18747
  } catch (error) {
18428
18748
  recordFailure(agent, error);
18429
18749
  break;
@@ -19157,7 +19477,8 @@ var OwneySDK = class {
19157
19477
  }
19158
19478
  /** Revalidate a saved transfer against the authenticated account and actual receipt. */
19159
19479
  async inspectFunding(evidence, direction, options = {}) {
19160
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19480
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19481
+ const state = this.readStateFor(connection);
19161
19482
  if (state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase() || !evidence.txHash)
19162
19483
  throw new OwneyError("AGENT_API_ERROR", "Funding evidence does not match the connected account.");
19163
19484
  const agent = this.getAgent(evidence.agentId);
@@ -19270,8 +19591,9 @@ var OwneySDK = class {
19270
19591
  const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
19271
19592
  if (!agent?.depositConfirmed || !movement) return;
19272
19593
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
19273
- if (this.announcedDeposits.has(key2)) return;
19594
+ if (this.announcedDeposits.has(key2) || wasDepositAnnounced(key2)) return;
19274
19595
  this.announcedDeposits.add(key2);
19596
+ rememberAnnouncedDeposit(key2);
19275
19597
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
19276
19598
  const legKey = `agent:${evidence.agentId}`;
19277
19599
  const record2 = (type, notice) => {
@@ -19332,7 +19654,8 @@ var OwneySDK = class {
19332
19654
  const fromBlock = parseBlock(opts?.fromBlock ?? evidence.payoutSearch?.fromBlock);
19333
19655
  const cursor = parseBlock(opts?.cursor);
19334
19656
  if (fromBlock === null || cursor === null) return null;
19335
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19657
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19658
+ const state = this.readStateFor(connection);
19336
19659
  if (typeof evidence.walletAddress !== "string" || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19337
19660
  const agent = this.getAgent(evidence.agentId);
19338
19661
  const verifiedWallet = agent.getFundingWallet ? await agent.getFundingWallet(state, chainId, evidence.token) : (await agent.getUserProfile(state, chainId)).smartWallet;
@@ -19357,7 +19680,8 @@ var OwneySDK = class {
19357
19680
  /** Resolve a saved sponsored-withdrawal ID without opening a wallet prompt. */
19358
19681
  async resolveSponsoredWithdrawalEvidence(evidence, options = {}) {
19359
19682
  if (evidence.callsId && !evidence.userOpHash) return this.resolveWalletCallsFundingEvidence(evidence, "withdraw");
19360
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19683
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19684
+ const state = this.readStateFor(connection);
19361
19685
  if (evidence.agentId !== "yieldseeker" || chainId !== 8453 || evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return evidence;
19362
19686
  const agent = this.getAgent("yieldseeker");
19363
19687
  const wallet = await agent.getFundingWallet?.(state, chainId, evidence.token);
@@ -19404,7 +19728,8 @@ var OwneySDK = class {
19404
19728
  }
19405
19729
  /** Recover an EIP-5792 deposit or payout using this account's exact batch ID. */
19406
19730
  async resolveWalletCallsFundingEvidence(evidence, direction) {
19407
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19731
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19732
+ const state = this.readStateFor(connection);
19408
19733
  if (!evidence.callsId || evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return evidence;
19409
19734
  const agent = this.getAgent(evidence.agentId);
19410
19735
  const wallet = agent.getFundingWallet ? await agent.getFundingWallet(state, chainId, evidence.token) : (await agent.getUserProfile(state, chainId)).smartWallet;
@@ -19437,7 +19762,8 @@ var OwneySDK = class {
19437
19762
  const first = evidences[0];
19438
19763
  const saved = !first.txHash && evidences.every((e) => !e.txHash && (e.serverBroadcast === "unknown" || e.serverBroadcast === true) && typeof e.authorizationDeadline === "number");
19439
19764
  if (!first.txHash && !saved) return false;
19440
- const { state, chainId, assertCurrent } = this.captureReadScope(first.chainId);
19765
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(first.chainId);
19766
+ const state = this.readStateFor(connection);
19441
19767
  const token = SupportedAssets.find((value) => value.chainId === chainId && value.symbol === first.token);
19442
19768
  if (!token) return false;
19443
19769
  const scope = {
@@ -19554,7 +19880,8 @@ var OwneySDK = class {
19554
19880
  /** Optional post-payout display proof; receipt verification and the provider
19555
19881
  * adapter must agree before attaching it to this exact balance object. */
19556
19882
  async verifyWithdrawalBalance(evidence, balance) {
19557
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19883
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19884
+ const state = this.readStateFor(connection);
19558
19885
  const agent = this.getAgent(evidence.agentId);
19559
19886
  if (!agent.verifyWithdrawalBalance || !evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return balance;
19560
19887
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}:${evidence.intendedAmount}`;
@@ -19603,7 +19930,8 @@ var OwneySDK = class {
19603
19930
  const agent = this.getAgent(evidence.agentId);
19604
19931
  if (!agent.getFundingHistory) return { data: [], hasMore: false };
19605
19932
  const filters = { tokenSymbol: evidence.token, fromDate, limit: 50, ...options };
19606
- const page = await this.readAgent(agent, "history", () => agent.getFundingHistory(state, chainId, filters), filters);
19933
+ const readState = this.readStateFor(state);
19934
+ const page = await this.readAgent(agent, "history", () => agent.getFundingHistory(readState, chainId, filters), filters);
19607
19935
  assertCurrent();
19608
19936
  return page;
19609
19937
  }
@@ -19620,7 +19948,7 @@ var OwneySDK = class {
19620
19948
  const state = this.state;
19621
19949
  const id = evidence.withdrawalRequest?.providerWithdrawalId;
19622
19950
  if (evidence.agentId !== "zyfai" || !id || !state || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19623
- return this.getAgent("zyfai").getWithdrawalLifecycle(state, id);
19951
+ return this.getAgent("zyfai").getWithdrawalLifecycle(this.readStateFor(state), id);
19624
19952
  }
19625
19953
  /** A Zyfai deposit's placement status by the id recorded on its evidence. Never signs,
19626
19954
  * prompts or authenticates; `null` when unavailable or not this wallet's Zyfai deposit. */
@@ -19628,7 +19956,7 @@ var OwneySDK = class {
19628
19956
  const state = this.state;
19629
19957
  const id = evidence.providerDepositId;
19630
19958
  if (evidence.agentId !== "zyfai" || !id || !state || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19631
- return this.getAgent("zyfai").getDepositPlacement(state, id);
19959
+ return this.getAgent("zyfai").getDepositPlacement(this.readStateFor(state), id);
19632
19960
  }
19633
19961
  // --- Fund operations ---
19634
19962
  /** On-chain version and ownership status for this owner's Yieldseeker agent. */
@@ -19636,7 +19964,7 @@ var OwneySDK = class {
19636
19964
  const state = this.requireState();
19637
19965
  const chainId = this.requireChainId();
19638
19966
  const agent = this.getAgent("yieldseeker");
19639
- return agent.getWalletStatus(state, chainId, asset);
19967
+ return agent.getWalletStatus(this.readStateFor(state), chainId, asset);
19640
19968
  }
19641
19969
  /** Deployment gate; an unavailable response keeps the current paid path. */
19642
19970
  async isYieldseekerWithdrawalSponsorshipAvailable() {
@@ -20709,7 +21037,7 @@ var OwneySDK = class {
20709
21037
  inspect: (value, fromHistory) => this.inspectFunding(value, "withdraw", { requireAmountMatch: fromHistory, refreshBalance: false }),
20710
21038
  resolve: (value) => this.resolveSponsoredWithdrawalEvidence(value, { submittedAt: recovery.submittedAt }),
20711
21039
  history: (value, fromDate, filters) => this.getFundingHistory(value, fromDate, filters),
20712
- verifyCompletion: (value) => this.getAgent(value.agentId).verifyWithdrawalCompletion?.(state, value) ?? Promise.resolve({ status: "unavailable" }),
21040
+ verifyCompletion: (value) => this.getAgent(value.agentId).verifyWithdrawalCompletion?.(this.readStateFor(state), value) ?? Promise.resolve({ status: "unavailable" }),
20713
21041
  onProgress: (value) => {
20714
21042
  recovery.evidence[value.agentId] = value;
20715
21043
  persist();
@@ -22129,7 +22457,7 @@ var OwneySDK = class {
22129
22457
  const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
22130
22458
  const asset = options?.asset;
22131
22459
  const agent = this.getAgent(agentId);
22132
- const state = this.readStateFor(agentId, scope);
22460
+ const state = this.readStateFor(scope);
22133
22461
  const result = await this.readAgent(
22134
22462
  agent,
22135
22463
  "balances",
@@ -22228,7 +22556,7 @@ var OwneySDK = class {
22228
22556
  const chainId = this.requireChainId();
22229
22557
  if (agentId) {
22230
22558
  const agent = this.getAgent(agentId);
22231
- const readState = this.readStateFor(agentId, state);
22559
+ const readState = this.readStateFor(state);
22232
22560
  return this.readAgent(
22233
22561
  agent,
22234
22562
  "earnings",
@@ -22258,7 +22586,7 @@ var OwneySDK = class {
22258
22586
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
22259
22587
  offChain ? { chainId: readChain } : null
22260
22588
  );
22261
- if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(agentId, state), chainId });
22589
+ if (agentId) return refreshAgent({ agent: this.getAgent(agentId), state: this.readStateFor(state), chainId });
22262
22590
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
22263
22591
  }
22264
22592
  async aggregateEarnings(entries, read2) {
@@ -22326,7 +22654,7 @@ var OwneySDK = class {
22326
22654
  for (const agent of agents) {
22327
22655
  for (const legChainId of chainIds) {
22328
22656
  if (agentRunsOn(agent, legChainId))
22329
- legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
22657
+ legs.push({ agent, legChainId, legState: this.readStateFor(state) });
22330
22658
  }
22331
22659
  }
22332
22660
  if (!agentId) {
@@ -22366,7 +22694,7 @@ var OwneySDK = class {
22366
22694
  assets: []
22367
22695
  };
22368
22696
  }
22369
- const readState = this.readStateFor(agentId, state);
22697
+ const readState = this.readStateFor(state);
22370
22698
  return this.readAgent(
22371
22699
  agent,
22372
22700
  "dailyEarnings",
@@ -22447,7 +22775,7 @@ var OwneySDK = class {
22447
22775
  `Agent ${agent.id} does not support pool customization`
22448
22776
  );
22449
22777
  }
22450
- return agent.getPoolSelection(state, chainId, {
22778
+ return agent.getPoolSelection(this.readStateFor(state), chainId, {
22451
22779
  pairs: params.pairs,
22452
22780
  assets: params.assets
22453
22781
  });
@@ -22472,7 +22800,7 @@ var OwneySDK = class {
22472
22800
  const scopeChainId = scope === "all" ? null : scope;
22473
22801
  if (agentId) {
22474
22802
  const agent = this.getAgent(agentId);
22475
- const readState = this.readStateFor(agentId, state);
22803
+ const readState = this.readStateFor(state);
22476
22804
  const accountApy = await this.readAgent(
22477
22805
  agent,
22478
22806
  "accountApy",
@@ -22612,7 +22940,7 @@ var OwneySDK = class {
22612
22940
  for (const agent of agents) {
22613
22941
  for (const legChainId of chainIds) {
22614
22942
  if (agentRunsOn(agent, legChainId))
22615
- legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(agent.id, state2) });
22943
+ legs.push({ agentId: agent.id, chainId: legChainId, legState: this.readStateFor(state2) });
22616
22944
  }
22617
22945
  }
22618
22946
  if (!agentId) {
@@ -22656,7 +22984,7 @@ var OwneySDK = class {
22656
22984
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
22657
22985
  if (agentId) {
22658
22986
  const agent = this.getAgent(agentId);
22659
- const readState = this.readStateFor(agentId, state);
22987
+ const readState = this.readStateFor(state);
22660
22988
  const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
22661
22989
  assertCurrent();
22662
22990
  return page;
@@ -22671,7 +22999,7 @@ var OwneySDK = class {
22671
22999
  }
22672
23000
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
22673
23001
  try {
22674
- const readState = this.readStateFor(agent.id, state);
23002
+ const readState = this.readStateFor(state);
22675
23003
  const page = await this.readAgent(
22676
23004
  agent,
22677
23005
  "history",
@@ -22733,7 +23061,7 @@ var OwneySDK = class {
22733
23061
  const chainId = this.requireChainId();
22734
23062
  if (agentId) {
22735
23063
  const agent = this.getAgent(agentId);
22736
- const readState = this.readStateFor(agentId, state);
23064
+ const readState = this.readStateFor(state);
22737
23065
  return this.readAgent(
22738
23066
  agent,
22739
23067
  "profile",
@@ -22956,7 +23284,7 @@ var OwneySDK = class {
22956
23284
  const entries = [...activeAgents.entries()];
22957
23285
  const balanceResults = await Promise.allSettled(
22958
23286
  entries.map(async ([id, agent]) => {
22959
- const readState = this.readStateFor(id, state);
23287
+ const readState = this.readStateFor(state);
22960
23288
  const b = await this.readAgent(
22961
23289
  agent,
22962
23290
  "balances",
@@ -23015,7 +23343,7 @@ var import_sdk2 = require("@zyfai/sdk");
23015
23343
 
23016
23344
  // src/agents/zyfai/zyfai.siwx-cache.ts
23017
23345
  var KEY_PREFIX7 = "owney.siwx.session";
23018
- var storage8 = () => {
23346
+ var storage10 = () => {
23019
23347
  if (typeof window === "undefined") return null;
23020
23348
  try {
23021
23349
  return window.localStorage;
@@ -23056,7 +23384,7 @@ var readLegacySiwxSession = (store, address) => {
23056
23384
  var readSiwxSession = (address, chainId) => {
23057
23385
  if (typeof window === "undefined") return null;
23058
23386
  const key2 = buildKey3(address);
23059
- const store = storage8();
23387
+ const store = storage10();
23060
23388
  let raw2 = null;
23061
23389
  try {
23062
23390
  raw2 = store?.getItem(key2) ?? null;
@@ -23086,7 +23414,7 @@ var writeSiwxSession = (address, _chainId, session) => {
23086
23414
  if (typeof window === "undefined") return;
23087
23415
  const key2 = buildKey3(address);
23088
23416
  memorySiwxSessions.set(key2, session);
23089
- const store = storage8();
23417
+ const store = storage10();
23090
23418
  try {
23091
23419
  store?.setItem(key2, JSON.stringify(session));
23092
23420
  } catch {
@@ -23095,7 +23423,7 @@ var writeSiwxSession = (address, _chainId, session) => {
23095
23423
  var clearSiwxSession = (address, _chainId) => {
23096
23424
  const key2 = buildKey3(address);
23097
23425
  memorySiwxSessions.delete(key2);
23098
- const store = storage8();
23426
+ const store = storage10();
23099
23427
  try {
23100
23428
  store?.removeItem(key2);
23101
23429
  } catch {