@owney/sdk 0.7.32-beta.10 → 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.10";
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;
@@ -5206,18 +5256,45 @@ var ZyfaiAgent = class _ZyfaiAgent {
5206
5256
  }
5207
5257
  return this.connectedAddress;
5208
5258
  }
5209
- /** Light connect: SIWE auth only. Re-auths if chain changed. */
5259
+ /**
5260
+ * Whether connecting now would ask the wallet to sign in: not connected for
5261
+ * this wallet and chain (the check `connectAuth` returns early on) and no
5262
+ * fresh saved session. Never prompts; reads only what is saved.
5263
+ */
5264
+ needsSignIn(state, chainId) {
5265
+ const owner = state.walletAddress.toLowerCase();
5266
+ if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === chainId) return false;
5267
+ return readSession(state.walletAddress, chainId) === null;
5268
+ }
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
+ */
5210
5284
  async connectAuth(state, chainId) {
5211
5285
  const validChainId = isValidChainId(chainId);
5212
5286
  const owner = state.walletAddress.toLowerCase();
5213
5287
  const scope = `${owner}:${validChainId}`;
5288
+ const promptless = state.promptless === true;
5214
5289
  if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === validChainId) {
5215
5290
  return;
5216
5291
  }
5217
5292
  if (this.connectAuthPromise && this.connectAuthScope === scope) {
5218
- await this.connectAuthPromise;
5293
+ if (this.connectAuthPromptless && !promptless) await this.connectAuthPromise.catch(() => void 0);
5294
+ else await this.connectAuthPromise;
5219
5295
  return this.connectAuth(state, chainId);
5220
5296
  }
5297
+ if (promptless && readSession(state.walletAddress, validChainId) === null) throw this.signInRequired();
5221
5298
  if (this.sdkHasConnected || this.connectedAddress) this.sdk = this.createSdk();
5222
5299
  this.sdkHasConnected = true;
5223
5300
  const executionSdk = this.sdk;
@@ -5230,7 +5307,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
5230
5307
  const address = await this.connectAccountWithRetry(
5231
5308
  state.provider,
5232
5309
  validChainId,
5233
- executionSdk
5310
+ executionSdk,
5311
+ promptless
5234
5312
  );
5235
5313
  if (generation !== this.connectionGeneration || address.toLowerCase() !== owner)
5236
5314
  throw new OwneyError("NOT_CONNECTED", "Wallet changed while connecting Zyfai.", void 0, this.id);
@@ -5239,12 +5317,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5239
5317
  })();
5240
5318
  this.connectAuthPromise = pending2;
5241
5319
  this.connectAuthScope = scope;
5320
+ this.connectAuthPromptless = promptless;
5242
5321
  try {
5243
5322
  await pending2;
5244
5323
  } finally {
5245
5324
  if (this.connectAuthPromise === pending2) {
5246
5325
  this.connectAuthPromise = null;
5247
5326
  this.connectAuthScope = null;
5327
+ this.connectAuthPromptless = false;
5248
5328
  }
5249
5329
  }
5250
5330
  }
