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

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
@@ -1723,7 +1723,7 @@ var SnapshotHistory = class {
1723
1723
  };
1724
1724
 
1725
1725
  // src/lib/funding-ledger.ts
1726
- var SDK_VERSION = "0.7.32-beta.12";
1726
+ var SDK_VERSION = "0.7.32-beta.14";
1727
1727
  var SCOPE2 = "funding-ledger";
1728
1728
  var REQUEST_TIMEOUT_MS2 = 5e3;
1729
1729
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -3996,14 +3996,16 @@ function splitOpportunity(opportunity) {
3996
3996
  }
3997
3997
  function mapEntries(rawEntries, chainId) {
3998
3998
  const actionMap = {
3999
- "Top up wallet": "Top up",
3999
+ // EOA -> smart wallet. Named "Top up" before ROUT-758; "Deposit" is what
4000
+ // users call it.
4001
+ "Top up wallet": "Deposit",
4000
4002
  "Partial withdraw from protocol": "Withdraw",
4001
4003
  "Withdraw from protocol": "Withdraw",
4002
- // The agent's own leg of a top up: the funds the user sent moving into the
4004
+ // The agent's own leg of a deposit: the funds the user sent moving into the
4003
4005
  // pool that earns the APY. Zyfai emits it as a separate entry seconds after
4004
- // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
4005
- // the public HistoryAction union, so no consumer type change is needed.
4006
- "Deposit to protocol": "Deposit",
4006
+ // "Top up wallet" and for slightly less (gas). Smart wallet -> pool, so
4007
+ // "Allocate" (ROUT-758; it was "Deposit").
4008
+ "Deposit to protocol": "Allocate",
4007
4009
  // Withdrawing from an async vault (Superform) is logged under its own
4008
4010
  // label and paid out later in a separate batch (ROUT-624).
4009
4011
  "Request async withdrawal": "Withdraw",
@@ -4054,7 +4056,7 @@ function mapEntries(rawEntries, chainId) {
4054
4056
  const asyncRequest = entry.action === "Request async withdrawal";
4055
4057
  const rawAmount2 = entry?.positions?.[0]?.amount;
4056
4058
  const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
4057
- const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
4059
+ const rawDelta = mappedAction === "Allocate" ? decodeDeltaAmount(
4058
4060
  entry?.positions?.[0]?.deltaAmount,
4059
4061
  tokenDecimals(entry?.positions?.[0]?.token_symbol)
4060
4062
  ) : void 0;
@@ -4332,7 +4334,7 @@ var isJwtExpired = (token) => {
4332
4334
  }
4333
4335
  };
4334
4336
  var memorySessions = /* @__PURE__ */ new Map();
4335
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
4337
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
4336
4338
  var readLegacySession = (store, address) => {
4337
4339
  if (!store) return null;
4338
4340
  const prefix = legacyKeyPrefix(address);
@@ -4414,13 +4416,27 @@ var clearSession = (address, _chainId) => {
4414
4416
  }
4415
4417
  readLegacySession(store, address);
4416
4418
  };
4419
+ var BrowserSessionStore = class {
4420
+ read(_agentId, address) {
4421
+ return readSession(address, 0);
4422
+ }
4423
+ write(_agentId, address, session) {
4424
+ writeSession(address, 0, session);
4425
+ }
4426
+ clear(_agentId, address) {
4427
+ clearSession(address, 0);
4428
+ }
4429
+ };
4417
4430
 
4418
4431
  // src/agents/zyfai/autoSelect.ts
4419
4432
  function buildAutoSelectUpdate(current, asset, chainId) {
4420
4433
  const chains = current.chains ?? [];
4421
4434
  const chainMissing = chainId !== void 0 && !chains.includes(chainId);
4422
- if (current.autoSelectProtocols === true && !chainMissing) return null;
4423
4435
  const nextChains = chainMissing ? [...chains, chainId] : chains;
4436
+ if (current.savedPoolChoices || current.autoSelectProtocols === false) {
4437
+ return chainMissing ? { asset, chains: nextChains } : null;
4438
+ }
4439
+ if (current.autoSelectProtocols === true && !chainMissing) return null;
4424
4440
  return {
4425
4441
  asset,
4426
4442
  autoSelectProtocols: true,
@@ -4429,15 +4445,34 @@ function buildAutoSelectUpdate(current, asset, chainId) {
4429
4445
  }
4430
4446
 
4431
4447
  // src/agents/zyfai/protocol-merge.ts
4432
- function buildProtocolMergeUpdate(available, current, asset) {
4448
+ function isExcludedProtocol(protocol, excluded) {
4449
+ if (excluded.length === 0) return false;
4450
+ const wanted = new Set(excluded.map((entry) => entry.toLowerCase()));
4451
+ return wanted.has(protocol.id.toLowerCase()) || protocol.name !== void 0 && wanted.has(protocol.name.toLowerCase());
4452
+ }
4453
+ function buildProtocolMergeUpdate(available, current, asset, excluded = []) {
4454
+ const excludedIds = /* @__PURE__ */ new Set([
4455
+ ...excluded.map((entry) => entry.toLowerCase()),
4456
+ ...available.filter((p) => isExcludedProtocol(p, excluded)).map((p) => p.id.toLowerCase())
4457
+ ]);
4458
+ const isExcludedId = (id) => excluded.length > 0 && excludedIds.has(id.toLowerCase());
4433
4459
  const enabled = current.protocols ?? [];
4434
- const enabledSet = new Set(enabled);
4435
- const missing = available.filter((p) => !enabledSet.has(p.id));
4436
- if (missing.length === 0) return null;
4460
+ const kept = enabled.filter((id) => !isExcludedId(id));
4461
+ const keptSet = new Set(kept);
4462
+ const missing = current.autoSelectProtocols === false ? [] : available.filter((p) => !keptSet.has(p.id) && !isExcluded(p));
4463
+ const fixAutoSelect = excluded.length > 0 && current.autoSelectProtocols !== false;
4464
+ const removedAny = kept.length !== enabled.length;
4465
+ if (missing.length === 0 && !removedAny && !fixAutoSelect) return null;
4466
+ const protocols = [.../* @__PURE__ */ new Set([...kept, ...missing.map((p) => p.id)])];
4467
+ if (protocols.length === 0) return null;
4437
4468
  return {
4438
4469
  asset,
4439
- protocols: [.../* @__PURE__ */ new Set([...enabled, ...missing.map((p) => p.id)])]
4470
+ protocols,
4471
+ ...excluded.length > 0 ? { autoSelectProtocols: false } : {}
4440
4472
  };
4473
+ function isExcluded(p) {
4474
+ return isExcludedProtocol(p, excluded);
4475
+ }
4441
4476
  }
4442
4477
 
4443
4478
  // src/agents/zyfai/splitting.ts
@@ -4570,11 +4605,107 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
4570
4605
  }
4571
4606
  function mergeScopedPoolNames(current, scoped, allAvailableNames) {
4572
4607
  const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
4608
+ const offered = new Set(allAvailableNames);
4573
4609
  const existing = current.autoselect ? allAvailableNames : current.pools;
4574
- const preserved = existing.filter((name) => !managed.has(name));
4610
+ const preserved = existing.filter(
4611
+ (name) => !managed.has(name) && (offered.size === 0 || offered.has(name))
4612
+ );
4575
4613
  const selected = scoped.flatMap((entry) => entry.pools);
4576
4614
  return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
4577
4615
  }
4616
+ function savedPoolRecords(customization, protocolId, chainId) {
4617
+ if (!customization || typeof customization !== "object") return [];
4618
+ const records = [];
4619
+ for (const byProtocol of Object.values(customization)) {
4620
+ const byChain = byProtocol?.[protocolId];
4621
+ const record2 = byChain?.[String(chainId)];
4622
+ if (!record2 || typeof record2 !== "object") continue;
4623
+ records.push({
4624
+ pools: Array.isArray(record2.pools) ? record2.pools.filter((name) => typeof name === "string") : [],
4625
+ autoselect: typeof record2.autoselect === "boolean" ? record2.autoselect : void 0
4626
+ });
4627
+ }
4628
+ return records;
4629
+ }
4630
+ function hasManualPoolChoices(customization) {
4631
+ return manuallyChosenProtocols(customization).size > 0;
4632
+ }
4633
+ function manuallyChosenProtocols(customization) {
4634
+ const chosen = /* @__PURE__ */ new Set();
4635
+ if (!customization || typeof customization !== "object") return chosen;
4636
+ for (const byProtocol of Object.values(customization)) {
4637
+ for (const [protocolId, byChain] of Object.entries(byProtocol ?? {})) {
4638
+ const manual = Object.values(byChain ?? {}).some(
4639
+ (record2) => record2?.autoselect === false
4640
+ );
4641
+ if (manual) chosen.add(protocolId);
4642
+ }
4643
+ }
4644
+ return chosen;
4645
+ }
4646
+ function manualChainsOf(customization, protocolId) {
4647
+ if (!customization || typeof customization !== "object") return [];
4648
+ const chains = /* @__PURE__ */ new Set();
4649
+ for (const byProtocol of Object.values(customization)) {
4650
+ const byChain = byProtocol?.[protocolId];
4651
+ for (const [chainKey, record2] of Object.entries(byChain ?? {})) {
4652
+ const chainId = Number(chainKey);
4653
+ if (Number.isFinite(chainId) && record2?.autoselect === false) {
4654
+ chains.add(chainId);
4655
+ }
4656
+ }
4657
+ }
4658
+ return [...chains];
4659
+ }
4660
+ function protocolsSyncLeavesOff(customization, available, assetChains) {
4661
+ const off = /* @__PURE__ */ new Set();
4662
+ for (const protocol of available) {
4663
+ const chains = (protocol.chains ?? []).filter((chainId) => assetChains.includes(chainId));
4664
+ if (chains.length === 0) continue;
4665
+ const decided = chains.every((chainId) => {
4666
+ const records = savedPoolRecords(customization, protocol.id, chainId);
4667
+ return records.length > 0 && !savedRecordsAreAuto(records);
4668
+ });
4669
+ if (decided) off.add(protocol.id);
4670
+ }
4671
+ return off;
4672
+ }
4673
+ function tokenIsAsset(token, asset) {
4674
+ const upper = token.toUpperCase();
4675
+ return asset === "WETH" ? upper === "WETH" || upper === "ETH" : upper === asset;
4676
+ }
4677
+ function savedRecordsAreAuto(records) {
4678
+ return records.length === 0 || records.some((record2) => record2.autoselect !== false);
4679
+ }
4680
+ function protocolsToKeep(params) {
4681
+ const { asset, chains, customization, catalogs } = params;
4682
+ const entries = params.selections.filter(
4683
+ (entry) => entry.asset === asset && entry.availablePools.length > 0
4684
+ );
4685
+ const picked = entries.filter((entry) => entry.pools.length > 0).map((entry) => entry.protocolId);
4686
+ const candidates = [.../* @__PURE__ */ new Set([...params.current, ...picked])];
4687
+ const inUse = (protocolId) => {
4688
+ if (picked.includes(protocolId)) return true;
4689
+ const catalog = catalogs.get(protocolId);
4690
+ if (!catalog || catalog.length === 0) return true;
4691
+ const covered = new Set(
4692
+ entries.filter((entry) => entry.protocolId === protocolId).map((entry) => entry.chainId)
4693
+ );
4694
+ const assetChains = new Set(chains);
4695
+ const toCheck = [.../* @__PURE__ */ new Set([...chains, ...manualChainsOf(customization, protocolId)])];
4696
+ return toCheck.some((chainId) => {
4697
+ if (covered.has(chainId)) return false;
4698
+ const offered = new Set(
4699
+ catalog.filter((pool) => pool.chainId === chainId && tokenIsAsset(pool.token, asset)).map((pool) => pool.name)
4700
+ );
4701
+ if (offered.size === 0) return false;
4702
+ const records = savedPoolRecords(customization, protocolId, chainId);
4703
+ return assetChains.has(chainId) && savedRecordsAreAuto(records) || records.some((record2) => record2.autoselect === false && record2.pools.some((name) => offered.has(name)));
4704
+ });
4705
+ };
4706
+ const kept = candidates.filter(inUse);
4707
+ return kept.length > 0 ? kept : candidates;
4708
+ }
4578
4709
  function mapAvailablePools(raw2) {
4579
4710
  const byChain = raw2 ?? {};
4580
4711
  if (typeof byChain !== "object" || byChain === null) return [];
@@ -4904,6 +5035,7 @@ var ERC7579_IS_MODULE_INSTALLED_ABI = (0, import_viem10.parseAbi)([
4904
5035
  "function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
4905
5036
  ]);
4906
5037
  var ZYFAI_SIGN_IN_REQUIRED_MESSAGE = "No Zyfai sign-in is available without a prompt.";
5038
+ var isPromiseLike = (value) => typeof value?.then === "function";
4907
5039
  var isSignInFailure = (error) => error instanceof OwneyError && error.code === "AGENT_AUTH_FAILED";
4908
5040
  var WETH_ADDRESS_BY_CHAIN = {
4909
5041
  8453: "0x4200000000000000000000000000000000000006",
@@ -4973,16 +5105,20 @@ function belowMinimumCeiling(rejection, token, decimals) {
4973
5105
  return idle === void 0 || minimum === void 0 ? void 0 : idle < minimum ? idle : minimum;
4974
5106
  }
4975
5107
  var ZyfaiAgent = class _ZyfaiAgent {
4976
- constructor(apiKey, rpcUrls, referralSource, accountReporting = {}) {
5108
+ constructor(apiKey, rpcUrls, referralSource, accountReporting = {}, sessionStore = new BrowserSessionStore(), excludedProtocols = []) {
4977
5109
  this.apiKey = apiKey;
4978
5110
  this.referralSource = referralSource;
4979
5111
  this.accountReporting = accountReporting;
5112
+ this.sessionStore = sessionStore;
5113
+ this.excludedProtocols = excludedProtocols;
4980
5114
  this.rpcUrls = resolveRpcUrls(rpcUrls);
4981
5115
  this.sdk = this.createSdk();
4982
5116
  }
4983
5117
  apiKey;
4984
5118
  referralSource;
4985
5119
  accountReporting;
5120
+ sessionStore;
5121
+ excludedProtocols;
4986
5122
  id = "zyfai";
4987
5123
  /** This adapter can hand its withdrawals to our server (part 4). */
4988
5124
  supportsServerTasks = true;
@@ -5134,7 +5270,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5134
5270
  */
5135
5271
  async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
5136
5272
  const movements = entries.filter(
5137
- (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
5273
+ (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Deposit") && e.transactions[0]?.txHashes[0]
5138
5274
  );
5139
5275
  if (movements.length === 0) return;
5140
5276
  const client = this.getPublicClient(chainId);
@@ -5191,6 +5327,48 @@ var ZyfaiAgent = class _ZyfaiAgent {
5191
5327
  })
5192
5328
  );
5193
5329
  }
5330
+ /**
5331
+ * The session store is a cache: an unavailable store must never block
5332
+ * authentication or teardown. Failures read as a cache miss. The store is
5333
+ * called synchronously, so a synchronous store (the browser default) has
5334
+ * already acted when this returns.
5335
+ */
5336
+ async storeOp(op) {
5337
+ try {
5338
+ return await op();
5339
+ } catch (error) {
5340
+ console.warn(
5341
+ "owney-sdk: agent session store failed, continuing without it",
5342
+ error
5343
+ );
5344
+ return null;
5345
+ }
5346
+ }
5347
+ /**
5348
+ * The fresh saved session for `address`, or null. Answered synchronously
5349
+ * when the store answers synchronously (the browser default), so a check
5350
+ * that must not yield keeps its order; a promise for an asynchronous store.
5351
+ * A store failure reads as no session.
5352
+ */
5353
+ savedSession(address) {
5354
+ let value;
5355
+ try {
5356
+ value = this.sessionStore.read(this.id, address);
5357
+ } catch (error) {
5358
+ console.warn("owney-sdk: agent session store failed, continuing without it", error);
5359
+ return null;
5360
+ }
5361
+ if (isPromiseLike(value)) {
5362
+ return Promise.resolve(value).then(
5363
+ (session) => isFreshSession(session) ? session : null,
5364
+ (error) => {
5365
+ console.warn("owney-sdk: agent session store failed, continuing without it", error);
5366
+ return null;
5367
+ }
5368
+ );
5369
+ }
5370
+ return isFreshSession(value) ? value : null;
5371
+ }
5194
5372
  /**
5195
5373
  * Patches `sdk.authenticateUser` so a fresh page can reuse the JWT from a
5196
5374
  * prior session instead of triggering a new SIWE prompt. Runs inside
@@ -5198,21 +5376,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
5198
5376
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
5199
5377
  * are populated, so the cache lookup has both keys it needs.
5200
5378
  *
5201
- * No-op on the server (no `window`) — the SDK is constructed during SSR
5202
- * for some apps and the patch only matters in the browser anyway.
5379
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
5380
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
5203
5381
  */
5204
5382
  installAuthCache(sdk = this.sdk) {
5205
- if (typeof window === "undefined") return;
5206
5383
  const internals = sdk;
5207
5384
  const original = internals.authenticateUser.bind(internals);
5208
5385
  let inFlight2 = null;
5209
5386
  const authenticate = async () => {
5210
5387
  if (internals.authenticatedUserId !== null) return;
5211
5388
  const address = internals.walletClient?.account?.address;
5212
- const chainId = internals.currentChainId ?? 0;
5213
5389
  if (address) {
5214
- const cached = readSession(address, chainId);
5215
- if (cached) {
5390
+ const cached = await this.storeOp(
5391
+ () => this.sessionStore.read(this.id, address)
5392
+ );
5393
+ if (isFreshSession(cached)) {
5216
5394
  internals.httpClient.setAuthToken(cached.token);
5217
5395
  internals.authenticatedUserId = cached.userId;
5218
5396
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -5223,15 +5401,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
5223
5401
  if (this.promptlessSdks.has(sdk)) throw this.signInRequired();
5224
5402
  await original();
5225
5403
  const newAddress = internals.walletClient?.account?.address;
5226
- const newChainId = internals.currentChainId ?? 0;
5227
5404
  const newToken = internals.httpClient.authToken;
5228
5405
  if (newAddress && newToken) {
5229
- writeSession(newAddress, newChainId, {
5230
- token: newToken,
5231
- userId: internals.authenticatedUserId,
5232
- hasActiveSessionKey: internals.hasActiveSessionKey,
5233
- isPredeployed: internals.isPredeployed
5234
- });
5406
+ await this.storeOp(
5407
+ () => this.sessionStore.write(this.id, newAddress, {
5408
+ token: newToken,
5409
+ userId: internals.authenticatedUserId,
5410
+ hasActiveSessionKey: internals.hasActiveSessionKey,
5411
+ isPredeployed: internals.isPredeployed
5412
+ })
5413
+ );
5235
5414
  }
5236
5415
  };
5237
5416
  internals.authenticateUser = () => {
@@ -5260,11 +5439,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
5260
5439
  * Whether connecting now would ask the wallet to sign in: not connected for
5261
5440
  * this wallet and chain (the check `connectAuth` returns early on) and no
5262
5441
  * fresh saved session. Never prompts; reads only what is saved.
5442
+ *
5443
+ * A session store that answers only asynchronously (a host's own
5444
+ * `sessionStore`) cannot be read here, so this throws: the caller counts an
5445
+ * unknown answer its own way (`OwneySDK.signInsNeeded` as a sign-in).
5263
5446
  */
5264
5447
  needsSignIn(state, chainId) {
5265
5448
  const owner = state.walletAddress.toLowerCase();
5266
5449
  if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === chainId) return false;
5267
- return readSession(state.walletAddress, chainId) === null;
5450
+ const saved = this.savedSession(state.walletAddress);
5451
+ if (isPromiseLike(saved)) {
5452
+ throw new Error("The Zyfai session store answers asynchronously; whether a sign-in is needed is unknown.");
5453
+ }
5454
+ return saved === null;
5268
5455
  }
5269
5456
  /** A read (promptless state) needs a sign-in it may not ask for. */
5270
5457
  signInRequired() {
@@ -5294,7 +5481,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
5294
5481
  else await this.connectAuthPromise;
5295
5482
  return this.connectAuth(state, chainId);
5296
5483
  }
5297
- if (promptless && readSession(state.walletAddress, validChainId) === null) throw this.signInRequired();
5484
+ if (promptless) {
5485
+ let saved = this.savedSession(state.walletAddress);
5486
+ if (isPromiseLike(saved)) {
5487
+ saved = await saved;
5488
+ if (saved === null) throw this.signInRequired();
5489
+ if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === validChainId || this.connectAuthPromise && this.connectAuthScope === scope) return this.connectAuth(state, chainId);
5490
+ }
5491
+ if (saved === null) throw this.signInRequired();
5492
+ }
5298
5493
  if (this.sdkHasConnected || this.connectedAddress) this.sdk = this.createSdk();
5299
5494
  this.sdkHasConnected = true;
5300
5495
  const executionSdk = this.sdk;
@@ -5354,8 +5549,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5354
5549
  if (!message.toLowerCase().includes("unauthorized")) throw error;
5355
5550
  const internals = executionSdk;
5356
5551
  const address = internals.walletClient?.account?.address;
5357
- if (promptless) throw this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
5358
- if (address) clearSession(address, chainId);
5552
+ if (promptless) throw await this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
5553
+ if (address) {
5554
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
5555
+ }
5359
5556
  return await executionSdk.connectAccount(provider, chainId);
5360
5557
  }
5361
5558
  }
@@ -5378,14 +5575,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5378
5575
  * the user's (connect, deposit, withdraw), on a new client. Returns the
5379
5576
  * read's error.
5380
5577
  */
5381
- dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
5578
+ async dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
5382
5579
  debugLog("zyfai:auth", "a read's session was refused; dropped without signing in again", { refusal });
5383
5580
  if (owner && typeof authToken === "string") {
5384
5581
  let dropped = false;
5385
- if (readSession(owner, 0)?.token === authToken) {
5386
- clearSession(owner, 0);
5387
- dropped = true;
5388
- }
5389
5582
  const internals = executionSdk;
5390
5583
  if (internals.httpClient.authToken === authToken) {
5391
5584
  dropped = true;
@@ -5395,6 +5588,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
5395
5588
  if (executionSdk === this.sdk && this.connectedAddress?.toLowerCase() === owner.toLowerCase())
5396
5589
  this.connectedChainId = null;
5397
5590
  }
5591
+ const saved = await this.savedSession(owner);
5592
+ if (saved?.token === authToken) {
5593
+ await this.storeOp(() => this.sessionStore.clear(this.id, owner));
5594
+ dropped = true;
5595
+ }
5398
5596
  if (dropped) this.tellSignInRefused();
5399
5597
  }
5400
5598
  return this.signInRequired();
@@ -5414,7 +5612,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5414
5612
  if (state.promptless !== true || error instanceof OwneyError) throw error;
5415
5613
  if (message.includes(ZYFAI_SIGN_IN_REQUIRED_MESSAGE)) throw this.signInRequired();
5416
5614
  if (!isZyfaiSessionRejected(message)) throw error;
5417
- throw this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
5615
+ throw await this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
5418
5616
  }
5419
5617
  }
5420
5618
  /**
@@ -5450,7 +5648,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
5450
5648
  dropWithdrawalSession(state, chainId, authToken) {
5451
5649
  const internals = this.sdk;
5452
5650
  if (typeof authToken !== "string" || internals.httpClient.authToken !== authToken || this.connectedAddress?.toLowerCase() !== state.walletAddress.toLowerCase() || this.connectedChainId !== chainId) return;
5453
- clearSession(state.walletAddress, chainId);
5651
+ const owner = state.walletAddress;
5652
+ void this.storeOp(() => this.sessionStore.clear(this.id, owner));
5454
5653
  internals.httpClient.clearAuthToken();
5455
5654
  internals.authenticatedUserId = null;
5456
5655
  this.connectedChainId = null;
@@ -5486,7 +5685,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
5486
5685
  );
5487
5686
  return;
5488
5687
  }
5489
- const update = buildProtocolMergeUpdate(available, current, asset);
5688
+ const decided = protocolsSyncLeavesOff(
5689
+ current.customization,
5690
+ available,
5691
+ current.chains ?? []
5692
+ );
5693
+ const excluded = this.excludedProtocols.length === 0 ? [] : [
5694
+ ...this.excludedProtocols,
5695
+ ...available.filter((protocol) => isExcludedProtocol(protocol, this.excludedProtocols)).map((protocol) => protocol.id)
5696
+ ];
5697
+ const update = buildProtocolMergeUpdate(
5698
+ available.filter((protocol) => !decided.has(protocol.id)),
5699
+ current,
5700
+ asset,
5701
+ excluded
5702
+ );
5490
5703
  if (!update) return;
5491
5704
  await this.sdk.updateUserProfile(update);
5492
5705
  debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
@@ -5560,9 +5773,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
5560
5773
  this.holdActiveScopes.clear();
5561
5774
  this.pendingRegistrations.clear();
5562
5775
  this.lastGoodEarnings.clear();
5563
- if (!options?.keepSignIns && this.connectedAddress && this.connectedChainId !== null) {
5564
- clearSession(this.connectedAddress, this.connectedChainId);
5565
- }
5776
+ const address = this.connectedAddress;
5777
+ const sessionCleared = !options?.keepSignIns && address ? this.storeOp(() => this.sessionStore.clear(this.id, address)) : void 0;
5566
5778
  this.connectedAddress = null;
5567
5779
  this.connectedChainId = null;
5568
5780
  this.connectAuthPromise = null;
@@ -5572,6 +5784,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5572
5784
  this.reportedAccounts.clear();
5573
5785
  this.sdk = this.createSdk();
5574
5786
  this.sdkHasConnected = false;
5787
+ await sessionCleared;
5575
5788
  await executionSdk.disconnectAccount();
5576
5789
  }
5577
5790
  // --- IAgent: Account lifecycle ---
@@ -5783,9 +5996,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
5783
5996
  * lookup fails is skipped rather than failing the whole catalogue.
5784
5997
  */
5785
5998
  async getPoolCatalog(params) {
5786
- const { protocols: universe } = await this.sdk.getAvailableProtocols(
5999
+ const { protocols: allProtocols } = await this.sdk.getAvailableProtocols(
5787
6000
  this.supportedChainIds[0]
5788
6001
  );
6002
+ const universe = allProtocols.filter(
6003
+ (protocol) => !isExcludedProtocol(protocol, this.excludedProtocols)
6004
+ );
5789
6005
  const poolResults = await Promise.all(
5790
6006
  universe.map(async (protocol) => {
5791
6007
  try {
@@ -5828,14 +6044,23 @@ var ZyfaiAgent = class _ZyfaiAgent {
5828
6044
  group.push(entry);
5829
6045
  byPair.set(pair, group);
5830
6046
  }
6047
+ const catalogReads = /* @__PURE__ */ new Map();
6048
+ const catalogOf = (protocolId) => {
6049
+ let read2 = catalogReads.get(protocolId);
6050
+ if (!read2) {
6051
+ read2 = this.sdk.getAvailablePools(protocolId, "yieldmaxxing").then(mapAvailablePools);
6052
+ catalogReads.set(protocolId, read2);
6053
+ }
6054
+ return read2;
6055
+ };
5831
6056
  const customizations = await Promise.all(
5832
6057
  [...byPair.values()].map(async (scoped) => {
5833
6058
  const { protocolId, chainId } = scoped[0];
5834
- const [current, rawAvailable] = await Promise.all([
6059
+ const [current, catalog] = await Promise.all([
5835
6060
  this.sdk.getSelectedPools(protocolId, chainId),
5836
- this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
6061
+ catalogOf(protocolId)
5837
6062
  ]);
5838
- const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
6063
+ const allAvailableNames = catalog.filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5839
6064
  return {
5840
6065
  protocolId,
5841
6066
  chainId,
@@ -5859,13 +6084,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
5859
6084
  await Promise.all(
5860
6085
  selection.strategies.map(async ({ asset, strategy }) => {
5861
6086
  const current = await this.sdk.getUserDetails(asset);
5862
- const selectedProtocols = selection.selections.filter(
5863
- (entry) => entry.asset === asset && entry.pools.length > 0
5864
- ).map((entry) => entry.protocolId);
5865
- const protocols = [
5866
- .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
5867
- ];
5868
- await this.sdk.updateUserProfile({ asset, strategy, protocols });
6087
+ const listed = current.protocols ?? [];
6088
+ const unpicked = listed.filter((protocolId) => !selection.selections.some(
6089
+ (entry) => entry.asset === asset && entry.protocolId === protocolId && entry.pools.length > 0
6090
+ ));
6091
+ const catalogs = new Map(await Promise.all(unpicked.map(async (protocolId) => [protocolId, await catalogOf(protocolId).catch(() => null)])));
6092
+ const protocols = protocolsToKeep({
6093
+ asset,
6094
+ current: listed,
6095
+ chains: current.chains ?? [],
6096
+ selections: selection.selections,
6097
+ customization: current.customization,
6098
+ catalogs
6099
+ });
6100
+ await this.sdk.updateUserProfile({
6101
+ asset,
6102
+ strategy,
6103
+ protocols,
6104
+ autoSelectProtocols: false
6105
+ });
5869
6106
  })
5870
6107
  );
5871
6108
  } catch (error) {
@@ -5916,6 +6153,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5916
6153
  }
5917
6154
  for (const protocol of universe) {
5918
6155
  if (excluded.has(protocol.id)) continue;
6156
+ if (isExcludedProtocol(protocol, this.excludedProtocols)) continue;
5919
6157
  try {
5920
6158
  const names = mapAvailablePools(await this.sdk.getAvailablePools(protocol.id, "yieldmaxxing")).filter((pool) => pool.chainId === chainId && pool.token.toUpperCase() === asset).map((pool) => pool.name);
5921
6159
  if (names.length === 0) continue;
@@ -6302,6 +6540,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
6302
6540
  assertCurrent();
6303
6541
  const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
6304
6542
  debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
6543
+ if (this.excludedProtocols.length > 0) {
6544
+ assertCurrent();
6545
+ await this.ensureProtocolsSynced(validChainId, asset);
6546
+ }
6305
6547
  if (isOwneyDebug()) {
6306
6548
  try {
6307
6549
  const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
@@ -7726,7 +7968,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
7726
7968
  const update = buildAutoSelectUpdate(
7727
7969
  {
7728
7970
  autoSelectProtocols: current.autoSelectProtocols,
7729
- chains: current.chains
7971
+ chains: current.chains,
7972
+ savedPoolChoices: hasManualPoolChoices(current.customization)
7730
7973
  },
7731
7974
  asset,
7732
7975
  isValidChainId(chainId)
@@ -8510,6 +8753,10 @@ function dailyApy(point) {
8510
8753
  if (principal <= 0n || earned === 0n) return 0;
8511
8754
  return Number(earned) / Number(principal) * 365 * 100;
8512
8755
  }
8756
+ var DUST_USD = 5e-3;
8757
+ function heldPosition(tokens, priceUsd) {
8758
+ return Number.isFinite(priceUsd) && priceUsd > 0 ? tokens * priceUsd >= DUST_USD : tokens > 0;
8759
+ }
8513
8760
  function aggregateHistory(contexts, dayCount, now, scopedAsset) {
8514
8761
  const today = new Date(now).toISOString().slice(0, 10);
8515
8762
  const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
@@ -8526,6 +8773,7 @@ function aggregateHistory(contexts, dayCount, now, scopedAsset) {
8526
8773
  if (!Number.isFinite(amount) || amount < 0) {
8527
8774
  invalid("historic position", "expected a finite non-negative balance");
8528
8775
  }
8776
+ if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
8529
8777
  const current = byDate.get(point.date) ?? { weighted: 0, amount: 0 };
8530
8778
  current.weighted += dailyApy(point) * amount;
8531
8779
  current.amount += amount;
@@ -8546,7 +8794,8 @@ function historyCoverage2(contexts, dayCount, now) {
8546
8794
  for (const context of contexts) {
8547
8795
  for (const point of context.historic?.dailyYieldSnapshots ?? []) {
8548
8796
  if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
8549
- if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
8797
+ const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
8798
+ if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
8550
8799
  const asset = context.asset.toUpperCase();
8551
8800
  const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
8552
8801
  dates.add(point.date);
@@ -8588,7 +8837,7 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scop
8588
8837
  }
8589
8838
  function actionType(value) {
8590
8839
  const normalized = value.toLowerCase();
8591
- if (normalized.includes("deposit")) return "Deposit";
8840
+ if (normalized.includes("deposit")) return "Allocate";
8592
8841
  if (normalized.includes("withdraw")) return "Withdraw";
8593
8842
  if (normalized.includes("yield") || normalized.includes("earn"))
8594
8843
  return "Earned";
@@ -8649,14 +8898,87 @@ function allocationLegs(value, context, requireAmount) {
8649
8898
  }
8650
8899
  return legs;
8651
8900
  }
8652
- function allocationEntry(action, context) {
8901
+ function vaultBook(context, vaultAddresses, catalog = []) {
8902
+ const base7 = context.agent.assetAddress.toLowerCase();
8903
+ const labels = /* @__PURE__ */ new Map();
8904
+ const name = (address, label) => {
8905
+ if (typeof address !== "string" || !(0, import_viem12.isAddress)(address)) return;
8906
+ const key2 = address.toLowerCase();
8907
+ if (!labels.has(key2)) labels.set(key2, label);
8908
+ };
8909
+ for (const action of context.actions ?? []) {
8910
+ for (const list of [action.details?.deposits, action.details?.withdrawals]) {
8911
+ if (!Array.isArray(list)) continue;
8912
+ for (const leg of list) {
8913
+ if (leg && typeof leg.vaultProvider === "string" && leg.vaultProvider)
8914
+ name(leg.vaultAddress, {
8915
+ protocol: leg.vaultProvider,
8916
+ ...typeof leg.vaultName === "string" && leg.vaultName ? { pool: leg.vaultName } : {}
8917
+ });
8918
+ }
8919
+ }
8920
+ }
8921
+ for (const option of [...context.positions.map((entry) => entry.vaultOption), ...catalog])
8922
+ if (option?.chainId === context.agent.chainId)
8923
+ name(option.address, { protocol: option.provider || "Vault", ...option.name ? { pool: option.name } : {} });
8924
+ for (const asset of context.historic?.assets ?? [])
8925
+ if (asset.chainId === context.agent.chainId && !asset.isSpam && asset.address.toLowerCase() !== base7)
8926
+ name(asset.address, { protocol: "Vault", ...asset.name || asset.symbol ? { pool: asset.name || asset.symbol } : {} });
8927
+ const addresses = /* @__PURE__ */ new Set([...vaultAddresses, ...labels.keys()]);
8928
+ return { addresses, label: (address) => labels.get(address.toLowerCase()) ?? { protocol: "Vault" } };
8929
+ }
8930
+ function recycledDeposits(context, movements, vaults) {
8931
+ const base7 = context.agent.assetAddress.toLowerCase();
8932
+ const agentWallet = context.wallet.walletAddress.toLowerCase();
8933
+ const relevant = movements.filter((movement) => movement.chainId === context.agent.chainId && movement.assetAddress.toLowerCase() === base7 && /^\d+$/.test(movement.assetAmount) && BigInt(movement.assetAmount) > 0n && (movement.fromAddress.toLowerCase() === agentWallet || movement.toAddress.toLowerCase() === agentWallet)).sort((a, b) => a.blockDate.localeCompare(b.blockDate) || a.blockNumber - b.blockNumber || a.logIndex - b.logIndex);
8934
+ const transactions = /* @__PURE__ */ new Map();
8935
+ for (const movement of relevant) {
8936
+ const hash2 = movement.transactionHash.toLowerCase();
8937
+ transactions.set(hash2, [...transactions.get(hash2) ?? [], movement]);
8938
+ }
8939
+ const held = [];
8940
+ const spend = (amount) => {
8941
+ const used = [];
8942
+ while (amount > 0n && held.length) {
8943
+ const first = held[0];
8944
+ const taken = first.amount < amount ? first.amount : amount;
8945
+ if (!used.some((entry) => entry.vault === first.vault && entry.hash === first.hash))
8946
+ used.push({ vault: first.vault, hash: first.hash });
8947
+ first.amount -= taken;
8948
+ amount -= taken;
8949
+ if (first.amount === 0n) held.shift();
8950
+ }
8951
+ return used;
8952
+ };
8953
+ const covered = /* @__PURE__ */ new Map();
8954
+ for (const [hash2, legs] of transactions) {
8955
+ let deposited = 0n;
8956
+ for (const movement of legs) {
8957
+ const from = movement.fromAddress.toLowerCase();
8958
+ const to = movement.toAddress.toLowerCase();
8959
+ const amount = BigInt(movement.assetAmount);
8960
+ if (to === agentWallet && from !== agentWallet) {
8961
+ if (vaults.has(from)) held.push({ vault: from, hash: hash2, amount });
8962
+ } else if (from === agentWallet && to !== agentWallet) {
8963
+ if (vaults.has(to)) deposited += amount;
8964
+ else spend(amount);
8965
+ }
8966
+ }
8967
+ if (deposited === 0n) continue;
8968
+ const available = held.reduce((total, entry) => total + entry.amount, 0n);
8969
+ const used = spend(deposited);
8970
+ if (available >= deposited) covered.set(hash2, used);
8971
+ }
8972
+ return covered;
8973
+ }
8974
+ function allocationEntry(action, context, evidence) {
8653
8975
  if (action.actionType.toLowerCase() !== "autoseek") return void 0;
8654
8976
  const hash2 = action.details?.depositTransactionHash;
8655
8977
  const withdrawHash = action.details?.withdrawTransactionHash;
8656
8978
  if (typeof hash2 !== "string" || !TX_HASH3.test(hash2)) return null;
8657
8979
  const deposits = allocationLegs(action.details?.deposits, context, true);
8658
- const withdrawals = action.details?.withdrawals == null ? [] : allocationLegs(action.details.withdrawals, context, false);
8659
- if (!deposits?.length || !withdrawals) return null;
8980
+ const listed = action.details?.withdrawals == null ? [] : allocationLegs(action.details.withdrawals, context, false);
8981
+ if (!deposits?.length || !listed) return null;
8660
8982
  const decimals = YIELDSEEKER_ASSET_METADATA[context.asset].decimals;
8661
8983
  const positions = deposits.map((leg) => ({
8662
8984
  protocol: leg.protocol,
@@ -8665,15 +8987,26 @@ function allocationEntry(action, context) {
8665
8987
  amount: (0, import_viem12.formatUnits)(leg.rawAmount, decimals)
8666
8988
  }));
8667
8989
  const amountRaw = deposits.reduce((total, leg) => total + leg.rawAmount, 0n);
8990
+ const withdrawTx = typeof withdrawHash === "string" && TX_HASH3.test(withdrawHash) && withdrawHash.toLowerCase() !== hash2.toLowerCase() ? withdrawHash : void 0;
8991
+ let withdrawals = listed;
8992
+ let hashes = listed.length && withdrawTx ? [hash2, withdrawTx] : [hash2];
8993
+ if (!listed.length) {
8994
+ const agentWallet = context.wallet.walletAddress.toLowerCase();
8995
+ const inWithdrawTx = withdrawTx ? evidence.movements.filter((movement) => movement.transactionHash.toLowerCase() === withdrawTx.toLowerCase() && movement.assetAddress.toLowerCase() === context.agent.assetAddress.toLowerCase() && movement.toAddress.toLowerCase() === agentWallet && evidence.book.addresses.has(movement.fromAddress.toLowerCase())).map((movement) => ({ vault: movement.fromAddress.toLowerCase(), hash: withdrawTx })) : [];
8996
+ const recycled = evidence.recycled.get(hash2.toLowerCase()) ?? [];
8997
+ const sources = inWithdrawTx.length ? inWithdrawTx : recycled;
8998
+ withdrawals = [...new Set(sources.map((source2) => source2.vault))].map((vault) => evidence.book.label(vault));
8999
+ hashes = [hash2, ...new Set(withdrawTx ? [withdrawTx] : sources.map((source2) => source2.hash).filter((value) => value !== hash2.toLowerCase()))];
9000
+ }
8668
9001
  const rebalance = withdrawals.length > 0;
8669
- const hashes = rebalance && typeof withdrawHash === "string" && TX_HASH3.test(withdrawHash) && withdrawHash.toLowerCase() !== hash2.toLowerCase() ? [hash2, withdrawHash] : [hash2];
9002
+ if (!rebalance) hashes = [hash2];
8670
9003
  const source = withdrawals.length === 1 ? withdrawals[0] : {
8671
9004
  protocol: [...new Set(withdrawals.map((leg) => leg.protocol))].join(" + "),
8672
9005
  pool: withdrawals.map((leg) => leg.pool).filter(Boolean).join(" + ") || void 0
8673
9006
  };
8674
9007
  return {
8675
9008
  agent: "yieldseeker",
8676
- action: rebalance ? "Rebalance" : "Deposit",
9009
+ action: rebalance ? "Rebalance" : "Allocate",
8677
9010
  date: action.createdDate,
8678
9011
  oldApy: null,
8679
9012
  newApy: null,
@@ -8720,17 +9053,17 @@ function movementEntry(movement, wallet, agent, asset, ownerAddress, vaultAddres
8720
9053
  }
8721
9054
  let action;
8722
9055
  if (to === agentWallet && !vaultAddresses.has(from)) {
8723
- action = "Top up";
9056
+ action = "Deposit";
8724
9057
  } else if (from === agentWallet && to === owner) {
8725
9058
  action = "Withdraw";
8726
9059
  } else if (from === agentWallet && destination) {
8727
- action = "Deposit";
9060
+ action = "Allocate";
8728
9061
  }
8729
9062
  if (!action) return void 0;
8730
9063
  return {
8731
9064
  agent: "yieldseeker",
8732
9065
  action,
8733
- ...action === "Deposit" && destination ? { positions: [{
9066
+ ...action === "Allocate" && destination ? { positions: [{
8734
9067
  ...destination,
8735
9068
  amount: decimal(movement.assetAmount, YIELDSEEKER_ASSET_METADATA[asset].decimals, "historic position")
8736
9069
  }] } : {},
@@ -8767,11 +9100,13 @@ function mapYieldseekerHistory(contexts, options) {
8767
9100
  seenMovements.add(key2);
8768
9101
  return true;
8769
9102
  });
9103
+ const book = vaultBook(context, options.vaultAddresses, options.vaultOptions);
9104
+ const evidence = { book, movements, recycled: recycledDeposits(context, movements, book.addresses) };
8770
9105
  const allocations = /* @__PURE__ */ new Map();
8771
9106
  const rebalanceHashes = /* @__PURE__ */ new Set();
8772
9107
  const actions = [];
8773
9108
  for (const action of context.actions ?? []) {
8774
- const allocation = allocationEntry(action, context);
9109
+ const allocation = allocationEntry(action, context, evidence);
8775
9110
  if (allocation === null) continue;
8776
9111
  if (!allocation) {
8777
9112
  const entry = actionEntry(action);
@@ -8791,11 +9126,11 @@ function mapYieldseekerHistory(contexts, options) {
8791
9126
  context.agent,
8792
9127
  context.asset,
8793
9128
  options.ownerAddress,
8794
- options.vaultAddresses,
9129
+ book.addresses,
8795
9130
  depositDestination(context, movement)
8796
9131
  )
8797
- ).filter((entry) => entry !== void 0 && !((entry.action === "Deposit" || entry.action === "Top up") && rebalanceHashes.has(entry.transactions[0]?.txHashes[0]?.toLowerCase() ?? "")));
8798
- const deposits = new Set(movementEntries.filter((entry) => entry.action === "Deposit").map((entry) => entry.transactions[0]?.txHashes[0]?.toLowerCase()));
9132
+ ).filter((entry) => entry !== void 0 && !((entry.action === "Allocate" || entry.action === "Deposit") && rebalanceHashes.has(entry.transactions[0]?.txHashes[0]?.toLowerCase() ?? "")));
9133
+ const deposits = new Set(movementEntries.filter((entry) => entry.action === "Allocate").map((entry) => entry.transactions[0]?.txHashes[0]?.toLowerCase()));
8799
9134
  for (const [hash2, allocation] of allocations)
8800
9135
  if (allocation.action === "Rebalance" || !deposits.has(hash2)) actions.push(allocation);
8801
9136
  return [...movementEntries, ...actions];
@@ -8816,14 +9151,14 @@ function mapYieldseekerHistory(contexts, options) {
8816
9151
  grouped.set(key2, entry);
8817
9152
  continue;
8818
9153
  }
8819
- if (entry.action === "Deposit" && entry.positions?.length) {
9154
+ if (entry.action === "Allocate" && entry.positions?.length) {
8820
9155
  if (!previous.positions?.length) {
8821
9156
  grouped.set(key2, entry);
8822
9157
  continue;
8823
9158
  }
8824
9159
  previous.positions.push(...entry.positions);
8825
9160
  previous.transactions.push(...entry.transactions);
8826
- } else if ((entry.action === "Top up" || entry.action === "Withdraw") && tx.amountRaw) {
9161
+ } else if ((entry.action === "Deposit" || entry.action === "Withdraw") && tx.amountRaw) {
8827
9162
  const target = previous.transactions[0];
8828
9163
  const known = new Set(target.logIndexes ?? []);
8829
9164
  if (tx.logIndexes?.some((index) => !known.has(index))) {
@@ -9781,7 +10116,7 @@ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9781
10116
  var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9782
10117
  var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9783
10118
  var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9784
- var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
10119
+ var WITHDRAWAL_UNDER_WAY_MAX_AGE_MS = 60 * 6e4;
9785
10120
  var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9786
10121
  var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9787
10122
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
@@ -10707,6 +11042,7 @@ var YieldseekerAgent = class {
10707
11042
  }
10708
11043
  async withdraw(state, chainId, asset, amount, onProgress, gasMode = "auto", onBeforeSubmission, assertOperation, submission) {
10709
11044
  let ownerTransferAttempted = false;
11045
+ const startedAt = Date.now();
10710
11046
  let evidence = {
10711
11047
  agentId: this.id,
10712
11048
  chainId,
@@ -10748,6 +11084,10 @@ var YieldseekerAgent = class {
10748
11084
  delivery: "failed"
10749
11085
  });
10750
11086
  throw error;
11087
+ } finally {
11088
+ for (const [wallet, markedAt] of this.releasingWallets) {
11089
+ if (markedAt >= startedAt) this.releasingWallets.delete(wallet);
11090
+ }
10751
11091
  }
10752
11092
  }
10753
11093
  async withdrawInternal(state, chainId, asset, amount, onProgress, onOwnerTransferAttempted, gasMode = "auto", onBeforeSubmission, assertOperation, operationId) {
@@ -11899,7 +12239,6 @@ var YieldseekerAgent = class {
11899
12239
  const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11900
12240
  if (await this.withdrawalUnderWay(state, chainId, slotAsset, context))
11901
12241
  return { notified: false, reason: "WITHDRAWAL_IN_PROGRESS" };
11902
- const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11903
12242
  let notified = false;
11904
12243
  let reason = "NOT_ALLOCATED";
11905
12244
  while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
@@ -11920,14 +12259,6 @@ var YieldseekerAgent = class {
11920
12259
  if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11921
12260
  const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11922
12261
  if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
11923
- if (cooldownEnds !== null)
11924
- return {
11925
- notified: true,
11926
- attempts,
11927
- allocated: false,
11928
- reason: "RECENT_WITHDRAWAL",
11929
- allocatesAfter: new Date(cooldownEnds).toISOString()
11930
- };
11931
12262
  reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11932
12263
  }
11933
12264
  return { notified: true, attempts, allocated: false, reason };
@@ -11984,11 +12315,6 @@ var YieldseekerAgent = class {
11984
12315
  debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11985
12316
  }
11986
12317
  }
11987
- /**
11988
- * When Yieldseeker may move funds again after this agent wallet's last
11989
- * confirmed withdrawal, if that is still ahead; null when there was none in
11990
- * the last hour or the ledger cannot say.
11991
- */
11992
12318
  /**
11993
12319
  * A withdrawal from this agent wallet that has started but not finished,
11994
12320
  * within the last hour: released by this page, or listed on the ledger with
@@ -11997,26 +12323,11 @@ var YieldseekerAgent = class {
11997
12323
  */
11998
12324
  async withdrawalUnderWay(state, chainId, asset, context) {
11999
12325
  const wallet = context.wallet.walletAddress.toLowerCase();
12000
- const since = Date.now() - YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
12326
+ const since = Date.now() - WITHDRAWAL_UNDER_WAY_MAX_AGE_MS;
12001
12327
  if ((this.releasingWallets.get(wallet) ?? 0) > since) return true;
12002
12328
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
12003
12329
  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
12330
  }
12005
- async withdrawalCooldownEnd(state, chainId, asset, context) {
12006
- const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
12007
- const wallet = context.wallet.walletAddress.toLowerCase();
12008
- let latest = 0;
12009
- for (const row of rows ?? []) {
12010
- if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
12011
- for (const leg of row.legs) {
12012
- if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
12013
- const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
12014
- if (Number.isFinite(at)) latest = Math.max(latest, at);
12015
- }
12016
- }
12017
- const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
12018
- return latest > 0 && ends > Date.now() ? ends : null;
12019
- }
12020
12331
  /**
12021
12332
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
12022
12333
  * not collected from it, read at one block for a balance read. Cached
@@ -12146,16 +12457,18 @@ var YieldseekerAgent = class {
12146
12457
  (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
12147
12458
  )
12148
12459
  );
12460
+ const vaultOptions = catalog.flat().filter(
12461
+ (vaultOption) => vaultOption.chainId === chainId && (0, import_viem17.isAddress)(vaultOption.address)
12462
+ );
12149
12463
  const vaultAddresses = new Set(
12150
- catalog.flat().filter(
12151
- (vaultOption) => vaultOption.chainId === chainId && (0, import_viem17.isAddress)(vaultOption.address)
12152
- ).map((vaultOption) => vaultOption.address.toLowerCase())
12464
+ vaultOptions.map((vaultOption) => vaultOption.address.toLowerCase())
12153
12465
  );
12154
12466
  return mapYieldseekerHistory(contexts, {
12155
12467
  limit: options?.limit ?? 10,
12156
12468
  cursor: options?.cursor,
12157
12469
  ownerAddress: state.walletAddress,
12158
12470
  vaultAddresses,
12471
+ vaultOptions,
12159
12472
  ...options?.fromDate ? { fromDate: options.fromDate } : {},
12160
12473
  ...options?.toDate ? { toDate: options.toDate } : {}
12161
12474
  });
@@ -17283,7 +17596,6 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
17283
17596
  // src/lib/walletconnect-switch.ts
17284
17597
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
17285
17598
  var HOLD_CHAIN_MS = 15e3;
17286
- var MAX_RESENDS = 2;
17287
17599
  var holds = /* @__PURE__ */ new Map();
17288
17600
  function parseChainId(raw2) {
17289
17601
  if (typeof raw2 === "number") return raw2;
@@ -17292,28 +17604,76 @@ function parseChainId(raw2) {
17292
17604
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
17293
17605
  return Number.isFinite(id) ? id : void 0;
17294
17606
  }
17295
- function walletConnectCore(provider) {
17607
+ function walletConnectSession(provider) {
17296
17608
  const p = provider;
17297
17609
  const core = p?.signer ?? p;
17298
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
17610
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
17299
17611
  return null;
17300
17612
  }
17301
17613
  const peer = core.session.peer?.metadata?.name ?? "";
17302
- if (!/metamask/i.test(peer)) return null;
17303
- return core;
17614
+ if (/metamask/i.test(peer)) {
17615
+ return { core, strategy: "remote-wallet" };
17616
+ }
17617
+ if (/fireblocks/i.test(peer)) {
17618
+ return { core, strategy: "session-default" };
17619
+ }
17620
+ return null;
17621
+ }
17622
+ function approvedChains(core) {
17623
+ const approved = /* @__PURE__ */ new Set();
17624
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
17625
+ for (const chain2 of namespace.chains ?? []) approved.add(chain2);
17626
+ for (const account of namespace.accounts ?? []) {
17627
+ const [namespaceName, reference] = account.split(":");
17628
+ if (namespaceName && reference) {
17629
+ approved.add(`${namespaceName}:${reference}`);
17630
+ }
17631
+ }
17632
+ }
17633
+ return approved;
17634
+ }
17635
+ async function selectSessionDefaultChain(core, chainId) {
17636
+ const target = `eip155:${chainId}`;
17637
+ if (!approvedChains(core).has(target)) {
17638
+ throw new Error(
17639
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
17640
+ );
17641
+ }
17642
+ core.setDefaultChain(target);
17643
+ const selected = parseChainId(
17644
+ await core.request({ method: "eth_chainId" })
17645
+ );
17646
+ debugLog("wc-switch", "selected WalletConnect session default", {
17647
+ peer: core.session.peer?.metadata?.name,
17648
+ target: chainId,
17649
+ selected
17650
+ });
17651
+ if (selected !== chainId) {
17652
+ throw new Error(
17653
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
17654
+ );
17655
+ }
17304
17656
  }
17305
17657
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
17306
- const core = walletConnectCore(provider);
17307
- if (!core) return false;
17658
+ const session = walletConnectSession(provider);
17659
+ if (!session) return false;
17660
+ const { core, strategy } = session;
17308
17661
  holds.get(core.session.topic)?.();
17662
+ if (strategy === "session-default") {
17663
+ await selectSessionDefaultChain(core, chainId);
17664
+ return true;
17665
+ }
17309
17666
  await requestSwitch(core, provider, chainId, timeoutMs);
17310
- holdChain(core, provider, chainId);
17667
+ holdChain(core, chainId);
17311
17668
  return true;
17312
17669
  }
17313
17670
  async function requestSwitch(core, provider, chainId, timeoutMs) {
17314
- const current = Number(
17671
+ const current = parseChainId(
17315
17672
  await provider.request({ method: "eth_chainId" })
17316
17673
  );
17674
+ if (current === void 0) {
17675
+ throw new Error("WalletConnect could not report its current chain.");
17676
+ }
17317
17677
  const hexChainId = `0x${chainId.toString(16)}`;
17318
17678
  let timer;
17319
17679
  try {
@@ -17343,26 +17703,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
17343
17703
  } catch {
17344
17704
  }
17345
17705
  }
17346
- function holdChain(core, provider, chainId) {
17706
+ function holdChain(core, chainId) {
17347
17707
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
17348
17708
  return;
17349
17709
  }
17350
- let resends = 0;
17710
+ let repins = 0;
17351
17711
  const listener = (raw2) => {
17352
17712
  const reported = parseChainId(raw2);
17353
17713
  debugLog("wc-switch", "wallet reported chain", {
17354
17714
  reported,
17355
17715
  holding: chainId,
17356
- resends
17716
+ repins
17357
17717
  });
17358
17718
  if (reported === void 0 || reported === chainId) return;
17359
- if (resends >= MAX_RESENDS) return;
17360
- resends += 1;
17361
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
17362
- (error) => debugLog("wc-switch", "re-switch failed", {
17719
+ repins += 1;
17720
+ try {
17721
+ core.setDefaultChain(`eip155:${chainId}`);
17722
+ } catch (error) {
17723
+ debugLog("wc-switch", "session re-pin failed", {
17363
17724
  error: error instanceof Error ? error.message : String(error)
17364
- })
17365
- );
17725
+ });
17726
+ }
17366
17727
  };
17367
17728
  const release = () => {
17368
17729
  clearTimeout(timer);
@@ -17376,7 +17737,7 @@ function holdChain(core, provider, chainId) {
17376
17737
  holds.set(core.session.topic, release);
17377
17738
  }
17378
17739
  function withWalletConnectSwitch(provider) {
17379
- if (!walletConnectCore(provider)) return provider;
17740
+ if (!walletConnectSession(provider)) return provider;
17380
17741
  const target = provider;
17381
17742
  const request2 = async (args) => {
17382
17743
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -17727,6 +18088,7 @@ var OwneySDK = class {
17727
18088
  yieldseekerApiBaseUrl;
17728
18089
  yieldseekerSiweOrigin;
17729
18090
  userPoolCustomization = false;
18091
+ excludedProtocols = [];
17730
18092
  routingApiBaseUrl;
17731
18093
  referralSource;
17732
18094
  ledger;
@@ -17737,6 +18099,7 @@ var OwneySDK = class {
17737
18099
  zyfaiServerTasks;
17738
18100
  /** The caller opted in to the Fusion+ secret handoff (`fusionSecretHandoff: true`). */
17739
18101
  fusionSecretHandoff;
18102
+ sessionStore;
17740
18103
  cachedSponsoredCallback = null;
17741
18104
  cachedWethSponsoredCallback = null;
17742
18105
  paymasterServiceUrl;
@@ -17779,7 +18142,9 @@ var OwneySDK = class {
17779
18142
  this.routingApiBaseUrl = config.routingApiBaseUrl;
17780
18143
  this.paymasterServiceUrl = config.paymasterServiceUrl;
17781
18144
  this.referralSource = config.referralSource;
18145
+ this.sessionStore = config.sessionStore;
17782
18146
  this.userPoolCustomization = config.userPoolCustomization ?? false;
18147
+ this.excludedProtocols = config.excludedProtocols ?? [];
17783
18148
  this.ledger = createFundingLedger({
17784
18149
  apiKey: config.apiKey,
17785
18150
  baseUrl: config.routingApiBaseUrl,
@@ -18534,7 +18899,9 @@ var OwneySDK = class {
18534
18899
  // Only an explicit opt-in lets the agent hand the Zyfai session to
18535
18900
  // Owney; a function is passed as it is and read per handoff.
18536
18901
  ...this.zyfaiServerTasks !== void 0 ? { zyfaiServerTasks: this.zyfaiServerTasks } : {}
18537
- }
18902
+ },
18903
+ this.sessionStore,
18904
+ this.excludedProtocols
18538
18905
  );
18539
18906
  }
18540
18907
  if (agentId === "yieldseeker") {