@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.js CHANGED
@@ -1051,7 +1051,7 @@ var SnapshotHistory = class {
1051
1051
  };
1052
1052
 
1053
1053
  // src/lib/funding-ledger.ts
1054
- var SDK_VERSION = "0.7.32-beta.12";
1054
+ var SDK_VERSION = "0.7.32-beta.14";
1055
1055
  var SCOPE2 = "funding-ledger";
1056
1056
  var REQUEST_TIMEOUT_MS2 = 5e3;
1057
1057
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -3314,14 +3314,16 @@ function splitOpportunity(opportunity) {
3314
3314
  }
3315
3315
  function mapEntries(rawEntries, chainId) {
3316
3316
  const actionMap = {
3317
- "Top up wallet": "Top up",
3317
+ // EOA -> smart wallet. Named "Top up" before ROUT-758; "Deposit" is what
3318
+ // users call it.
3319
+ "Top up wallet": "Deposit",
3318
3320
  "Partial withdraw from protocol": "Withdraw",
3319
3321
  "Withdraw from protocol": "Withdraw",
3320
- // The agent's own leg of a top up: the funds the user sent moving into the
3322
+ // The agent's own leg of a deposit: the funds the user sent moving into the
3321
3323
  // pool that earns the APY. Zyfai emits it as a separate entry seconds after
3322
- // "Top up wallet" and for slightly less (gas). `Deposit` already exists in
3323
- // the public HistoryAction union, so no consumer type change is needed.
3324
- "Deposit to protocol": "Deposit",
3324
+ // "Top up wallet" and for slightly less (gas). Smart wallet -> pool, so
3325
+ // "Allocate" (ROUT-758; it was "Deposit").
3326
+ "Deposit to protocol": "Allocate",
3325
3327
  // Withdrawing from an async vault (Superform) is logged under its own
3326
3328
  // label and paid out later in a separate batch (ROUT-624).
3327
3329
  "Request async withdrawal": "Withdraw",
@@ -3372,7 +3374,7 @@ function mapEntries(rawEntries, chainId) {
3372
3374
  const asyncRequest = entry.action === "Request async withdrawal";
3373
3375
  const rawAmount2 = entry?.positions?.[0]?.amount;
3374
3376
  const hasAmount = (mappedAction !== "Withdraw" || asyncRequest) && typeof rawAmount2 === "string" && rawAmount2 !== "" && rawAmount2 !== "0x" && rawAmount2 !== "0x0" && rawAmount2 !== "0";
3375
- const rawDelta = mappedAction === "Deposit" ? decodeDeltaAmount(
3377
+ const rawDelta = mappedAction === "Allocate" ? decodeDeltaAmount(
3376
3378
  entry?.positions?.[0]?.deltaAmount,
3377
3379
  tokenDecimals(entry?.positions?.[0]?.token_symbol)
3378
3380
  ) : void 0;
@@ -3647,7 +3649,7 @@ var isJwtExpired = (token) => {
3647
3649
  }
3648
3650
  };
3649
3651
  var memorySessions = /* @__PURE__ */ new Map();
3650
- var isFreshSession = (session) => !!session && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
3652
+ var isFreshSession = (session) => typeof session === "object" && session !== null && typeof session.isPredeployed === "boolean" && !!session.token && !isJwtExpired(session.token);
3651
3653
  var readLegacySession = (store, address) => {
3652
3654
  if (!store) return null;
3653
3655
  const prefix = legacyKeyPrefix(address);
@@ -3729,13 +3731,27 @@ var clearSession = (address, _chainId) => {
3729
3731
  }
3730
3732
  readLegacySession(store, address);
3731
3733
  };
3734
+ var BrowserSessionStore = class {
3735
+ read(_agentId, address) {
3736
+ return readSession(address, 0);
3737
+ }
3738
+ write(_agentId, address, session) {
3739
+ writeSession(address, 0, session);
3740
+ }
3741
+ clear(_agentId, address) {
3742
+ clearSession(address, 0);
3743
+ }
3744
+ };
3732
3745
 
3733
3746
  // src/agents/zyfai/autoSelect.ts
3734
3747
  function buildAutoSelectUpdate(current, asset, chainId) {
3735
3748
  const chains = current.chains ?? [];
3736
3749
  const chainMissing = chainId !== void 0 && !chains.includes(chainId);
3737
- if (current.autoSelectProtocols === true && !chainMissing) return null;
3738
3750
  const nextChains = chainMissing ? [...chains, chainId] : chains;
3751
+ if (current.savedPoolChoices || current.autoSelectProtocols === false) {
3752
+ return chainMissing ? { asset, chains: nextChains } : null;
3753
+ }
3754
+ if (current.autoSelectProtocols === true && !chainMissing) return null;
3739
3755
  return {
3740
3756
  asset,
3741
3757
  autoSelectProtocols: true,
@@ -3744,15 +3760,34 @@ function buildAutoSelectUpdate(current, asset, chainId) {
3744
3760
  }
3745
3761
 
3746
3762
  // src/agents/zyfai/protocol-merge.ts
3747
- function buildProtocolMergeUpdate(available, current, asset) {
3763
+ function isExcludedProtocol(protocol, excluded) {
3764
+ if (excluded.length === 0) return false;
3765
+ const wanted = new Set(excluded.map((entry) => entry.toLowerCase()));
3766
+ return wanted.has(protocol.id.toLowerCase()) || protocol.name !== void 0 && wanted.has(protocol.name.toLowerCase());
3767
+ }
3768
+ function buildProtocolMergeUpdate(available, current, asset, excluded = []) {
3769
+ const excludedIds = /* @__PURE__ */ new Set([
3770
+ ...excluded.map((entry) => entry.toLowerCase()),
3771
+ ...available.filter((p) => isExcludedProtocol(p, excluded)).map((p) => p.id.toLowerCase())
3772
+ ]);
3773
+ const isExcludedId = (id) => excluded.length > 0 && excludedIds.has(id.toLowerCase());
3748
3774
  const enabled = current.protocols ?? [];
3749
- const enabledSet = new Set(enabled);
3750
- const missing = available.filter((p) => !enabledSet.has(p.id));
3751
- if (missing.length === 0) return null;
3775
+ const kept = enabled.filter((id) => !isExcludedId(id));
3776
+ const keptSet = new Set(kept);
3777
+ const missing = current.autoSelectProtocols === false ? [] : available.filter((p) => !keptSet.has(p.id) && !isExcluded(p));
3778
+ const fixAutoSelect = excluded.length > 0 && current.autoSelectProtocols !== false;
3779
+ const removedAny = kept.length !== enabled.length;
3780
+ if (missing.length === 0 && !removedAny && !fixAutoSelect) return null;
3781
+ const protocols = [.../* @__PURE__ */ new Set([...kept, ...missing.map((p) => p.id)])];
3782
+ if (protocols.length === 0) return null;
3752
3783
  return {
3753
3784
  asset,
3754
- protocols: [.../* @__PURE__ */ new Set([...enabled, ...missing.map((p) => p.id)])]
3785
+ protocols,
3786
+ ...excluded.length > 0 ? { autoSelectProtocols: false } : {}
3755
3787
  };
3788
+ function isExcluded(p) {
3789
+ return isExcludedProtocol(p, excluded);
3790
+ }
3756
3791
  }
3757
3792
 
3758
3793
  // src/agents/zyfai/splitting.ts
@@ -3885,11 +3920,107 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
3885
3920
  }
3886
3921
  function mergeScopedPoolNames(current, scoped, allAvailableNames) {
3887
3922
  const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
3923
+ const offered = new Set(allAvailableNames);
3888
3924
  const existing = current.autoselect ? allAvailableNames : current.pools;
3889
- const preserved = existing.filter((name) => !managed.has(name));
3925
+ const preserved = existing.filter(
3926
+ (name) => !managed.has(name) && (offered.size === 0 || offered.has(name))
3927
+ );
3890
3928
  const selected = scoped.flatMap((entry) => entry.pools);
3891
3929
  return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
3892
3930
  }
3931
+ function savedPoolRecords(customization, protocolId, chainId) {
3932
+ if (!customization || typeof customization !== "object") return [];
3933
+ const records = [];
3934
+ for (const byProtocol of Object.values(customization)) {
3935
+ const byChain = byProtocol?.[protocolId];
3936
+ const record2 = byChain?.[String(chainId)];
3937
+ if (!record2 || typeof record2 !== "object") continue;
3938
+ records.push({
3939
+ pools: Array.isArray(record2.pools) ? record2.pools.filter((name) => typeof name === "string") : [],
3940
+ autoselect: typeof record2.autoselect === "boolean" ? record2.autoselect : void 0
3941
+ });
3942
+ }
3943
+ return records;
3944
+ }
3945
+ function hasManualPoolChoices(customization) {
3946
+ return manuallyChosenProtocols(customization).size > 0;
3947
+ }
3948
+ function manuallyChosenProtocols(customization) {
3949
+ const chosen = /* @__PURE__ */ new Set();
3950
+ if (!customization || typeof customization !== "object") return chosen;
3951
+ for (const byProtocol of Object.values(customization)) {
3952
+ for (const [protocolId, byChain] of Object.entries(byProtocol ?? {})) {
3953
+ const manual = Object.values(byChain ?? {}).some(
3954
+ (record2) => record2?.autoselect === false
3955
+ );
3956
+ if (manual) chosen.add(protocolId);
3957
+ }
3958
+ }
3959
+ return chosen;
3960
+ }
3961
+ function manualChainsOf(customization, protocolId) {
3962
+ if (!customization || typeof customization !== "object") return [];
3963
+ const chains = /* @__PURE__ */ new Set();
3964
+ for (const byProtocol of Object.values(customization)) {
3965
+ const byChain = byProtocol?.[protocolId];
3966
+ for (const [chainKey, record2] of Object.entries(byChain ?? {})) {
3967
+ const chainId = Number(chainKey);
3968
+ if (Number.isFinite(chainId) && record2?.autoselect === false) {
3969
+ chains.add(chainId);
3970
+ }
3971
+ }
3972
+ }
3973
+ return [...chains];
3974
+ }
3975
+ function protocolsSyncLeavesOff(customization, available, assetChains) {
3976
+ const off = /* @__PURE__ */ new Set();
3977
+ for (const protocol of available) {
3978
+ const chains = (protocol.chains ?? []).filter((chainId) => assetChains.includes(chainId));
3979
+ if (chains.length === 0) continue;
3980
+ const decided = chains.every((chainId) => {
3981
+ const records = savedPoolRecords(customization, protocol.id, chainId);
3982
+ return records.length > 0 && !savedRecordsAreAuto(records);
3983
+ });
3984
+ if (decided) off.add(protocol.id);
3985
+ }
3986
+ return off;
3987
+ }
3988
+ function tokenIsAsset(token, asset) {
3989
+ const upper = token.toUpperCase();
3990
+ return asset === "WETH" ? upper === "WETH" || upper === "ETH" : upper === asset;
3991
+ }
3992
+ function savedRecordsAreAuto(records) {
3993
+ return records.length === 0 || records.some((record2) => record2.autoselect !== false);
3994
+ }
3995
+ function protocolsToKeep(params) {
3996
+ const { asset, chains, customization, catalogs } = params;
3997
+ const entries = params.selections.filter(
3998
+ (entry) => entry.asset === asset && entry.availablePools.length > 0
3999
+ );
4000
+ const picked = entries.filter((entry) => entry.pools.length > 0).map((entry) => entry.protocolId);
4001
+ const candidates = [.../* @__PURE__ */ new Set([...params.current, ...picked])];
4002
+ const inUse = (protocolId) => {
4003
+ if (picked.includes(protocolId)) return true;
4004
+ const catalog = catalogs.get(protocolId);
4005
+ if (!catalog || catalog.length === 0) return true;
4006
+ const covered = new Set(
4007
+ entries.filter((entry) => entry.protocolId === protocolId).map((entry) => entry.chainId)
4008
+ );
4009
+ const assetChains = new Set(chains);
4010
+ const toCheck = [.../* @__PURE__ */ new Set([...chains, ...manualChainsOf(customization, protocolId)])];
4011
+ return toCheck.some((chainId) => {
4012
+ if (covered.has(chainId)) return false;
4013
+ const offered = new Set(
4014
+ catalog.filter((pool) => pool.chainId === chainId && tokenIsAsset(pool.token, asset)).map((pool) => pool.name)
4015
+ );
4016
+ if (offered.size === 0) return false;
4017
+ const records = savedPoolRecords(customization, protocolId, chainId);
4018
+ return assetChains.has(chainId) && savedRecordsAreAuto(records) || records.some((record2) => record2.autoselect === false && record2.pools.some((name) => offered.has(name)));
4019
+ });
4020
+ };
4021
+ const kept = candidates.filter(inUse);
4022
+ return kept.length > 0 ? kept : candidates;
4023
+ }
3893
4024
  function mapAvailablePools(raw2) {
3894
4025
  const byChain = raw2 ?? {};
3895
4026
  if (typeof byChain !== "object" || byChain === null) return [];
@@ -4221,6 +4352,7 @@ var ERC7579_IS_MODULE_INSTALLED_ABI = parseAbi3([
4221
4352
  "function isModuleInstalled(uint256 moduleTypeId, address module, bytes additionalContext) view returns (bool)"
4222
4353
  ]);
4223
4354
  var ZYFAI_SIGN_IN_REQUIRED_MESSAGE = "No Zyfai sign-in is available without a prompt.";
4355
+ var isPromiseLike = (value) => typeof value?.then === "function";
4224
4356
  var isSignInFailure = (error) => error instanceof OwneyError && error.code === "AGENT_AUTH_FAILED";
4225
4357
  var WETH_ADDRESS_BY_CHAIN = {
4226
4358
  8453: "0x4200000000000000000000000000000000000006",
@@ -4290,16 +4422,20 @@ function belowMinimumCeiling(rejection, token, decimals) {
4290
4422
  return idle === void 0 || minimum === void 0 ? void 0 : idle < minimum ? idle : minimum;
4291
4423
  }
4292
4424
  var ZyfaiAgent = class _ZyfaiAgent {
4293
- constructor(apiKey, rpcUrls, referralSource, accountReporting = {}) {
4425
+ constructor(apiKey, rpcUrls, referralSource, accountReporting = {}, sessionStore = new BrowserSessionStore(), excludedProtocols = []) {
4294
4426
  this.apiKey = apiKey;
4295
4427
  this.referralSource = referralSource;
4296
4428
  this.accountReporting = accountReporting;
4429
+ this.sessionStore = sessionStore;
4430
+ this.excludedProtocols = excludedProtocols;
4297
4431
  this.rpcUrls = resolveRpcUrls(rpcUrls);
4298
4432
  this.sdk = this.createSdk();
4299
4433
  }
4300
4434
  apiKey;
4301
4435
  referralSource;
4302
4436
  accountReporting;
4437
+ sessionStore;
4438
+ excludedProtocols;
4303
4439
  id = "zyfai";
4304
4440
  /** This adapter can hand its withdrawals to our server (part 4). */
4305
4441
  supportsServerTasks = true;
@@ -4451,7 +4587,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4451
4587
  */
4452
4588
  async resolveFundingTransfers(entries, chainId, recipient, smartWallet, tokenSymbol) {
4453
4589
  const movements = entries.filter(
4454
- (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Top up") && e.transactions[0]?.txHashes[0]
4590
+ (e) => (e.action === "Withdraw" && !e.asyncRequest || e.action === "Deposit") && e.transactions[0]?.txHashes[0]
4455
4591
  );
4456
4592
  if (movements.length === 0) return;
4457
4593
  const client = this.getPublicClient(chainId);
@@ -4508,6 +4644,48 @@ var ZyfaiAgent = class _ZyfaiAgent {
4508
4644
  })
4509
4645
  );
4510
4646
  }
4647
+ /**
4648
+ * The session store is a cache: an unavailable store must never block
4649
+ * authentication or teardown. Failures read as a cache miss. The store is
4650
+ * called synchronously, so a synchronous store (the browser default) has
4651
+ * already acted when this returns.
4652
+ */
4653
+ async storeOp(op) {
4654
+ try {
4655
+ return await op();
4656
+ } catch (error) {
4657
+ console.warn(
4658
+ "owney-sdk: agent session store failed, continuing without it",
4659
+ error
4660
+ );
4661
+ return null;
4662
+ }
4663
+ }
4664
+ /**
4665
+ * The fresh saved session for `address`, or null. Answered synchronously
4666
+ * when the store answers synchronously (the browser default), so a check
4667
+ * that must not yield keeps its order; a promise for an asynchronous store.
4668
+ * A store failure reads as no session.
4669
+ */
4670
+ savedSession(address) {
4671
+ let value;
4672
+ try {
4673
+ value = this.sessionStore.read(this.id, address);
4674
+ } catch (error) {
4675
+ console.warn("owney-sdk: agent session store failed, continuing without it", error);
4676
+ return null;
4677
+ }
4678
+ if (isPromiseLike(value)) {
4679
+ return Promise.resolve(value).then(
4680
+ (session) => isFreshSession(session) ? session : null,
4681
+ (error) => {
4682
+ console.warn("owney-sdk: agent session store failed, continuing without it", error);
4683
+ return null;
4684
+ }
4685
+ );
4686
+ }
4687
+ return isFreshSession(value) ? value : null;
4688
+ }
4511
4689
  /**
4512
4690
  * Patches `sdk.authenticateUser` so a fresh page can reuse the JWT from a
4513
4691
  * prior session instead of triggering a new SIWE prompt. Runs inside
@@ -4515,21 +4693,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
4515
4693
  * (Zyfai dist line 1374). At that point `walletClient` + `currentChainId`
4516
4694
  * are populated, so the cache lookup has both keys it needs.
4517
4695
  *
4518
- * No-op on the server (no `window`) — the SDK is constructed during SSR
4519
- * for some apps and the patch only matters in the browser anyway.
4696
+ * The session lives in `sessionStore`: localStorage in the browser (a no-op
4697
+ * on the server), or whatever the host passed in `OwneySDKConfig`.
4520
4698
  */
4521
4699
  installAuthCache(sdk = this.sdk) {
4522
- if (typeof window === "undefined") return;
4523
4700
  const internals = sdk;
4524
4701
  const original = internals.authenticateUser.bind(internals);
4525
4702
  let inFlight2 = null;
4526
4703
  const authenticate = async () => {
4527
4704
  if (internals.authenticatedUserId !== null) return;
4528
4705
  const address = internals.walletClient?.account?.address;
4529
- const chainId = internals.currentChainId ?? 0;
4530
4706
  if (address) {
4531
- const cached = readSession(address, chainId);
4532
- if (cached) {
4707
+ const cached = await this.storeOp(
4708
+ () => this.sessionStore.read(this.id, address)
4709
+ );
4710
+ if (isFreshSession(cached)) {
4533
4711
  internals.httpClient.setAuthToken(cached.token);
4534
4712
  internals.authenticatedUserId = cached.userId;
4535
4713
  internals.hasActiveSessionKey = cached.hasActiveSessionKey;
@@ -4540,15 +4718,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
4540
4718
  if (this.promptlessSdks.has(sdk)) throw this.signInRequired();
4541
4719
  await original();
4542
4720
  const newAddress = internals.walletClient?.account?.address;
4543
- const newChainId = internals.currentChainId ?? 0;
4544
4721
  const newToken = internals.httpClient.authToken;
4545
4722
  if (newAddress && newToken) {
4546
- writeSession(newAddress, newChainId, {
4547
- token: newToken,
4548
- userId: internals.authenticatedUserId,
4549
- hasActiveSessionKey: internals.hasActiveSessionKey,
4550
- isPredeployed: internals.isPredeployed
4551
- });
4723
+ await this.storeOp(
4724
+ () => this.sessionStore.write(this.id, newAddress, {
4725
+ token: newToken,
4726
+ userId: internals.authenticatedUserId,
4727
+ hasActiveSessionKey: internals.hasActiveSessionKey,
4728
+ isPredeployed: internals.isPredeployed
4729
+ })
4730
+ );
4552
4731
  }
4553
4732
  };
4554
4733
  internals.authenticateUser = () => {
@@ -4577,11 +4756,19 @@ var ZyfaiAgent = class _ZyfaiAgent {
4577
4756
  * Whether connecting now would ask the wallet to sign in: not connected for
4578
4757
  * this wallet and chain (the check `connectAuth` returns early on) and no
4579
4758
  * fresh saved session. Never prompts; reads only what is saved.
4759
+ *
4760
+ * A session store that answers only asynchronously (a host's own
4761
+ * `sessionStore`) cannot be read here, so this throws: the caller counts an
4762
+ * unknown answer its own way (`OwneySDK.signInsNeeded` as a sign-in).
4580
4763
  */
4581
4764
  needsSignIn(state, chainId) {
4582
4765
  const owner = state.walletAddress.toLowerCase();
4583
4766
  if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === chainId) return false;
4584
- return readSession(state.walletAddress, chainId) === null;
4767
+ const saved = this.savedSession(state.walletAddress);
4768
+ if (isPromiseLike(saved)) {
4769
+ throw new Error("The Zyfai session store answers asynchronously; whether a sign-in is needed is unknown.");
4770
+ }
4771
+ return saved === null;
4585
4772
  }
4586
4773
  /** A read (promptless state) needs a sign-in it may not ask for. */
4587
4774
  signInRequired() {
@@ -4611,7 +4798,15 @@ var ZyfaiAgent = class _ZyfaiAgent {
4611
4798
  else await this.connectAuthPromise;
4612
4799
  return this.connectAuth(state, chainId);
4613
4800
  }
4614
- if (promptless && readSession(state.walletAddress, validChainId) === null) throw this.signInRequired();
4801
+ if (promptless) {
4802
+ let saved = this.savedSession(state.walletAddress);
4803
+ if (isPromiseLike(saved)) {
4804
+ saved = await saved;
4805
+ if (saved === null) throw this.signInRequired();
4806
+ if (this.connectedAddress?.toLowerCase() === owner && this.connectedChainId === validChainId || this.connectAuthPromise && this.connectAuthScope === scope) return this.connectAuth(state, chainId);
4807
+ }
4808
+ if (saved === null) throw this.signInRequired();
4809
+ }
4615
4810
  if (this.sdkHasConnected || this.connectedAddress) this.sdk = this.createSdk();
4616
4811
  this.sdkHasConnected = true;
4617
4812
  const executionSdk = this.sdk;
@@ -4671,8 +4866,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
4671
4866
  if (!message.toLowerCase().includes("unauthorized")) throw error;
4672
4867
  const internals = executionSdk;
4673
4868
  const address = internals.walletClient?.account?.address;
4674
- if (promptless) throw this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
4675
- if (address) clearSession(address, chainId);
4869
+ if (promptless) throw await this.dropRefusedReadSession(address, executionSdk, internals.httpClient.authToken, message);
4870
+ if (address) {
4871
+ await this.storeOp(() => this.sessionStore.clear(this.id, address));
4872
+ }
4676
4873
  return await executionSdk.connectAccount(provider, chainId);
4677
4874
  }
4678
4875
  }
@@ -4695,14 +4892,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
4695
4892
  * the user's (connect, deposit, withdraw), on a new client. Returns the
4696
4893
  * read's error.
4697
4894
  */
4698
- dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
4895
+ async dropRefusedReadSession(owner, executionSdk, authToken, refusal) {
4699
4896
  debugLog("zyfai:auth", "a read's session was refused; dropped without signing in again", { refusal });
4700
4897
  if (owner && typeof authToken === "string") {
4701
4898
  let dropped = false;
4702
- if (readSession(owner, 0)?.token === authToken) {
4703
- clearSession(owner, 0);
4704
- dropped = true;
4705
- }
4706
4899
  const internals = executionSdk;
4707
4900
  if (internals.httpClient.authToken === authToken) {
4708
4901
  dropped = true;
@@ -4712,6 +4905,11 @@ var ZyfaiAgent = class _ZyfaiAgent {
4712
4905
  if (executionSdk === this.sdk && this.connectedAddress?.toLowerCase() === owner.toLowerCase())
4713
4906
  this.connectedChainId = null;
4714
4907
  }
4908
+ const saved = await this.savedSession(owner);
4909
+ if (saved?.token === authToken) {
4910
+ await this.storeOp(() => this.sessionStore.clear(this.id, owner));
4911
+ dropped = true;
4912
+ }
4715
4913
  if (dropped) this.tellSignInRefused();
4716
4914
  }
4717
4915
  return this.signInRequired();
@@ -4731,7 +4929,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4731
4929
  if (state.promptless !== true || error instanceof OwneyError) throw error;
4732
4930
  if (message.includes(ZYFAI_SIGN_IN_REQUIRED_MESSAGE)) throw this.signInRequired();
4733
4931
  if (!isZyfaiSessionRejected(message)) throw error;
4734
- throw this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
4932
+ throw await this.dropRefusedReadSession(state.walletAddress, executionSdk, authToken, message);
4735
4933
  }
4736
4934
  }
4737
4935
  /**
@@ -4767,7 +4965,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
4767
4965
  dropWithdrawalSession(state, chainId, authToken) {
4768
4966
  const internals = this.sdk;
4769
4967
  if (typeof authToken !== "string" || internals.httpClient.authToken !== authToken || this.connectedAddress?.toLowerCase() !== state.walletAddress.toLowerCase() || this.connectedChainId !== chainId) return;
4770
- clearSession(state.walletAddress, chainId);
4968
+ const owner = state.walletAddress;
4969
+ void this.storeOp(() => this.sessionStore.clear(this.id, owner));
4771
4970
  internals.httpClient.clearAuthToken();
4772
4971
  internals.authenticatedUserId = null;
4773
4972
  this.connectedChainId = null;
@@ -4803,7 +5002,21 @@ var ZyfaiAgent = class _ZyfaiAgent {
4803
5002
  );
4804
5003
  return;
4805
5004
  }
4806
- const update = buildProtocolMergeUpdate(available, current, asset);
5005
+ const decided = protocolsSyncLeavesOff(
5006
+ current.customization,
5007
+ available,
5008
+ current.chains ?? []
5009
+ );
5010
+ const excluded = this.excludedProtocols.length === 0 ? [] : [
5011
+ ...this.excludedProtocols,
5012
+ ...available.filter((protocol) => isExcludedProtocol(protocol, this.excludedProtocols)).map((protocol) => protocol.id)
5013
+ ];
5014
+ const update = buildProtocolMergeUpdate(
5015
+ available.filter((protocol) => !decided.has(protocol.id)),
5016
+ current,
5017
+ asset,
5018
+ excluded
5019
+ );
4807
5020
  if (!update) return;
4808
5021
  await this.sdk.updateUserProfile(update);
4809
5022
  debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
@@ -4877,9 +5090,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
4877
5090
  this.holdActiveScopes.clear();
4878
5091
  this.pendingRegistrations.clear();
4879
5092
  this.lastGoodEarnings.clear();
4880
- if (!options?.keepSignIns && this.connectedAddress && this.connectedChainId !== null) {
4881
- clearSession(this.connectedAddress, this.connectedChainId);
4882
- }
5093
+ const address = this.connectedAddress;
5094
+ const sessionCleared = !options?.keepSignIns && address ? this.storeOp(() => this.sessionStore.clear(this.id, address)) : void 0;
4883
5095
  this.connectedAddress = null;
4884
5096
  this.connectedChainId = null;
4885
5097
  this.connectAuthPromise = null;
@@ -4889,6 +5101,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
4889
5101
  this.reportedAccounts.clear();
4890
5102
  this.sdk = this.createSdk();
4891
5103
  this.sdkHasConnected = false;
5104
+ await sessionCleared;
4892
5105
  await executionSdk.disconnectAccount();
4893
5106
  }
4894
5107
  // --- IAgent: Account lifecycle ---
@@ -5100,9 +5313,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
5100
5313
  * lookup fails is skipped rather than failing the whole catalogue.
5101
5314
  */
5102
5315
  async getPoolCatalog(params) {
5103
- const { protocols: universe } = await this.sdk.getAvailableProtocols(
5316
+ const { protocols: allProtocols } = await this.sdk.getAvailableProtocols(
5104
5317
  this.supportedChainIds[0]
5105
5318
  );
5319
+ const universe = allProtocols.filter(
5320
+ (protocol) => !isExcludedProtocol(protocol, this.excludedProtocols)
5321
+ );
5106
5322
  const poolResults = await Promise.all(
5107
5323
  universe.map(async (protocol) => {
5108
5324
  try {
@@ -5145,14 +5361,23 @@ var ZyfaiAgent = class _ZyfaiAgent {
5145
5361
  group.push(entry);
5146
5362
  byPair.set(pair, group);
5147
5363
  }
5364
+ const catalogReads = /* @__PURE__ */ new Map();
5365
+ const catalogOf = (protocolId) => {
5366
+ let read2 = catalogReads.get(protocolId);
5367
+ if (!read2) {
5368
+ read2 = this.sdk.getAvailablePools(protocolId, "yieldmaxxing").then(mapAvailablePools);
5369
+ catalogReads.set(protocolId, read2);
5370
+ }
5371
+ return read2;
5372
+ };
5148
5373
  const customizations = await Promise.all(
5149
5374
  [...byPair.values()].map(async (scoped) => {
5150
5375
  const { protocolId, chainId } = scoped[0];
5151
- const [current, rawAvailable] = await Promise.all([
5376
+ const [current, catalog] = await Promise.all([
5152
5377
  this.sdk.getSelectedPools(protocolId, chainId),
5153
- this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
5378
+ catalogOf(protocolId)
5154
5379
  ]);
5155
- const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5380
+ const allAvailableNames = catalog.filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5156
5381
  return {
5157
5382
  protocolId,
5158
5383
  chainId,
@@ -5176,13 +5401,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
5176
5401
  await Promise.all(
5177
5402
  selection.strategies.map(async ({ asset, strategy }) => {
5178
5403
  const current = await this.sdk.getUserDetails(asset);
5179
- const selectedProtocols = selection.selections.filter(
5180
- (entry) => entry.asset === asset && entry.pools.length > 0
5181
- ).map((entry) => entry.protocolId);
5182
- const protocols = [
5183
- .../* @__PURE__ */ new Set([...current.protocols ?? [], ...selectedProtocols])
5184
- ];
5185
- await this.sdk.updateUserProfile({ asset, strategy, protocols });
5404
+ const listed = current.protocols ?? [];
5405
+ const unpicked = listed.filter((protocolId) => !selection.selections.some(
5406
+ (entry) => entry.asset === asset && entry.protocolId === protocolId && entry.pools.length > 0
5407
+ ));
5408
+ const catalogs = new Map(await Promise.all(unpicked.map(async (protocolId) => [protocolId, await catalogOf(protocolId).catch(() => null)])));
5409
+ const protocols = protocolsToKeep({
5410
+ asset,
5411
+ current: listed,
5412
+ chains: current.chains ?? [],
5413
+ selections: selection.selections,
5414
+ customization: current.customization,
5415
+ catalogs
5416
+ });
5417
+ await this.sdk.updateUserProfile({
5418
+ asset,
5419
+ strategy,
5420
+ protocols,
5421
+ autoSelectProtocols: false
5422
+ });
5186
5423
  })
5187
5424
  );
5188
5425
  } catch (error) {
@@ -5233,6 +5470,7 @@ var ZyfaiAgent = class _ZyfaiAgent {
5233
5470
  }
5234
5471
  for (const protocol of universe) {
5235
5472
  if (excluded.has(protocol.id)) continue;
5473
+ if (isExcludedProtocol(protocol, this.excludedProtocols)) continue;
5236
5474
  try {
5237
5475
  const names = mapAvailablePools(await this.sdk.getAvailablePools(protocol.id, "yieldmaxxing")).filter((pool) => pool.chainId === chainId && pool.token.toUpperCase() === asset).map((pool) => pool.name);
5238
5476
  if (names.length === 0) continue;
@@ -5619,6 +5857,10 @@ var ZyfaiAgent = class _ZyfaiAgent {
5619
5857
  assertCurrent();
5620
5858
  const setupResult = await executionSdk.ensureFirstDepositSetup("aggressive");
5621
5859
  debugLog("zyfai:first-deposit", "setup call completed", { asset, chainId: validChainId, requestedStrategy: "aggressive", setupResult });
5860
+ if (this.excludedProtocols.length > 0) {
5861
+ assertCurrent();
5862
+ await this.ensureProtocolsSynced(validChainId, asset);
5863
+ }
5622
5864
  if (isOwneyDebug()) {
5623
5865
  try {
5624
5866
  const profile = await executionSdk.getUserDetails(asset === "WETH" ? "WETH" : "USDC");
@@ -7043,7 +7285,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
7043
7285
  const update = buildAutoSelectUpdate(
7044
7286
  {
7045
7287
  autoSelectProtocols: current.autoSelectProtocols,
7046
- chains: current.chains
7288
+ chains: current.chains,
7289
+ savedPoolChoices: hasManualPoolChoices(current.customization)
7047
7290
  },
7048
7291
  asset,
7049
7292
  isValidChainId(chainId)
@@ -7842,6 +8085,10 @@ function dailyApy(point) {
7842
8085
  if (principal <= 0n || earned === 0n) return 0;
7843
8086
  return Number(earned) / Number(principal) * 365 * 100;
7844
8087
  }
8088
+ var DUST_USD = 5e-3;
8089
+ function heldPosition(tokens, priceUsd) {
8090
+ return Number.isFinite(priceUsd) && priceUsd > 0 ? tokens * priceUsd >= DUST_USD : tokens > 0;
8091
+ }
7845
8092
  function aggregateHistory(contexts, dayCount, now, scopedAsset) {
7846
8093
  const today = new Date(now).toISOString().slice(0, 10);
7847
8094
  const cutoff = new Date(Date.parse(today) - (dayCount - 1) * 864e5).toISOString().slice(0, 10);
@@ -7858,6 +8105,7 @@ function aggregateHistory(contexts, dayCount, now, scopedAsset) {
7858
8105
  if (!Number.isFinite(amount) || amount < 0) {
7859
8106
  invalid("historic position", "expected a finite non-negative balance");
7860
8107
  }
8108
+ if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
7861
8109
  const current = byDate.get(point.date) ?? { weighted: 0, amount: 0 };
7862
8110
  current.weighted += dailyApy(point) * amount;
7863
8111
  current.amount += amount;
@@ -7878,7 +8126,8 @@ function historyCoverage2(contexts, dayCount, now) {
7878
8126
  for (const context of contexts) {
7879
8127
  for (const point of context.historic?.dailyYieldSnapshots ?? []) {
7880
8128
  if (!/^\d{4}-\d{2}-\d{2}$/.test(point.date) || point.date < cutoff || point.date > today) continue;
7881
- if (!(Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position")) > 0)) continue;
8129
+ const tokens = Number(decimal(point.totalValueBase, point.baseAssetDecimals, "historic position"));
8130
+ if (!heldPosition(tokens, point.baseAssetPriceUsd)) continue;
7882
8131
  const asset = context.asset.toUpperCase();
7883
8132
  const dates = datesByAsset.get(asset) ?? /* @__PURE__ */ new Set();
7884
8133
  dates.add(point.date);
@@ -7920,7 +8169,7 @@ function mapYieldseekerApy(walletAddress, contexts, days, now = Date.now(), scop
7920
8169
  }
7921
8170
  function actionType(value) {
7922
8171
  const normalized = value.toLowerCase();
7923
- if (normalized.includes("deposit")) return "Deposit";
8172
+ if (normalized.includes("deposit")) return "Allocate";
7924
8173
  if (normalized.includes("withdraw")) return "Withdraw";
7925
8174
  if (normalized.includes("yield") || normalized.includes("earn"))
7926
8175
  return "Earned";
@@ -7981,14 +8230,87 @@ function allocationLegs(value, context, requireAmount) {
7981
8230
  }
7982
8231
  return legs;
7983
8232
  }
7984
- function allocationEntry(action, context) {
8233
+ function vaultBook(context, vaultAddresses, catalog = []) {
8234
+ const base7 = context.agent.assetAddress.toLowerCase();
8235
+ const labels = /* @__PURE__ */ new Map();
8236
+ const name = (address, label) => {
8237
+ if (typeof address !== "string" || !isAddress3(address)) return;
8238
+ const key2 = address.toLowerCase();
8239
+ if (!labels.has(key2)) labels.set(key2, label);
8240
+ };
8241
+ for (const action of context.actions ?? []) {
8242
+ for (const list of [action.details?.deposits, action.details?.withdrawals]) {
8243
+ if (!Array.isArray(list)) continue;
8244
+ for (const leg of list) {
8245
+ if (leg && typeof leg.vaultProvider === "string" && leg.vaultProvider)
8246
+ name(leg.vaultAddress, {
8247
+ protocol: leg.vaultProvider,
8248
+ ...typeof leg.vaultName === "string" && leg.vaultName ? { pool: leg.vaultName } : {}
8249
+ });
8250
+ }
8251
+ }
8252
+ }
8253
+ for (const option of [...context.positions.map((entry) => entry.vaultOption), ...catalog])
8254
+ if (option?.chainId === context.agent.chainId)
8255
+ name(option.address, { protocol: option.provider || "Vault", ...option.name ? { pool: option.name } : {} });
8256
+ for (const asset of context.historic?.assets ?? [])
8257
+ if (asset.chainId === context.agent.chainId && !asset.isSpam && asset.address.toLowerCase() !== base7)
8258
+ name(asset.address, { protocol: "Vault", ...asset.name || asset.symbol ? { pool: asset.name || asset.symbol } : {} });
8259
+ const addresses = /* @__PURE__ */ new Set([...vaultAddresses, ...labels.keys()]);
8260
+ return { addresses, label: (address) => labels.get(address.toLowerCase()) ?? { protocol: "Vault" } };
8261
+ }
8262
+ function recycledDeposits(context, movements, vaults) {
8263
+ const base7 = context.agent.assetAddress.toLowerCase();
8264
+ const agentWallet = context.wallet.walletAddress.toLowerCase();
8265
+ 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);
8266
+ const transactions = /* @__PURE__ */ new Map();
8267
+ for (const movement of relevant) {
8268
+ const hash2 = movement.transactionHash.toLowerCase();
8269
+ transactions.set(hash2, [...transactions.get(hash2) ?? [], movement]);
8270
+ }
8271
+ const held = [];
8272
+ const spend = (amount) => {
8273
+ const used = [];
8274
+ while (amount > 0n && held.length) {
8275
+ const first = held[0];
8276
+ const taken = first.amount < amount ? first.amount : amount;
8277
+ if (!used.some((entry) => entry.vault === first.vault && entry.hash === first.hash))
8278
+ used.push({ vault: first.vault, hash: first.hash });
8279
+ first.amount -= taken;
8280
+ amount -= taken;
8281
+ if (first.amount === 0n) held.shift();
8282
+ }
8283
+ return used;
8284
+ };
8285
+ const covered = /* @__PURE__ */ new Map();
8286
+ for (const [hash2, legs] of transactions) {
8287
+ let deposited = 0n;
8288
+ for (const movement of legs) {
8289
+ const from = movement.fromAddress.toLowerCase();
8290
+ const to = movement.toAddress.toLowerCase();
8291
+ const amount = BigInt(movement.assetAmount);
8292
+ if (to === agentWallet && from !== agentWallet) {
8293
+ if (vaults.has(from)) held.push({ vault: from, hash: hash2, amount });
8294
+ } else if (from === agentWallet && to !== agentWallet) {
8295
+ if (vaults.has(to)) deposited += amount;
8296
+ else spend(amount);
8297
+ }
8298
+ }
8299
+ if (deposited === 0n) continue;
8300
+ const available = held.reduce((total, entry) => total + entry.amount, 0n);
8301
+ const used = spend(deposited);
8302
+ if (available >= deposited) covered.set(hash2, used);
8303
+ }
8304
+ return covered;
8305
+ }
8306
+ function allocationEntry(action, context, evidence) {
7985
8307
  if (action.actionType.toLowerCase() !== "autoseek") return void 0;
7986
8308
  const hash2 = action.details?.depositTransactionHash;
7987
8309
  const withdrawHash = action.details?.withdrawTransactionHash;
7988
8310
  if (typeof hash2 !== "string" || !TX_HASH3.test(hash2)) return null;
7989
8311
  const deposits = allocationLegs(action.details?.deposits, context, true);
7990
- const withdrawals = action.details?.withdrawals == null ? [] : allocationLegs(action.details.withdrawals, context, false);
7991
- if (!deposits?.length || !withdrawals) return null;
8312
+ const listed = action.details?.withdrawals == null ? [] : allocationLegs(action.details.withdrawals, context, false);
8313
+ if (!deposits?.length || !listed) return null;
7992
8314
  const decimals = YIELDSEEKER_ASSET_METADATA[context.asset].decimals;
7993
8315
  const positions = deposits.map((leg) => ({
7994
8316
  protocol: leg.protocol,
@@ -7997,15 +8319,26 @@ function allocationEntry(action, context) {
7997
8319
  amount: formatUnits3(leg.rawAmount, decimals)
7998
8320
  }));
7999
8321
  const amountRaw = deposits.reduce((total, leg) => total + leg.rawAmount, 0n);
8322
+ const withdrawTx = typeof withdrawHash === "string" && TX_HASH3.test(withdrawHash) && withdrawHash.toLowerCase() !== hash2.toLowerCase() ? withdrawHash : void 0;
8323
+ let withdrawals = listed;
8324
+ let hashes = listed.length && withdrawTx ? [hash2, withdrawTx] : [hash2];
8325
+ if (!listed.length) {
8326
+ const agentWallet = context.wallet.walletAddress.toLowerCase();
8327
+ 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 })) : [];
8328
+ const recycled = evidence.recycled.get(hash2.toLowerCase()) ?? [];
8329
+ const sources = inWithdrawTx.length ? inWithdrawTx : recycled;
8330
+ withdrawals = [...new Set(sources.map((source2) => source2.vault))].map((vault) => evidence.book.label(vault));
8331
+ hashes = [hash2, ...new Set(withdrawTx ? [withdrawTx] : sources.map((source2) => source2.hash).filter((value) => value !== hash2.toLowerCase()))];
8332
+ }
8000
8333
  const rebalance = withdrawals.length > 0;
8001
- const hashes = rebalance && typeof withdrawHash === "string" && TX_HASH3.test(withdrawHash) && withdrawHash.toLowerCase() !== hash2.toLowerCase() ? [hash2, withdrawHash] : [hash2];
8334
+ if (!rebalance) hashes = [hash2];
8002
8335
  const source = withdrawals.length === 1 ? withdrawals[0] : {
8003
8336
  protocol: [...new Set(withdrawals.map((leg) => leg.protocol))].join(" + "),
8004
8337
  pool: withdrawals.map((leg) => leg.pool).filter(Boolean).join(" + ") || void 0
8005
8338
  };
8006
8339
  return {
8007
8340
  agent: "yieldseeker",
8008
- action: rebalance ? "Rebalance" : "Deposit",
8341
+ action: rebalance ? "Rebalance" : "Allocate",
8009
8342
  date: action.createdDate,
8010
8343
  oldApy: null,
8011
8344
  newApy: null,
@@ -8052,17 +8385,17 @@ function movementEntry(movement, wallet, agent, asset, ownerAddress, vaultAddres
8052
8385
  }
8053
8386
  let action;
8054
8387
  if (to === agentWallet && !vaultAddresses.has(from)) {
8055
- action = "Top up";
8388
+ action = "Deposit";
8056
8389
  } else if (from === agentWallet && to === owner) {
8057
8390
  action = "Withdraw";
8058
8391
  } else if (from === agentWallet && destination) {
8059
- action = "Deposit";
8392
+ action = "Allocate";
8060
8393
  }
8061
8394
  if (!action) return void 0;
8062
8395
  return {
8063
8396
  agent: "yieldseeker",
8064
8397
  action,
8065
- ...action === "Deposit" && destination ? { positions: [{
8398
+ ...action === "Allocate" && destination ? { positions: [{
8066
8399
  ...destination,
8067
8400
  amount: decimal(movement.assetAmount, YIELDSEEKER_ASSET_METADATA[asset].decimals, "historic position")
8068
8401
  }] } : {},
@@ -8099,11 +8432,13 @@ function mapYieldseekerHistory(contexts, options) {
8099
8432
  seenMovements.add(key2);
8100
8433
  return true;
8101
8434
  });
8435
+ const book = vaultBook(context, options.vaultAddresses, options.vaultOptions);
8436
+ const evidence = { book, movements, recycled: recycledDeposits(context, movements, book.addresses) };
8102
8437
  const allocations = /* @__PURE__ */ new Map();
8103
8438
  const rebalanceHashes = /* @__PURE__ */ new Set();
8104
8439
  const actions = [];
8105
8440
  for (const action of context.actions ?? []) {
8106
- const allocation = allocationEntry(action, context);
8441
+ const allocation = allocationEntry(action, context, evidence);
8107
8442
  if (allocation === null) continue;
8108
8443
  if (!allocation) {
8109
8444
  const entry = actionEntry(action);
@@ -8123,11 +8458,11 @@ function mapYieldseekerHistory(contexts, options) {
8123
8458
  context.agent,
8124
8459
  context.asset,
8125
8460
  options.ownerAddress,
8126
- options.vaultAddresses,
8461
+ book.addresses,
8127
8462
  depositDestination(context, movement)
8128
8463
  )
8129
- ).filter((entry) => entry !== void 0 && !((entry.action === "Deposit" || entry.action === "Top up") && rebalanceHashes.has(entry.transactions[0]?.txHashes[0]?.toLowerCase() ?? "")));
8130
- const deposits = new Set(movementEntries.filter((entry) => entry.action === "Deposit").map((entry) => entry.transactions[0]?.txHashes[0]?.toLowerCase()));
8464
+ ).filter((entry) => entry !== void 0 && !((entry.action === "Allocate" || entry.action === "Deposit") && rebalanceHashes.has(entry.transactions[0]?.txHashes[0]?.toLowerCase() ?? "")));
8465
+ const deposits = new Set(movementEntries.filter((entry) => entry.action === "Allocate").map((entry) => entry.transactions[0]?.txHashes[0]?.toLowerCase()));
8131
8466
  for (const [hash2, allocation] of allocations)
8132
8467
  if (allocation.action === "Rebalance" || !deposits.has(hash2)) actions.push(allocation);
8133
8468
  return [...movementEntries, ...actions];
@@ -8148,14 +8483,14 @@ function mapYieldseekerHistory(contexts, options) {
8148
8483
  grouped.set(key2, entry);
8149
8484
  continue;
8150
8485
  }
8151
- if (entry.action === "Deposit" && entry.positions?.length) {
8486
+ if (entry.action === "Allocate" && entry.positions?.length) {
8152
8487
  if (!previous.positions?.length) {
8153
8488
  grouped.set(key2, entry);
8154
8489
  continue;
8155
8490
  }
8156
8491
  previous.positions.push(...entry.positions);
8157
8492
  previous.transactions.push(...entry.transactions);
8158
- } else if ((entry.action === "Top up" || entry.action === "Withdraw") && tx.amountRaw) {
8493
+ } else if ((entry.action === "Deposit" || entry.action === "Withdraw") && tx.amountRaw) {
8159
8494
  const target = previous.transactions[0];
8160
8495
  const known = new Set(target.logIndexes ?? []);
8161
8496
  if (tx.logIndexes?.some((index) => !known.has(index))) {
@@ -9121,7 +9456,7 @@ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9121
9456
  var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9122
9457
  var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9123
9458
  var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9124
- var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
9459
+ var WITHDRAWAL_UNDER_WAY_MAX_AGE_MS = 60 * 6e4;
9125
9460
  var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9126
9461
  var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9127
9462
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
@@ -10047,6 +10382,7 @@ var YieldseekerAgent = class {
10047
10382
  }
10048
10383
  async withdraw(state, chainId, asset, amount, onProgress, gasMode = "auto", onBeforeSubmission, assertOperation, submission) {
10049
10384
  let ownerTransferAttempted = false;
10385
+ const startedAt = Date.now();
10050
10386
  let evidence = {
10051
10387
  agentId: this.id,
10052
10388
  chainId,
@@ -10088,6 +10424,10 @@ var YieldseekerAgent = class {
10088
10424
  delivery: "failed"
10089
10425
  });
10090
10426
  throw error;
10427
+ } finally {
10428
+ for (const [wallet, markedAt] of this.releasingWallets) {
10429
+ if (markedAt >= startedAt) this.releasingWallets.delete(wallet);
10430
+ }
10091
10431
  }
10092
10432
  }
10093
10433
  async withdrawInternal(state, chainId, asset, amount, onProgress, onOwnerTransferAttempted, gasMode = "auto", onBeforeSubmission, assertOperation, operationId) {
@@ -11239,7 +11579,6 @@ var YieldseekerAgent = class {
11239
11579
  const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11240
11580
  if (await this.withdrawalUnderWay(state, chainId, slotAsset, context))
11241
11581
  return { notified: false, reason: "WITHDRAWAL_IN_PROGRESS" };
11242
- const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11243
11582
  let notified = false;
11244
11583
  let reason = "NOT_ALLOCATED";
11245
11584
  while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
@@ -11260,14 +11599,6 @@ var YieldseekerAgent = class {
11260
11599
  if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11261
11600
  const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11262
11601
  if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
11263
- if (cooldownEnds !== null)
11264
- return {
11265
- notified: true,
11266
- attempts,
11267
- allocated: false,
11268
- reason: "RECENT_WITHDRAWAL",
11269
- allocatesAfter: new Date(cooldownEnds).toISOString()
11270
- };
11271
11602
  reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11272
11603
  }
11273
11604
  return { notified: true, attempts, allocated: false, reason };
@@ -11324,11 +11655,6 @@ var YieldseekerAgent = class {
11324
11655
  debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11325
11656
  }
11326
11657
  }
11327
- /**
11328
- * When Yieldseeker may move funds again after this agent wallet's last
11329
- * confirmed withdrawal, if that is still ahead; null when there was none in
11330
- * the last hour or the ledger cannot say.
11331
- */
11332
11658
  /**
11333
11659
  * A withdrawal from this agent wallet that has started but not finished,
11334
11660
  * within the last hour: released by this page, or listed on the ledger with
@@ -11337,26 +11663,11 @@ var YieldseekerAgent = class {
11337
11663
  */
11338
11664
  async withdrawalUnderWay(state, chainId, asset, context) {
11339
11665
  const wallet = context.wallet.walletAddress.toLowerCase();
11340
- const since = Date.now() - YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11666
+ const since = Date.now() - WITHDRAWAL_UNDER_WAY_MAX_AGE_MS;
11341
11667
  if ((this.releasingWallets.get(wallet) ?? 0) > since) return true;
11342
11668
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11343
11669
  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)));
11344
11670
  }
11345
- async withdrawalCooldownEnd(state, chainId, asset, context) {
11346
- const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11347
- const wallet = context.wallet.walletAddress.toLowerCase();
11348
- let latest = 0;
11349
- for (const row of rows ?? []) {
11350
- if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
11351
- for (const leg of row.legs) {
11352
- if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
11353
- const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
11354
- if (Number.isFinite(at)) latest = Math.max(latest, at);
11355
- }
11356
- }
11357
- const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11358
- return latest > 0 && ends > Date.now() ? ends : null;
11359
- }
11360
11671
  /**
11361
11672
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
11362
11673
  * not collected from it, read at one block for a balance read. Cached
@@ -11486,16 +11797,18 @@ var YieldseekerAgent = class {
11486
11797
  (contextAsset) => this.loadVaultOptions(contextAsset, { includeUnavailable: true })
11487
11798
  )
11488
11799
  );
11800
+ const vaultOptions = catalog.flat().filter(
11801
+ (vaultOption) => vaultOption.chainId === chainId && isAddress4(vaultOption.address)
11802
+ );
11489
11803
  const vaultAddresses = new Set(
11490
- catalog.flat().filter(
11491
- (vaultOption) => vaultOption.chainId === chainId && isAddress4(vaultOption.address)
11492
- ).map((vaultOption) => vaultOption.address.toLowerCase())
11804
+ vaultOptions.map((vaultOption) => vaultOption.address.toLowerCase())
11493
11805
  );
11494
11806
  return mapYieldseekerHistory(contexts, {
11495
11807
  limit: options?.limit ?? 10,
11496
11808
  cursor: options?.cursor,
11497
11809
  ownerAddress: state.walletAddress,
11498
11810
  vaultAddresses,
11811
+ vaultOptions,
11499
11812
  ...options?.fromDate ? { fromDate: options.fromDate } : {},
11500
11813
  ...options?.toDate ? { toDate: options.toDate } : {}
11501
11814
  });
@@ -16629,7 +16942,6 @@ async function runAgentDepositBatch(chainId, legs, transfer) {
16629
16942
  // src/lib/walletconnect-switch.ts
16630
16943
  var WALLET_SWITCH_TIMEOUT_MS = 12e4;
16631
16944
  var HOLD_CHAIN_MS = 15e3;
16632
- var MAX_RESENDS = 2;
16633
16945
  var holds = /* @__PURE__ */ new Map();
16634
16946
  function parseChainId(raw2) {
16635
16947
  if (typeof raw2 === "number") return raw2;
@@ -16638,28 +16950,76 @@ function parseChainId(raw2) {
16638
16950
  const id = ref.startsWith("0x") ? Number.parseInt(ref, 16) : Number(ref);
16639
16951
  return Number.isFinite(id) ? id : void 0;
16640
16952
  }
16641
- function walletConnectCore(provider) {
16953
+ function walletConnectSession(provider) {
16642
16954
  const p = provider;
16643
16955
  const core = p?.signer ?? p;
16644
- if (typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
16956
+ if (typeof core?.request !== "function" || typeof core?.client?.request !== "function" || typeof core.setDefaultChain !== "function" || typeof core.session?.topic !== "string") {
16645
16957
  return null;
16646
16958
  }
16647
16959
  const peer = core.session.peer?.metadata?.name ?? "";
16648
- if (!/metamask/i.test(peer)) return null;
16649
- return core;
16960
+ if (/metamask/i.test(peer)) {
16961
+ return { core, strategy: "remote-wallet" };
16962
+ }
16963
+ if (/fireblocks/i.test(peer)) {
16964
+ return { core, strategy: "session-default" };
16965
+ }
16966
+ return null;
16967
+ }
16968
+ function approvedChains(core) {
16969
+ const approved = /* @__PURE__ */ new Set();
16970
+ for (const namespace of Object.values(core.session.namespaces ?? {})) {
16971
+ for (const chain2 of namespace.chains ?? []) approved.add(chain2);
16972
+ for (const account of namespace.accounts ?? []) {
16973
+ const [namespaceName, reference] = account.split(":");
16974
+ if (namespaceName && reference) {
16975
+ approved.add(`${namespaceName}:${reference}`);
16976
+ }
16977
+ }
16978
+ }
16979
+ return approved;
16980
+ }
16981
+ async function selectSessionDefaultChain(core, chainId) {
16982
+ const target = `eip155:${chainId}`;
16983
+ if (!approvedChains(core).has(target)) {
16984
+ throw new Error(
16985
+ `The WalletConnect session has not approved ${target}. Reconnect the wallet and try again.`
16986
+ );
16987
+ }
16988
+ core.setDefaultChain(target);
16989
+ const selected = parseChainId(
16990
+ await core.request({ method: "eth_chainId" })
16991
+ );
16992
+ debugLog("wc-switch", "selected WalletConnect session default", {
16993
+ peer: core.session.peer?.metadata?.name,
16994
+ target: chainId,
16995
+ selected
16996
+ });
16997
+ if (selected !== chainId) {
16998
+ throw new Error(
16999
+ `WalletConnect stayed on chain ${selected ?? "unknown"}; expected ${chainId}.`
17000
+ );
17001
+ }
16650
17002
  }
16651
17003
  async function switchWalletConnectChain(provider, chainId, timeoutMs = WALLET_SWITCH_TIMEOUT_MS) {
16652
- const core = walletConnectCore(provider);
16653
- if (!core) return false;
17004
+ const session = walletConnectSession(provider);
17005
+ if (!session) return false;
17006
+ const { core, strategy } = session;
16654
17007
  holds.get(core.session.topic)?.();
17008
+ if (strategy === "session-default") {
17009
+ await selectSessionDefaultChain(core, chainId);
17010
+ return true;
17011
+ }
16655
17012
  await requestSwitch(core, provider, chainId, timeoutMs);
16656
- holdChain(core, provider, chainId);
17013
+ holdChain(core, chainId);
16657
17014
  return true;
16658
17015
  }
16659
17016
  async function requestSwitch(core, provider, chainId, timeoutMs) {
16660
- const current = Number(
17017
+ const current = parseChainId(
16661
17018
  await provider.request({ method: "eth_chainId" })
16662
17019
  );
17020
+ if (current === void 0) {
17021
+ throw new Error("WalletConnect could not report its current chain.");
17022
+ }
16663
17023
  const hexChainId = `0x${chainId.toString(16)}`;
16664
17024
  let timer;
16665
17025
  try {
@@ -16689,26 +17049,27 @@ async function requestSwitch(core, provider, chainId, timeoutMs) {
16689
17049
  } catch {
16690
17050
  }
16691
17051
  }
16692
- function holdChain(core, provider, chainId) {
17052
+ function holdChain(core, chainId) {
16693
17053
  if (typeof core.on !== "function" || typeof core.removeListener !== "function") {
16694
17054
  return;
16695
17055
  }
16696
- let resends = 0;
17056
+ let repins = 0;
16697
17057
  const listener = (raw2) => {
16698
17058
  const reported = parseChainId(raw2);
16699
17059
  debugLog("wc-switch", "wallet reported chain", {
16700
17060
  reported,
16701
17061
  holding: chainId,
16702
- resends
17062
+ repins
16703
17063
  });
16704
17064
  if (reported === void 0 || reported === chainId) return;
16705
- if (resends >= MAX_RESENDS) return;
16706
- resends += 1;
16707
- void requestSwitch(core, provider, chainId, WALLET_SWITCH_TIMEOUT_MS).catch(
16708
- (error) => debugLog("wc-switch", "re-switch failed", {
17065
+ repins += 1;
17066
+ try {
17067
+ core.setDefaultChain(`eip155:${chainId}`);
17068
+ } catch (error) {
17069
+ debugLog("wc-switch", "session re-pin failed", {
16709
17070
  error: error instanceof Error ? error.message : String(error)
16710
- })
16711
- );
17071
+ });
17072
+ }
16712
17073
  };
16713
17074
  const release = () => {
16714
17075
  clearTimeout(timer);
@@ -16722,7 +17083,7 @@ function holdChain(core, provider, chainId) {
16722
17083
  holds.set(core.session.topic, release);
16723
17084
  }
16724
17085
  function withWalletConnectSwitch(provider) {
16725
- if (!walletConnectCore(provider)) return provider;
17086
+ if (!walletConnectSession(provider)) return provider;
16726
17087
  const target = provider;
16727
17088
  const request2 = async (args) => {
16728
17089
  if (args?.method !== "wallet_switchEthereumChain") {
@@ -17072,6 +17433,7 @@ var OwneySDK = class {
17072
17433
  yieldseekerApiBaseUrl;
17073
17434
  yieldseekerSiweOrigin;
17074
17435
  userPoolCustomization = false;
17436
+ excludedProtocols = [];
17075
17437
  routingApiBaseUrl;
17076
17438
  referralSource;
17077
17439
  ledger;
@@ -17082,6 +17444,7 @@ var OwneySDK = class {
17082
17444
  zyfaiServerTasks;
17083
17445
  /** The caller opted in to the Fusion+ secret handoff (`fusionSecretHandoff: true`). */
17084
17446
  fusionSecretHandoff;
17447
+ sessionStore;
17085
17448
  cachedSponsoredCallback = null;
17086
17449
  cachedWethSponsoredCallback = null;
17087
17450
  paymasterServiceUrl;
@@ -17124,7 +17487,9 @@ var OwneySDK = class {
17124
17487
  this.routingApiBaseUrl = config.routingApiBaseUrl;
17125
17488
  this.paymasterServiceUrl = config.paymasterServiceUrl;
17126
17489
  this.referralSource = config.referralSource;
17490
+ this.sessionStore = config.sessionStore;
17127
17491
  this.userPoolCustomization = config.userPoolCustomization ?? false;
17492
+ this.excludedProtocols = config.excludedProtocols ?? [];
17128
17493
  this.ledger = createFundingLedger({
17129
17494
  apiKey: config.apiKey,
17130
17495
  baseUrl: config.routingApiBaseUrl,
@@ -17879,7 +18244,9 @@ var OwneySDK = class {
17879
18244
  // Only an explicit opt-in lets the agent hand the Zyfai session to
17880
18245
  // Owney; a function is passed as it is and read per handoff.
17881
18246
  ...this.zyfaiServerTasks !== void 0 ? { zyfaiServerTasks: this.zyfaiServerTasks } : {}
17882
- }
18247
+ },
18248
+ this.sessionStore,
18249
+ this.excludedProtocols
17883
18250
  );
17884
18251
  }
17885
18252
  if (agentId === "yieldseeker") {