@@ -5257,19 +5337,86 @@ var ZyfaiAgent = class _ZyfaiAgent {
5257
5337
  * which does not separate a revoked JWT from a misconfigured API key; we
5258
5338
  * retry once either way, and if the second attempt still fails the original
5259
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.
5260
5345
  */
5261
- async connectAccountWithRetry(provider, chainId, executionSdk = this.sdk) {
5346
+ async connectAccountWithRetry(provider, chainId, executionSdk = this.sdk, promptless = false) {
5347
+ if (promptless) this.promptlessSdks.add(executionSdk);
5262
5348
  try {
5263
- return await executionSdk.connectAccount(provider, chainId);
5349
+ const address = await executionSdk.connectAccount(provider, chainId);
5350
+ this.promptlessSdks.delete(executionSdk);
5351
+ return address;
5264
5352
  } catch (error) {
5265
5353
  const message = error instanceof Error ? error.message : String(error);
5266
5354
  if (!message.toLowerCase().includes("unauthorized")) throw error;
5267
5355
  const internals = executionSdk;
5268
5356
  const address = internals.walletClient?.account?.address;
5357
+ if (promptless) throw this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
5269
5358
  if (address) clearSession(address, chainId);
5270
5359
  return await executionSdk.connectAccount(provider, chainId);
5271
5360
  }
5272
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
+ }
5273
5420
  /**
5274
5421
  * Reconnect if the Zyfai connection was torn down behind our back: a
5275
5422
  * chain/account switch fires the provider's `accountsChanged` →
@@ -5307,6 +5454,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5307
5454
  internals.httpClient.clearAuthToken();
5308
5455
  internals.authenticatedUserId = null;
5309
5456
  this.connectedChainId = null;
5457
+ this.tellSignInRefused();
5310
5458
  }
5311
5459
  /**
5312
5460
  * Sync newly-available protocols onto an existing user's profile at wallet
@@ -5358,11 +5506,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5358
5506
  * per chain, in parallel) cancel each other's sign-in. Funding keeps
5359
5507
  * `connectAuth`/`ensureConnected`. Returns the owner verified for this call,
5360
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`).
5361
5511
  */
5362
5512
  async ensureReadSession(state, chainId) {
5363
5513
  const owner = state.walletAddress?.toLowerCase();
5364
5514
  if (this.connectAuthPromise) await this.connectAuthPromise.catch(() => void 0);
5365
- 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);
5366
5517
  }
5367
5518
  /** `ensureReadSession`, then the owner it verified, read in the same turn. */
5368
5519
  async connectForRead(state, chainId) {
@@ -5396,7 +5547,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5396
5547
  return pending2;
5397
5548
  }
5398
5549
  // --- IAgent: Connection lifecycle ---
5399
- async disconnect() {
5550
+ async disconnect(options) {
5400
5551
  const executionSdk = this.sdk;
5401
5552
  this.connectionGeneration++;
5402
5553
  this.earningsGeneration++;
@@ -5409,7 +5560,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5409
5560
  this.holdActiveScopes.clear();
5410
5561
  this.pendingRegistrations.clear();
5411
5562
  this.lastGoodEarnings.clear();
5412
- if (this.connectedAddress && this.connectedChainId !== null) {
5563
+ if (!options?.keepSignIns && this.connectedAddress && this.connectedChainId !== null) {
5413
5564
  clearSession(this.connectedAddress, this.connectedChainId);
5414
5565
  }
5415
5566
  this.connectedAddress = null;
@@ -5787,13 +5938,14 @@ var ZyfaiAgent = class _ZyfaiAgent {
5787
5938
  Promise.all(
5788
5939
  params.pairs.map(async ({ protocolId, chainId: chainId2 }) => {
5789
5940
  try {
5790
- const current = await this.sdk.getSelectedPools(
5941
+ const current = await this.readCall(state, () => this.sdk.getSelectedPools(
5791
5942
  protocolId,
5792
5943
  chainId2
5793
- );
5944
+ ));
5794
5945
  if (current.autoselect) return null;
5795
5946
  return { protocolId, chainId: chainId2, pools: current.pools ?? [] };
5796
- } catch {
5947
+ } catch (error) {
5948
+ if (isSignInFailure(error)) throw error;
5797
5949
  return null;
5798
5950
  }
5799
5951
  })
@@ -5801,9 +5953,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5801
5953
  Promise.all(
5802
5954
  params.assets.map(async (asset) => {
5803
5955
  try {
5804
- const current = await this.sdk.getUserDetails(asset);
5956
+ const current = await this.readCall(state, () => this.sdk.getUserDetails(asset));
5805
5957
  return current.strategy ? { asset, strategy: current.strategy } : null;
5806
- } catch {
5958
+ } catch (error) {
5959
+ if (isSignInFailure(error)) throw error;
5807
5960
  return null;
5808
5961
  }
5809
5962
  })
@@ -7196,7 +7349,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7196
7349
  const requestedAt = Date.now();
7197
7350
  const generation = this.earningsGeneration;
7198
7351
  const { smartWallet, chainId: validChainId } = await this.resolveSmartWallet(state, chainId);
7199
- const raw2 = await this.sdk.getPortfolio(this.getAddress());
7352
+ const raw2 = await this.readCall(state, () => this.sdk.getPortfolio(this.getAddress()));
7200
7353
  debugLog("zyfai:balances", "read", { ms: Date.now() - requestedAt });
7201
7354
  const balance = mapBalances(raw2, validChainId, smartWallet);
7202
7355
  const reads = balance.readMetadata?.map((read2) => ({ ...read2, requestedAt })) ?? [];
@@ -7258,7 +7411,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7258
7411
  async getEarnings(state, chainId) {
7259
7412
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
7260
7413
  const key2 = this.earningsKey(state, chainId, smartWallet);
7261
- const raw2 = await this.readEarnings(key2, smartWallet);
7414
+ const raw2 = await this.readCall(state, () => this.readEarnings(key2, smartWallet));
7262
7415
  const held = await this.holdEarnings(state, chainId, smartWallet, key2, raw2);
7263
7416
  if (held.active) void this.refreshEarnings(state, chainId).catch(() => void 0);
7264
7417
  return mapEarnings(held.value, smartWallet);
@@ -7409,7 +7562,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7409
7562
  if (existing) return existing;
7410
7563
  const pending2 = (async () => {
7411
7564
  const recent = this.earningsSnapshot;
7412
- 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);
7413
7566
  const lastCheck = current.data.lastCheckTimestamp ? Date.parse(current.data.lastCheckTimestamp) : Number.NaN;
7414
7567
  const mapped = mapEarnings(current, smartWallet);
7415
7568
  const held = await this.holdEarnings(state, chainId, smartWallet, key2, current);
@@ -7423,7 +7576,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7423
7576
  if (isFresh && !negative || !canCalculate)
7424
7577
  return held.active ? mapEarnings(held.value, smartWallet) : mapped;
7425
7578
  this.earningsCalculationAttempts.set(calculationKey, now);
7426
- const earnings = await executionSdk.calculateOnchainEarnings(smartWallet);
7579
+ const earnings = await this.readCall(state, () => executionSdk.calculateOnchainEarnings(smartWallet), executionSdk);
7427
7580
  assertCurrent();
7428
7581
  this.earningsSnapshot = { key: key2, raw: earnings, at: Date.now() };
7429
7582
  const recalculated = await this.holdEarnings(state, chainId, smartWallet, key2, earnings);
@@ -7438,7 +7591,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7438
7591
  }
7439
7592
  async getAccountApy(state, chainId, days, tokenSymbol, scopeChainId) {
7440
7593
  const { smartWallet } = await this.resolveSmartWallet(state, chainId);
7441
- const raw2 = await this.sdk.getDailyApyHistory(smartWallet, days);
7594
+ const raw2 = await this.readCall(state, () => this.sdk.getDailyApyHistory(smartWallet, days));
7442
7595
  const scope = scopeChainId === null ? void 0 : scopeChainId ?? chainId;
7443
7596
  const ethUsd = tokenSymbol === void 0 && holdsEthPosition(raw2) ? await readEthUsdPrice(this.getPublicClient(8453)) : void 0;
7444
7597
  return mapApyHistory(raw2, scope, tokenSymbol, ethUsd);
@@ -7448,10 +7601,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
7448
7601
  const start = new Date(
7449
7602
  Date.now() - (DayFilterMapping[days] + 1) * 864e5
7450
7603
  );
7451
- const raw2 = await this.sdk.getDailyEarnings(
7604
+ const raw2 = await this.readCall(state, () => this.sdk.getDailyEarnings(
7452
7605
  smartWallet,
7453
7606
  start.toISOString().slice(0, 10)
7454
- );
7607
+ ));
7455
7608
  return mapDailyEarnings(raw2, chainId, tokenSymbol);
7456
7609
  }
7457
7610
  /**
@@ -7495,7 +7648,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7495
7648
  const matched = [];
7496
7649
  let backendExhausted = false;
7497
7650
  for (let i = 0; i < MAX_BACKEND_CALLS && matched.length < limit; i++) {
7498
- const raw2 = await this.sdk.getHistory(smartWallet, validChainId, {
7651
+ const raw2 = await this.readCall(state, () => this.sdk.getHistory(smartWallet, validChainId, {
7499
7652
  limit: backendPageSize,
7500
7653
  offset,
7501
7654
  fromDate: options?.fromDate,
@@ -7505,7 +7658,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7505
7658
  // relevant entries instead of spending its budget on the other
7506
7659
  // asset's rows and handing back a page that filters to nothing.
7507
7660
  assetType
7508
- });
7661
+ }));
7509
7662
  raw2.data.forEach((entry, idx) => {
7510
7663
  if (entry.chainId === validChainId) {
7511
7664
  matched.push({ entry, rawIdx: offset + idx });
@@ -7541,7 +7694,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
7541
7694
  }
7542
7695
  async getUserProfile(state, chainId) {
7543
7696
  await this.ensureReadSession(state, chainId);
7544
- const raw2 = await this.sdk.getUserDetails();
7697
+ const raw2 = await this.readCall(state, () => this.sdk.getUserDetails());
7545
7698
  debugLog("zyfai:profile", "getUserProfile \u2014 Zyfai reports", {
7546
7699
  asset: "USDC (default \u2014 no asset passed)",
7547
7700
  splitting: raw2.splitting,
@@ -7634,7 +7787,7 @@ var INVALIDATED_KEY_PREFIXES = [
7634
7787
  "owney.yieldseeker.session.v3",
7635
7788
  "owney.yieldseeker.session.v4"
7636
7789
  ];
7637
- var storage3 = () => {
7790
+ var storage4 = () => {
7638
7791
  if (typeof window === "undefined") return null;
7639
7792
  try {
7640
7793
  return window.localStorage;
@@ -7668,7 +7821,7 @@ var isValidSession = (session) => {
7668
7821
  var readYieldseekerSession = (address, chainId) => {
7669
7822
  if (typeof window === "undefined") return null;
7670
7823
  const key2 = buildKey2(address, chainId);
7671
- const store = storage3();
7824
+ const store = storage4();
7672
7825
  clearInvalidatedSessions(store, address, chainId);
7673
7826
  let raw2 = null;
7674
7827
  try {
@@ -7700,7 +7853,7 @@ var writeYieldseekerSession = (address, chainId, token) => {
7700
7853
  if (!isValidSession(session)) return;
7701
7854
  const key2 = buildKey2(address, chainId);
7702
7855
  memorySessions2.set(key2, session);
7703
- const store = storage3();
7856
+ const store = storage4();
7704
7857
  try {
7705
7858
  store?.setItem(key2, JSON.stringify(session));
7706
7859
  } catch {
@@ -7709,7 +7862,7 @@ var writeYieldseekerSession = (address, chainId, token) => {
7709
7862
  var clearYieldseekerSession = (address, chainId) => {
7710
7863
  const key2 = buildKey2(address, chainId);
7711
7864
  memorySessions2.delete(key2);
7712
- const store = storage3();
7865
+ const store = storage4();
7713
7866
  clearInvalidatedSessions(store, address, chainId);
7714
7867
  try {
7715
7868
  store?.removeItem(key2);
@@ -7821,12 +7974,21 @@ var YieldseekerAuth = class {
7821
7974
  return this.getToken(state, chainId);
7822
7975
  }
7823
7976
  /** Drop a proof the provider refused, without signing a new one: a
7824
- * 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. */
7825
7980
  discardToken(state, chainId, rejectedToken) {
7826
7981
  const key2 = this.key(state, chainId);
7827
- if (this.tokens.get(key2) === rejectedToken) this.tokens.delete(key2);
7828
- 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) {
7829
7988
  clearYieldseekerSession(state.walletAddress, chainId);
7989
+ dropped = true;
7990
+ }
7991
+ return dropped;
7830
7992
  }
7831
7993
  isReusable(token, state, chainId) {
7832
7994
  try {
@@ -7842,6 +8004,12 @@ var YieldseekerAuth = class {
7842
8004
  return false;
7843
8005
  }
7844
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
+ }
7845
8013
  clear(state, chainId) {
7846
8014
  if (!state || chainId === void 0) {
7847
8015
  for (const scope of this.scopes.values()) {
@@ -7886,9 +8054,9 @@ var YieldseekerAuth = class {
7886
8054
 
7887
8055
  // src/agents/yieldseeker/yieldseeker.identity-cache.ts
7888
8056
  var KEY_PREFIX3 = "owney.yieldseeker.identity.v1";
7889
- var YIELDSEEKER_IDENTITY_TTL_MS = 24 * 60 * 60 * 1e3;
8057
+ var YIELDSEEKER_IDENTITY_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
7890
8058
  var memoryIdentities = /* @__PURE__ */ new Map();
7891
- var storage4 = () => {
8059
+ var storage5 = () => {
7892
8060
  if (typeof window === "undefined") return null;
7893
8061
  try {
7894
8062
  return window.localStorage;
@@ -7905,7 +8073,7 @@ function valid(value, walletAddress, chainId, now) {
7905
8073
  function readYieldseekerIdentity(walletAddress, chainId, now = Date.now()) {
7906
8074
  if (typeof window === "undefined") return null;
7907
8075
  const key2 = keyFor(walletAddress, chainId);
7908
- const store = storage4();
8076
+ const store = storage5();
7909
8077
  let parsed = null;
7910
8078
  try {
7911
8079
  const raw2 = store?.getItem(key2);
@@ -7937,7 +8105,7 @@ function writeYieldseekerIdentity(walletAddress, chainId, userId, now = Date.now
7937
8105
  const key2 = keyFor(walletAddress, chainId);
7938
8106
  memoryIdentities.set(key2, identity);
7939
8107
  try {
7940
- storage4()?.setItem(key2, JSON.stringify(identity));
8108
+ storage5()?.setItem(key2, JSON.stringify(identity));
7941
8109
  } catch {
7942
8110
  }
7943
8111
  }
@@ -7945,9 +8113,41 @@ function clearYieldseekerIdentity(walletAddress, chainId) {
7945
8113
  const key2 = keyFor(walletAddress, chainId);
7946
8114
  memoryIdentities.delete(key2);
7947
8115
  try {
7948
- 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));
7949
8148
  } catch {
7950
8149
  }
8150
+ return until;
7951
8151
  }
7952
8152
 
7953
8153
  // src/agents/yieldseeker/yieldseeker.client.ts
@@ -9603,6 +9803,12 @@ function generateYieldseekerUsername() {
9603
9803
  const suffix = globalThis.crypto.randomUUID().replaceAll("-", "").slice(0, YIELDSEEKER_USERNAME_RANDOM_LENGTH).toLowerCase();
9604
9804
  return `${YIELDSEEKER_USERNAME_PREFIX}${suffix}`;
9605
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
+ }
9606
9812
  function isUsernameConflict(error) {
9607
9813
  if (!(error instanceof YieldseekerApiError)) return false;
9608
9814
  const code = error.providerCode.toUpperCase();
@@ -9750,6 +9956,15 @@ var YieldseekerAgent = class {
9750
9956
  balanceContexts = /* @__PURE__ */ new WeakMap();
9751
9957
  balanceVaults = /* @__PURE__ */ new Map();
9752
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();
9753
9968
  pendingAgents = /* @__PURE__ */ new Map();
9754
9969
  pendingWalletContexts = /* @__PURE__ */ new Map();
9755
9970
  readCache = /* @__PURE__ */ new Map();
@@ -9776,6 +9991,7 @@ var YieldseekerAgent = class {
9776
9991
  // or while the ledger read is null, settlement and earnings are as before.
9777
9992
  ledgerAccess;
9778
9993
  accountRefusedListener;
9994
+ signInRefusedListener;
9779
9995
  ledgerReads = /* @__PURE__ */ new Map();
9780
9996
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9781
9997
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -10071,16 +10287,16 @@ var YieldseekerAgent = class {
10071
10287
  this.rememberWalletStatus(versionKey, status);
10072
10288
  return { txHash: hash2, status };
10073
10289
  };
10074
- let storage9;
10290
+ let storage11;
10075
10291
  try {
10076
- storage9 = typeof window === "undefined" ? void 0 : window.localStorage;
10292
+ storage11 = typeof window === "undefined" ? void 0 : window.localStorage;
10077
10293
  } catch {
10078
- storage9 = void 0;
10294
+ storage11 = void 0;
10079
10295
  }
10080
10296
  const clearRecordedUpgrade = () => {
10081
10297
  this.pendingUpgrades.delete(pendingKey2);
10082
10298
  try {
10083
- storage9?.removeItem(pendingKey2);
10299
+ storage11?.removeItem(pendingKey2);
10084
10300
  } catch {
10085
10301
  this.pendingUpgrades.set(pendingKey2, null);
10086
10302
  }
@@ -10103,7 +10319,7 @@ var YieldseekerAgent = class {
10103
10319
  throw pendingUpgrade(hash2);
10104
10320
  }
10105
10321
  };
10106
- if (!storage9 && (gasMode === "sponsored" || before.ownerPath === "smart"))
10322
+ if (!storage11 && (gasMode === "sponsored" || before.ownerPath === "smart"))
10107
10323
  throw new OwneyError(
10108
10324
  "SPONSOR_REQUEST_FAILED",
10109
10325
  "Upgrade status cannot be saved in this browser.",
@@ -10112,14 +10328,14 @@ var YieldseekerAgent = class {
10112
10328
  );
10113
10329
  let prior = null;
10114
10330
  try {
10115
- 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);
10116
10332
  try {
10117
10333
  prior = JSON.parse(saved ?? "null");
10118
10334
  } catch {
10119
10335
  prior = { callsId: void 0 };
10120
10336
  }
10121
10337
  } catch {
10122
- if (gasMode === "paid" && before.ownerPath === "eoa") storage9 = void 0;
10338
+ if (gasMode === "paid" && before.ownerPath === "eoa") storage11 = void 0;
10123
10339
  else throw new OwneyError(
10124
10340
  "SPONSOR_REQUEST_FAILED",
10125
10341
  "Upgrade status cannot be read in this browser.",
@@ -10213,9 +10429,9 @@ var YieldseekerAgent = class {
10213
10429
  asset: YIELDSEEKER_ASSET_METADATA[asset].address,
10214
10430
  callData: data,
10215
10431
  onPending: (pending2) => {
10216
- 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");
10217
10433
  const next = { startedAt: Date.now(), ...current, ...pending2 };
10218
- storage9.setItem(pendingKey2, JSON.stringify(next));
10434
+ storage11.setItem(pendingKey2, JSON.stringify(next));
10219
10435
  this.pendingUpgrades.delete(pendingKey2);
10220
10436
  }
10221
10437
  });
@@ -10239,8 +10455,8 @@ var YieldseekerAgent = class {
10239
10455
  const pending2 = { txHash: hash2 };
10240
10456
  this.pendingUpgrades.set(pendingKey2, pending2);
10241
10457
  try {
10242
- if (storage9) {
10243
- storage9.setItem(pendingKey2, JSON.stringify(pending2));
10458
+ if (storage11) {
10459
+ storage11.setItem(pendingKey2, JSON.stringify(pending2));
10244
10460
  this.pendingUpgrades.delete(pendingKey2);
10245
10461
  }
10246
10462
  } catch {
@@ -10261,14 +10477,18 @@ var YieldseekerAgent = class {
10261
10477
  clearRecordedUpgrade();
10262
10478
  return confirmed;
10263
10479
  }
10264
- async disconnect() {
10480
+ async disconnect(options) {
10265
10481
  this.withdrawalVersionCache.clear();
10266
10482
  this.pendingWalletStatus.clear();
10267
10483
  this.readGeneration += 1;
10268
- this.auth.clear();
10269
- for (const key2 of this.users.keys()) {
10270
- const [walletAddress, chainId] = key2.split(":");
10271
- 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
+ }
10272
10492
  }
10273
10493
  this.users.clear();
10274
10494
  this.agentContexts.clear();
@@ -10310,6 +10530,13 @@ var YieldseekerAgent = class {
10310
10530
  this.planHistoryKeys.clear();
10311
10531
  this.lastLedgerRows.clear();
10312
10532
  }
10533
+ /**
10534
+ * Whether connecting now would ask the wallet to sign in: no reusable saved
10535
+ * sign-in for this wallet and chain. Never prompts; reads only what is saved.
10536
+ */
10537
+ needsSignIn(state, chainId) {
10538
+ return !this.auth.peekToken(state, chainId);
10539
+ }
10313
10540
  /**
10314
10541
  * The connect's account check (2026-11-13), run before any agent activates:
10315
10542
  * sign in (a saved sign-in, else login-with-wallet, else POST /users for a
@@ -10855,6 +11082,7 @@ var YieldseekerAgent = class {
10855
11082
  const unwind = async (position2, assetsRaw) => {
10856
11083
  this.assertSession(generation, chainId, asset);
10857
11084
  assertOperation?.();
11085
+ this.releasingWallets.set(context.wallet.walletAddress.toLowerCase(), Date.now());
10858
11086
  let unwindTransactionHash;
10859
11087
  try {
10860
11088
  const response = await this.walletRequest(
@@ -11650,7 +11878,9 @@ var YieldseekerAgent = class {
11650
11878
  * left idle. While it has not, Yieldseeker is told again, up to
11651
11879
  * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
11652
11880
  * limit) is sent again after a wait. Within an hour of a withdrawal it is
11653
- * 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
11654
11884
  * knows for the asset and the saved sign-in only: never prompts, never
11655
11885
  * throws. Each call is reported through `onNotice`.
11656
11886
  */
@@ -11667,6 +11897,8 @@ var YieldseekerAgent = class {
11667
11897
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11668
11898
  const generation = this.readGeneration;
11669
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" };
11670
11902
  const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11671
11903
  let notified = false;
11672
11904
  let reason = "NOT_ALLOCATED";
@@ -11757,6 +11989,19 @@ var YieldseekerAgent = class {
11757
11989
  * confirmed withdrawal, if that is still ahead; null when there was none in
11758
11990
  * the last hour or the ledger cannot say.
11759
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
+ }
11760
12005
  async withdrawalCooldownEnd(state, chainId, asset, context) {
11761
12006
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11762
12007
  const wallet = context.wallet.walletAddress.toLowerCase();
@@ -12872,6 +13117,29 @@ var YieldseekerAgent = class {
12872
13117
  this.users.set(key2, persisted);
12873
13118
  return persisted;
12874
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
+ };
12875
13143
  const walletAddress = (0, import_viem17.getAddress)(state.walletAddress);
12876
13144
  const generation = this.readGeneration;
12877
13145
  let user = null;
@@ -12889,11 +13157,13 @@ var YieldseekerAgent = class {
12889
13157
  });
12890
13158
  }
12891
13159
  } catch (error) {
13160
+ if (isSignInRateLimit(error)) limited(error);
12892
13161
  if (!(error instanceof YieldseekerApiError) || error.providerCode !== "NO_USER") {
12893
13162
  if (error instanceof OwneyError) throw error;
12894
13163
  throw this.mapRequestFailure(error);
12895
13164
  }
12896
13165
  let created;
13166
+ let registeredMeanwhile = false;
12897
13167
  for (let attempt = 0; attempt < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS; attempt += 1) {
12898
13168
  try {
12899
13169
  created = await this.providerRequest(
@@ -12910,12 +13180,32 @@ var YieldseekerAgent = class {
12910
13180
  );
12911
13181
  break;
12912
13182
  } catch (createError) {
13183
+ if (isSignInRateLimit(createError)) limited(createError);
13184
+ if (isWalletAlreadyRegistered(createError)) {
13185
+ registeredMeanwhile = true;
13186
+ break;
13187
+ }
12913
13188
  const canRetry = isUsernameConflict(createError) && attempt + 1 < YIELDSEEKER_USERNAME_CREATE_ATTEMPTS;
12914
13189
  if (canRetry) continue;
12915
13190
  throw this.mapRequestFailure(createError);
12916
13191
  }
12917
13192
  }
12918
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
+ }
12919
13209
  }
12920
13210
  if (!user || !/^[a-zA-Z0-9_-]{1,128}$/.test(user.userId)) {
12921
13211
  throw this.invalidResponse("wallet identity");
@@ -12926,6 +13216,19 @@ var YieldseekerAgent = class {
12926
13216
  writeYieldseekerIdentity(state.walletAddress, chainId, resolved.userId);
12927
13217
  return resolved;
12928
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
+ }
12929
13232
  forgetUser(state, chainId) {
12930
13233
  this.users.delete(this.userKey(state, chainId));
12931
13234
  clearYieldseekerIdentity(state.walletAddress, chainId);
@@ -13407,6 +13710,9 @@ var YieldseekerAgent = class {
13407
13710
  setAccountRefusedListener(listener) {
13408
13711
  this.accountRefusedListener = listener;
13409
13712
  }
13713
+ setSignInRefusedListener(listener) {
13714
+ this.signInRefusedListener = listener;
13715
+ }
13410
13716
  setFundingLedgerAccess(access) {
13411
13717
  this.ledgerAccess = access;
13412
13718
  this.ledgerReads.clear();
@@ -13800,7 +14106,13 @@ var YieldseekerAgent = class {
13800
14106
  if (error.providerCode === "NO_USER") throw error;
13801
14107
  if (!error.isAuthenticationError) throw error;
13802
14108
  if (promptless) {
13803
- 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
+ }
13804
14116
  throw error;
13805
14117
  }
13806
14118
  signature = await this.auth.refreshToken(state, chainId, signature);
@@ -14913,7 +15225,7 @@ function runSameChainOrder(deps, options) {
14913
15225
 
14914
15226
  // src/lib/swap/swap.secret-store.ts
14915
15227
  var KEY_PREFIX4 = "owney.swap.order";
14916
- var storage5 = () => {
15228
+ var storage7 = () => {
14917
15229
  if (typeof window === "undefined") return null;
14918
15230
  try {
14919
15231
  return window.localStorage;
@@ -14923,7 +15235,7 @@ var storage5 = () => {
14923
15235
  };
14924
15236
  var keyFor2 = (orderHash) => `${KEY_PREFIX4}.${orderHash}`;
14925
15237
  function saveOrder(order) {
14926
- const store = storage5();
15238
+ const store = storage7();
14927
15239
  if (!store) return false;
14928
15240
  try {
14929
15241
  const value = JSON.stringify(order);
@@ -14934,7 +15246,7 @@ function saveOrder(order) {
14934
15246
  }
14935
15247
  }
14936
15248
  function loadOrder(orderHash) {
14937
- const store = storage5();
15249
+ const store = storage7();
14938
15250
  if (!store) return null;
14939
15251
  try {
14940
15252
  const raw2 = store.getItem(keyFor2(orderHash));
@@ -14949,7 +15261,7 @@ function loadOrder(orderHash) {
14949
15261
  }
14950
15262
  }
14951
15263
  function clearOrder(orderHash) {
14952
- const store = storage5();
15264
+ const store = storage7();
14953
15265
  if (!store) return;
14954
15266
  try {
14955
15267
  store.removeItem(keyFor2(orderHash));
@@ -14957,7 +15269,7 @@ function clearOrder(orderHash) {
14957
15269
  }
14958
15270
  }
14959
15271
  function listOrders(_now = Date.now()) {
14960
- const store = storage5();
15272
+ const store = storage7();
14961
15273
  if (!store) return [];
14962
15274
  const out = [];
14963
15275
  try {
@@ -15765,7 +16077,7 @@ async function buildErc2612Permit(reads, input) {
15765
16077
  // src/lib/swap/swap.withdraw-swap.ts
15766
16078
  var KEY_PREFIX5 = "owney.swap.withdraw";
15767
16079
  var MAX_AGE_MS = 24 * 60 * 60 * 1e3;
15768
- var storage6 = () => {
16080
+ var storage8 = () => {
15769
16081
  if (typeof window === "undefined") return null;
15770
16082
  try {
15771
16083
  return window.localStorage;
@@ -15790,7 +16102,7 @@ var notify = () => {
15790
16102
  }
15791
16103
  };
15792
16104
  function saveWithdrawSwap(record2) {
15793
- const store = storage6();
16105
+ const store = storage8();
15794
16106
  if (!store) return false;
15795
16107
  try {
15796
16108
  const current = store.getItem(keyFor3(record2.orderHash));
@@ -15804,7 +16116,7 @@ function saveWithdrawSwap(record2) {
15804
16116
  return true;
15805
16117
  }
15806
16118
  function updateWithdrawSwap(orderHash, patch) {
15807
- const store = storage6();
16119
+ const store = storage8();
15808
16120
  if (!store) return;
15809
16121
  try {
15810
16122
  const raw2 = store.getItem(keyFor3(orderHash));
@@ -15821,7 +16133,7 @@ function updateWithdrawSwap(orderHash, patch) {
15821
16133
  notify();
15822
16134
  }
15823
16135
  function clearWithdrawSwap(orderHash) {
15824
- const store = storage6();
16136
+ const store = storage8();
15825
16137
  if (!store) return;
15826
16138
  try {
15827
16139
  const raw2 = store.getItem(keyFor3(orderHash));
@@ -15835,7 +16147,7 @@ function clearWithdrawSwap(orderHash) {
15835
16147
  notify();
15836
16148
  }
15837
16149
  function listWithdrawSwaps(now = Date.now(), includeDismissed = false) {
15838
- const store = storage6();
16150
+ const store = storage8();
15839
16151
  if (!store) return [];
15840
16152
  const out = [];
15841
16153
  try {
@@ -15872,7 +16184,7 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
15872
16184
  // src/lib/swap/swap.pending-deposit.ts
15873
16185
  var KEY_PREFIX6 = "owney.swap.pending-deposit";
15874
16186
  var MAX_AGE_MS2 = 24 * 60 * 60 * 1e3;
15875
- var storage7 = () => {
16187
+ var storage9 = () => {
15876
16188
  if (typeof window === "undefined") return null;
15877
16189
  try {
15878
16190
  return window.localStorage;
@@ -15882,7 +16194,7 @@ var storage7 = () => {
15882
16194
  };
15883
16195
  var keyFor4 = (id) => `${KEY_PREFIX6}.${id}`;
15884
16196
  function savePendingDeposit(entry) {
15885
- const store = storage7();
16197
+ const store = storage9();
15886
16198
  if (!store) return;
15887
16199
  try {
15888
16200
  store.setItem(keyFor4(entry.id), JSON.stringify(entry));
@@ -15891,7 +16203,7 @@ function savePendingDeposit(entry) {
15891
16203
  }
15892
16204
  }
15893
16205
  function clearPendingDeposit(id) {
15894
- const store = storage7();
16206
+ const store = storage9();
15895
16207
  if (!store) return;
15896
16208
  try {
15897
16209
  store.removeItem(keyFor4(id));
@@ -15900,7 +16212,7 @@ function clearPendingDeposit(id) {
15900
16212
  }
15901
16213
  }
15902
16214
  function listPendingDeposits(now = Date.now()) {
15903
- const store = storage7();
16215
+ const store = storage9();
15904
16216
  if (!store) return [];
15905
16217
  const out = [];
15906
16218
  try {
@@ -17398,14 +17710,8 @@ var OwneySDK = class {
17398
17710
  */
17399
17711
  disabledAgents = /* @__PURE__ */ new Set();
17400
17712
  accountRefusedListeners = /* @__PURE__ */ new Set();
17401
- /**
17402
- * Agents whose sign-in the user cancelled this session (the wallet rejected
17403
- * the prompt), keyed by chain. Until the app ends the session they are read
17404
- * from a saved sign-in only (`readStateFor`), so no read reopens the prompt
17405
- * the user cancelled. A later successful activation of the agent removes
17406
- * it, and `disconnect()` or a different wallet's `connect()` clears the map.
17407
- */
17408
- declinedSignIns = /* @__PURE__ */ new Map();
17713
+ signInRefusedListeners = /* @__PURE__ */ new Set();
17714
+ signInProgressListeners = /* @__PURE__ */ new Set();
17409
17715
  state = null;
17410
17716
  connectionRevision = 0;
17411
17717
  disconnectingAgents = null;
@@ -17612,7 +17918,7 @@ var OwneySDK = class {
17612
17918
  read: async () => {
17613
17919
  const state = this.state;
17614
17920
  if (!state || state.walletAddress.toLowerCase() !== owner) return null;
17615
- const sample = await agent.providerEarningsSample(state, evidence.chainId);
17921
+ const sample = await agent.providerEarningsSample(this.readStateFor(state), evidence.chainId);
17616
17922
  return sample ? { ...sample, observedAt: (/* @__PURE__ */ new Date()).toISOString() } : null;
17617
17923
  },
17618
17924
  emit: (data) => op.event?.("provider.sample", data)
@@ -17631,6 +17937,97 @@ var OwneySDK = class {
17631
17937
  this.accountRefusedListeners.delete(listener);
17632
17938
  };
17633
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
+ }
17953
+ /**
17954
+ * Listens for the sign-ins a connect asks for (`SignInProgress`): which
17955
+ * agents will ask the wallet to sign in, and each one as it starts and ends,
17956
+ * then `"finished"` after the last one (or when the connect ends first).
17957
+ * Nothing is sent when no agent needs a sign-in. Returns the unsubscribe
17958
+ * function.
17959
+ */
17960
+ onSignInProgress(listener) {
17961
+ this.signInProgressListeners.add(listener);
17962
+ return () => {
17963
+ this.signInProgressListeners.delete(listener);
17964
+ };
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
+ }
17988
+ /**
17989
+ * The sign-ins this connect asks for: the agents whose `needsSignIn` says
17990
+ * yes now (one that throws counts as no). Each is announced at its first
17991
+ * step (its account check, or its activation when it has none) and counted
17992
+ * once.
17993
+ */
17994
+ planSignIns(agents, state, chainId) {
17995
+ const planned = /* @__PURE__ */ new Set();
17996
+ for (const agent of agents) {
17997
+ try {
17998
+ if (agent.needsSignIn?.(state, chainId) === true) planned.add(agent.id);
17999
+ } catch {
18000
+ }
18001
+ }
18002
+ const total = planned.size;
18003
+ let done = 0;
18004
+ let finished = false;
18005
+ const send = (progress) => {
18006
+ if (total === 0 || finished) return;
18007
+ for (const listener of [...this.signInProgressListeners]) {
18008
+ try {
18009
+ listener(progress);
18010
+ } catch {
18011
+ }
18012
+ }
18013
+ };
18014
+ const finish = () => {
18015
+ send({ state: "finished", total, done });
18016
+ finished = true;
18017
+ };
18018
+ return {
18019
+ before: (agent) => {
18020
+ if (planned.has(agent.id)) send({ state: "waiting", total, done, agentId: agent.id });
18021
+ },
18022
+ after: (agent) => {
18023
+ if (!planned.delete(agent.id)) return;
18024
+ done += 1;
18025
+ send({ state: "signed", total, done, agentId: agent.id });
18026
+ if (done === total) finish();
18027
+ },
18028
+ finish
18029
+ };
18030
+ }
17634
18031
  /** Wires the optional hooks the SDK offers an agent. */
17635
18032
  attachAgentHooks(agent) {
17636
18033
  try {
@@ -17645,6 +18042,14 @@ var OwneySDK = class {
17645
18042
  }
17646
18043
  }
17647
18044
  });
18045
+ agent.setSignInRefusedListener?.(() => {
18046
+ for (const listener of [...this.signInRefusedListeners]) {
18047
+ try {
18048
+ listener(agent.id);
18049
+ } catch {
18050
+ }
18051
+ }
18052
+ });
17648
18053
  }
17649
18054
  /**
17650
18055
  * Funding-ledger read access handed to agents for earnings holds. Reads only
@@ -17724,7 +18129,6 @@ var OwneySDK = class {
17724
18129
  }
17725
18130
  const replacingOwner = this.state !== null && this.state.walletAddress.toLowerCase() !== walletAddress.toLowerCase();
17726
18131
  this.clearConnectionState();
17727
- if (replacingOwner) this.declinedSignIns.clear();
17728
18132
  await (replacingOwner ? this.disconnectAgents() : this.disconnectingAgents);
17729
18133
  if (revision !== this.connectionRevision)
17730
18134
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
@@ -17738,11 +18142,10 @@ var OwneySDK = class {
17738
18142
  * Disconnect from all agents and clear connection state.
17739
18143
  * After calling this, `connect()` must be called again before using agent methods.
17740
18144
  */
17741
- async disconnect() {
18145
+ async disconnect(options) {
17742
18146
  ++this.connectionRevision;
17743
18147
  this.clearConnectionState();
17744
- this.declinedSignIns.clear();
17745
- await this.disconnectAgents();
18148
+ await this.disconnectAgents(options);
17746
18149
  }
17747
18150
  clearConnectionState() {
17748
18151
  this.state = null;
@@ -17754,9 +18157,9 @@ var OwneySDK = class {
17754
18157
  this.cachedWethSponsoredCallback = null;
17755
18158
  this.cachedSponsoredCallsCallbacks.clear();
17756
18159
  }
17757
- disconnectAgents() {
18160
+ disconnectAgents(options) {
17758
18161
  if (this.disconnectingAgents) return this.disconnectingAgents;
17759
- 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) => {
17760
18163
  const failure = results.find((result) => result.status === "rejected");
17761
18164
  if (failure?.status === "rejected") throw failure.reason;
17762
18165
  });
@@ -17797,17 +18200,14 @@ var OwneySDK = class {
17797
18200
  return agent?.isSlotUnavailable?.(state, chainId, asset) === true;
17798
18201
  }
17799
18202
  /**
17800
- * The state an agent's reads use. An agent whose sign-in the user cancelled
17801
- * on the connection chain this session is read from a saved sign-in only,
17802
- * as `offChainPortfolioAgents` reads: a read that would need a wallet
17803
- * prompt fails for that agent instead of reopening the prompt the user
17804
- * cancelled. A later successful activation of the agent, or `disconnect()`,
17805
- * 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.
17806
18208
  */
17807
- readStateFor(agentId, state) {
17808
- const chainId = state.chainId;
17809
- if (state.promptless === true || chainId === null) return state;
17810
- return this.declinedSignIns.get(chainId)?.has(agentId) === true ? { ...state, promptless: true } : state;
18209
+ readStateFor(state) {
18210
+ return state.promptless === true ? state : { ...state, promptless: true };
17811
18211
  }
17812
18212
  /**
17813
18213
  * Check if the SDK has an active connection state.
@@ -18031,7 +18431,7 @@ var OwneySDK = class {
18031
18431
  }
18032
18432
  /** The active agents, each with the state its reads use (`readStateFor`). */
18033
18433
  activeReads(state, chainId) {
18034
- 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 }));
18035
18435
  }
18036
18436
  /**
18037
18437
  * Read the org's agent policy once and reuse it. fetchOrgAgentConfig never
@@ -18295,6 +18695,14 @@ var OwneySDK = class {
18295
18695
  * activation, with nothing activated.
18296
18696
  */
18297
18697
  async activateAgentsInTurn(agents, state, chainId, asset, onAgentsSelected) {
18698
+ const signIns = this.planSignIns(agents, state, chainId);
18699
+ try {
18700
+ await this.activatePlannedAgents(agents, state, chainId, signIns, asset, onAgentsSelected);
18701
+ } finally {
18702
+ signIns.finish();
18703
+ }
18704
+ }
18705
+ async activatePlannedAgents(agents, state, chainId, signIns, asset, onAgentsSelected) {
18298
18706
  let firstError = null;
18299
18707
  let walletRejected = false;
18300
18708
  const activatedAgentIds = [];
@@ -18309,19 +18717,16 @@ var OwneySDK = class {
18309
18717
  ...error instanceof OwneyError && error.details ? { details: error.details } : {}
18310
18718
  });
18311
18719
  firstError = error;
18312
- if (this.isUserRejectedWithdrawal(error)) {
18313
- walletRejected = true;
18314
- const declined = this.declinedSignIns.get(chainId) ?? /* @__PURE__ */ new Set();
18315
- declined.add(agent.id);
18316
- this.declinedSignIns.set(chainId, declined);
18317
- }
18720
+ if (this.isUserRejectedWithdrawal(error)) walletRejected = true;
18318
18721
  };
18319
18722
  for (const agent of agents) {
18320
18723
  if (!agent.checkAccount) continue;
18321
18724
  this.assertActivationSession(state);
18322
18725
  try {
18726
+ signIns.before(agent);
18323
18727
  await agent.checkAccount(state, chainId);
18324
18728
  this.assertActivationSession(state);
18729
+ signIns.after(agent);
18325
18730
  } catch (error) {
18326
18731
  recordFailure(agent, error);
18327
18732
  break;
@@ -18332,12 +18737,13 @@ var OwneySDK = class {
18332
18737
  for (const agent of agents) {
18333
18738
  this.assertActivationSession(state);
18334
18739
  try {
18740
+ signIns.before(agent);
18335
18741
  await agent.activateAgent(state, chainId, asset);
18336
18742
  this.assertActivationSession(state);
18743
+ signIns.after(agent);
18337
18744
  await this.applyOrgPolicyTo(agent, state, chainId);
18338
18745
  this.assertActivationSession(state);
18339
18746
  activatedAgentIds.push(agent.id);
18340
- this.declinedSignIns.get(chainId)?.delete(agent.id);
18341
18747
  } catch (error) {
18342
18748
  recordFailure(agent, error);
18343
18749
  break;
@@ -19071,7 +19477,8 @@ var OwneySDK = class {
19071
19477
  }
19072
19478
  /** Revalidate a saved transfer against the authenticated account and actual receipt. */
19073
19479
  async inspectFunding(evidence, direction, options = {}) {
19074
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19480
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19481
+ const state = this.readStateFor(connection);
19075
19482
  if (state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase() || !evidence.txHash)
19076
19483
  throw new OwneyError("AGENT_API_ERROR", "Funding evidence does not match the connected account.");
19077
19484
  const agent = this.getAgent(evidence.agentId);
@@ -19184,8 +19591,9 @@ var OwneySDK = class {
19184
19591
  const movement = evidence.txHash ?? evidence.userOpHash ?? evidence.callsId;
19185
19592
  if (!agent?.depositConfirmed || !movement) return;
19186
19593
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${movement.toLowerCase()}`;
19187
- if (this.announcedDeposits.has(key2)) return;
19594
+ if (this.announcedDeposits.has(key2) || wasDepositAnnounced(key2)) return;
19188
19595
  this.announcedDeposits.add(key2);
19596
+ rememberAnnouncedDeposit(key2);
19189
19597
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
19190
19598
  const legKey = `agent:${evidence.agentId}`;
19191
19599
  const record2 = (type, notice) => {
@@ -19246,7 +19654,8 @@ var OwneySDK = class {
19246
19654
  const fromBlock = parseBlock(opts?.fromBlock ?? evidence.payoutSearch?.fromBlock);
19247
19655
  const cursor = parseBlock(opts?.cursor);
19248
19656
  if (fromBlock === null || cursor === null) return null;
19249
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19657
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19658
+ const state = this.readStateFor(connection);
19250
19659
  if (typeof evidence.walletAddress !== "string" || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19251
19660
  const agent = this.getAgent(evidence.agentId);
19252
19661
  const verifiedWallet = agent.getFundingWallet ? await agent.getFundingWallet(state, chainId, evidence.token) : (await agent.getUserProfile(state, chainId)).smartWallet;
@@ -19271,7 +19680,8 @@ var OwneySDK = class {
19271
19680
  /** Resolve a saved sponsored-withdrawal ID without opening a wallet prompt. */
19272
19681
  async resolveSponsoredWithdrawalEvidence(evidence, options = {}) {
19273
19682
  if (evidence.callsId && !evidence.userOpHash) return this.resolveWalletCallsFundingEvidence(evidence, "withdraw");
19274
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19683
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19684
+ const state = this.readStateFor(connection);
19275
19685
  if (evidence.agentId !== "yieldseeker" || chainId !== 8453 || evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return evidence;
19276
19686
  const agent = this.getAgent("yieldseeker");
19277
19687
  const wallet = await agent.getFundingWallet?.(state, chainId, evidence.token);
@@ -19318,7 +19728,8 @@ var OwneySDK = class {
19318
19728
  }
19319
19729
  /** Recover an EIP-5792 deposit or payout using this account's exact batch ID. */
19320
19730
  async resolveWalletCallsFundingEvidence(evidence, direction) {
19321
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19731
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19732
+ const state = this.readStateFor(connection);
19322
19733
  if (!evidence.callsId || evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return evidence;
19323
19734
  const agent = this.getAgent(evidence.agentId);
19324
19735
  const wallet = agent.getFundingWallet ? await agent.getFundingWallet(state, chainId, evidence.token) : (await agent.getUserProfile(state, chainId)).smartWallet;
@@ -19351,7 +19762,8 @@ var OwneySDK = class {
19351
19762
  const first = evidences[0];
19352
19763
  const saved = !first.txHash && evidences.every((e) => !e.txHash && (e.serverBroadcast === "unknown" || e.serverBroadcast === true) && typeof e.authorizationDeadline === "number");
19353
19764
  if (!first.txHash && !saved) return false;
19354
- const { state, chainId, assertCurrent } = this.captureReadScope(first.chainId);
19765
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(first.chainId);
19766
+ const state = this.readStateFor(connection);
19355
19767
  const token = SupportedAssets.find((value) => value.chainId === chainId && value.symbol === first.token);
19356
19768
  if (!token) return false;
19357
19769
  const scope = {
@@ -19468,7 +19880,8 @@ var OwneySDK = class {
19468
19880
  /** Optional post-payout display proof; receipt verification and the provider
19469
19881
  * adapter must agree before attaching it to this exact balance object. */
19470
19882
  async verifyWithdrawalBalance(evidence, balance) {
19471
- const { state, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19883
+ const { state: connection, chainId, assertCurrent } = this.captureReadScope(evidence.chainId);
19884
+ const state = this.readStateFor(connection);
19472
19885
  const agent = this.getAgent(evidence.agentId);
19473
19886
  if (!agent.verifyWithdrawalBalance || !evidence.txHash || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return balance;
19474
19887
  const key2 = `${state.walletAddress.toLowerCase()}:${chainId}:${evidence.agentId}:${evidence.token}:${evidence.txHash}:${evidence.intendedAmount}`;
@@ -19517,7 +19930,8 @@ var OwneySDK = class {
19517
19930
  const agent = this.getAgent(evidence.agentId);
19518
19931
  if (!agent.getFundingHistory) return { data: [], hasMore: false };
19519
19932
  const filters = { tokenSymbol: evidence.token, fromDate, limit: 50, ...options };
19520
- 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);
19521
19935
  assertCurrent();
19522
19936
  return page;
19523
19937
  }
@@ -19534,7 +19948,7 @@ var OwneySDK = class {
19534
19948
  const state = this.state;
19535
19949
  const id = evidence.withdrawalRequest?.providerWithdrawalId;
19536
19950
  if (evidence.agentId !== "zyfai" || !id || !state || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19537
- return this.getAgent("zyfai").getWithdrawalLifecycle(state, id);
19951
+ return this.getAgent("zyfai").getWithdrawalLifecycle(this.readStateFor(state), id);
19538
19952
  }
19539
19953
  /** A Zyfai deposit's placement status by the id recorded on its evidence. Never signs,
19540
19954
  * prompts or authenticates; `null` when unavailable or not this wallet's Zyfai deposit. */
@@ -19542,7 +19956,7 @@ var OwneySDK = class {
19542
19956
  const state = this.state;
19543
19957
  const id = evidence.providerDepositId;
19544
19958
  if (evidence.agentId !== "zyfai" || !id || !state || state.walletAddress.toLowerCase() !== evidence.walletAddress.toLowerCase()) return null;
19545
- return this.getAgent("zyfai").getDepositPlacement(state, id);
19959
+ return this.getAgent("zyfai").getDepositPlacement(this.readStateFor(state), id);
19546
19960
  }
19547
19961
  // --- Fund operations ---
19548
19962
  /** On-chain version and ownership status for this owner's Yieldseeker agent. */
@@ -19550,7 +19964,7 @@ var OwneySDK = class {
19550
19964
  const state = this.requireState();
19551
19965
  const chainId = this.requireChainId();
19552
19966
  const agent = this.getAgent("yieldseeker");
19553
- return agent.getWalletStatus(state, chainId, asset);
19967
+ return agent.getWalletStatus(this.readStateFor(state), chainId, asset);
19554
19968
  }
19555
19969
  /** Deployment gate; an unavailable response keeps the current paid path. */
19556
19970
  async isYieldseekerWithdrawalSponsorshipAvailable() {
@@ -20623,7 +21037,7 @@ var OwneySDK = class {
20623
21037
  inspect: (value, fromHistory) => this.inspectFunding(value, "withdraw", { requireAmountMatch: fromHistory, refreshBalance: false }),
20624
21038
  resolve: (value) => this.resolveSponsoredWithdrawalEvidence(value, { submittedAt: recovery.submittedAt }),
20625
21039
  history: (value, fromDate, filters) => this.getFundingHistory(value, fromDate, filters),
20626
- 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" }),
20627
21041
  onProgress: (value) => {
20628
21042
  recovery.evidence[value.agentId] = value;
20629
21043
  persist();
@@ -22043,7 +22457,7 @@ var OwneySDK = class {
22043
22457
  const { state: scope, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
22044
22458
  const asset = options?.asset;
22045
22459
  const agent = this.getAgent(agentId);
22046
- const state = this.readStateFor(agentId, scope);
22460
+ const state = this.readStateFor(scope);
22047
22461
  const result = await this.readAgent(
22048
22462
  agent,
22049
22463
  "balances",
@@ -22142,7 +22556,7 @@ var OwneySDK = class {
22142
22556
  const chainId = this.requireChainId();
22143
22557
  if (agentId) {
22144
22558
  const agent = this.getAgent(agentId);
22145
- const readState = this.readStateFor(agentId, state);
22559
+ const readState = this.readStateFor(state);
22146
22560
  return this.readAgent(
22147
22561
  agent,
22148
22562
  "earnings",
@@ -22172,7 +22586,7 @@ var OwneySDK = class {
22172
22586
  () => agent.refreshEarnings?.(readState, readChain) ?? agent.getEarnings(readState, readChain),
22173
22587
  offChain ? { chainId: readChain } : null
22174
22588
  );
22175
- 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 });
22176
22590
  return this.aggregateEarnings(this.portfolioReads(state, chainId), refreshAgent);
22177
22591
  }
22178
22592
  async aggregateEarnings(entries, read2) {
@@ -22240,7 +22654,7 @@ var OwneySDK = class {
22240
22654
  for (const agent of agents) {
22241
22655
  for (const legChainId of chainIds) {
22242
22656
  if (agentRunsOn(agent, legChainId))
22243
- legs.push({ agent, legChainId, legState: this.readStateFor(agent.id, state) });
22657
+ legs.push({ agent, legChainId, legState: this.readStateFor(state) });
22244
22658
  }
22245
22659
  }
22246
22660
  if (!agentId) {
@@ -22280,7 +22694,7 @@ var OwneySDK = class {
22280
22694
  assets: []
22281
22695
  };
22282
22696
  }
22283
- const readState = this.readStateFor(agentId, state);
22697
+ const readState = this.readStateFor(state);
22284
22698
  return this.readAgent(
22285
22699
  agent,
22286
22700
  "dailyEarnings",
@@ -22361,7 +22775,7 @@ var OwneySDK = class {
22361
22775
  `Agent ${agent.id} does not support pool customization`
22362
22776
  );
22363
22777
  }
22364
- return agent.getPoolSelection(state, chainId, {
22778
+ return agent.getPoolSelection(this.readStateFor(state), chainId, {
22365
22779
  pairs: params.pairs,
22366
22780
  assets: params.assets
22367
22781
  });
@@ -22386,7 +22800,7 @@ var OwneySDK = class {
22386
22800
  const scopeChainId = scope === "all" ? null : scope;
22387
22801
  if (agentId) {
22388
22802
  const agent = this.getAgent(agentId);
22389
- const readState = this.readStateFor(agentId, state);
22803
+ const readState = this.readStateFor(state);
22390
22804
  const accountApy = await this.readAgent(
22391
22805
  agent,
22392
22806
  "accountApy",
@@ -22526,7 +22940,7 @@ var OwneySDK = class {
22526
22940
  for (const agent of agents) {
22527
22941
  for (const legChainId of chainIds) {
22528
22942
  if (agentRunsOn(agent, legChainId))
22529
- 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) });
22530
22944
  }
22531
22945
  }
22532
22946
  if (!agentId) {
@@ -22570,7 +22984,7 @@ var OwneySDK = class {
22570
22984
  const { state, chainId, assertCurrent } = this.captureReadScope(options?.chainId);
22571
22985
  if (agentId) {
22572
22986
  const agent = this.getAgent(agentId);
22573
- const readState = this.readStateFor(agentId, state);
22987
+ const readState = this.readStateFor(state);
22574
22988
  const page = await this.readAgent(agent, "history", () => agent.getHistory(readState, chainId, filters), filters);
22575
22989
  assertCurrent();
22576
22990
  return page;
@@ -22585,7 +22999,7 @@ var OwneySDK = class {
22585
22999
  }
22586
23000
  const agentFilters = { ...filters, cursor: agentCursor || void 0 };
22587
23001
  try {
22588
- const readState = this.readStateFor(agent.id, state);
23002
+ const readState = this.readStateFor(state);
22589
23003
  const page = await this.readAgent(
22590
23004
  agent,
22591
23005
  "history",
@@ -22647,7 +23061,7 @@ var OwneySDK = class {
22647
23061
  const chainId = this.requireChainId();
22648
23062
  if (agentId) {
22649
23063
  const agent = this.getAgent(agentId);
22650
- const readState = this.readStateFor(agentId, state);
23064
+ const readState = this.readStateFor(state);
22651
23065
  return this.readAgent(
22652
23066
  agent,
22653
23067
  "profile",
@@ -22870,7 +23284,7 @@ var OwneySDK = class {
22870
23284
  const entries = [...activeAgents.entries()];
22871
23285
  const balanceResults = await Promise.allSettled(
22872
23286
  entries.map(async ([id, agent]) => {
22873
- const readState = this.readStateFor(id, state);
23287
+ const readState = this.readStateFor(state);
22874
23288
  const b = await this.readAgent(
22875
23289
  agent,
22876
23290
  "balances",
@@ -22929,7 +23343,7 @@ var import_sdk2 = require("@zyfai/sdk");
22929
23343
 
22930
23344
  // src/agents/zyfai/zyfai.siwx-cache.ts
22931
23345
  var KEY_PREFIX7 = "owney.siwx.session";
22932
- var storage8 = () => {
23346
+ var storage10 = () => {
22933
23347
  if (typeof window === "undefined") return null;
22934
23348
  try {
22935
23349
  return window.localStorage;
@@ -22970,7 +23384,7 @@ var readLegacySiwxSession = (store, address) => {
22970
23384
  var readSiwxSession = (address, chainId) => {
22971
23385
  if (typeof window === "undefined") return null;
22972
23386
  const key2 = buildKey3(address);
22973
- const store = storage8();
23387
+ const store = storage10();
22974
23388
  let raw2 = null;
22975
23389
  try {
22976
23390
  raw2 = store?.getItem(key2) ?? null;
@@ -23000,7 +23414,7 @@ var writeSiwxSession = (address, _chainId, session) => {
23000
23414
  if (typeof window === "undefined") return;
23001
23415
  const key2 = buildKey3(address);
23002
23416
  memorySiwxSessions.set(key2, session);
23003
- const store = storage8();
23417
+ const store = storage10();
23004
23418
  try {
23005
23419
  store?.setItem(key2, JSON.stringify(session));
23006
23420
  } catch {
@@ -23009,7 +23423,7 @@ var writeSiwxSession = (address, _chainId, session) => {
23009
23423
  var clearSiwxSession = (address, _chainId) => {
23010
23424
  const key2 = buildKey3(address);
23011
23425
  memorySiwxSessions.delete(key2);
23012
- const store = storage8();
23426
+ const store = storage10();
23013
23427
  try {
23014
23428
  store?.removeItem(key2);
23015
23429
  } catch {