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

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.13";
1727
1727
  var SCOPE2 = "funding-ledger";
1728
1728
  var REQUEST_TIMEOUT_MS2 = 5e3;
1729
1729
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -4419,8 +4419,11 @@ var clearSession = (address, _chainId) => {
4419
4419
  function buildAutoSelectUpdate(current, asset, chainId) {
4420
4420
  const chains = current.chains ?? [];
4421
4421
  const chainMissing = chainId !== void 0 && !chains.includes(chainId);
4422
- if (current.autoSelectProtocols === true && !chainMissing) return null;
4423
4422
  const nextChains = chainMissing ? [...chains, chainId] : chains;
4423
+ if (current.savedPoolChoices) {
4424
+ return chainMissing ? { asset, chains: nextChains } : null;
4425
+ }
4426
+ if (current.autoSelectProtocols === true && !chainMissing) return null;
4424
4427
  return {
4425
4428
  asset,
4426
4429
  autoSelectProtocols: true,
@@ -4570,11 +4573,107 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
4570
4573
  }
4571
4574
  function mergeScopedPoolNames(current, scoped, allAvailableNames) {
4572
4575
  const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
4576
+ const offered = new Set(allAvailableNames);
4573
4577
  const existing = current.autoselect ? allAvailableNames : current.pools;
4574
- const preserved = existing.filter((name) => !managed.has(name));
4578
+ const preserved = existing.filter(
4579
+ (name) => !managed.has(name) && (offered.size === 0 || offered.has(name))
4580
+ );
4575
4581
  const selected = scoped.flatMap((entry) => entry.pools);
4576
4582
  return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
4577
4583
  }
4584
+ function savedPoolRecords(customization, protocolId, chainId) {
4585
+ if (!customization || typeof customization !== "object") return [];
4586
+ const records = [];
4587
+ for (const byProtocol of Object.values(customization)) {
4588
+ const byChain = byProtocol?.[protocolId];
4589
+ const record2 = byChain?.[String(chainId)];
4590
+ if (!record2 || typeof record2 !== "object") continue;
4591
+ records.push({
4592
+ pools: Array.isArray(record2.pools) ? record2.pools.filter((name) => typeof name === "string") : [],
4593
+ autoselect: typeof record2.autoselect === "boolean" ? record2.autoselect : void 0
4594
+ });
4595
+ }
4596
+ return records;
4597
+ }
4598
+ function hasManualPoolChoices(customization) {
4599
+ return manuallyChosenProtocols(customization).size > 0;
4600
+ }
4601
+ function manuallyChosenProtocols(customization) {
4602
+ const chosen = /* @__PURE__ */ new Set();
4603
+ if (!customization || typeof customization !== "object") return chosen;
4604
+ for (const byProtocol of Object.values(customization)) {
4605
+ for (const [protocolId, byChain] of Object.entries(byProtocol ?? {})) {
4606
+ const manual = Object.values(byChain ?? {}).some(
4607
+ (record2) => record2?.autoselect === false
4608
+ );
4609
+ if (manual) chosen.add(protocolId);
4610
+ }
4611
+ }
4612
+ return chosen;
4613
+ }
4614
+ function manualChainsOf(customization, protocolId) {
4615
+ if (!customization || typeof customization !== "object") return [];
4616
+ const chains = /* @__PURE__ */ new Set();
4617
+ for (const byProtocol of Object.values(customization)) {
4618
+ const byChain = byProtocol?.[protocolId];
4619
+ for (const [chainKey, record2] of Object.entries(byChain ?? {})) {
4620
+ const chainId = Number(chainKey);
4621
+ if (Number.isFinite(chainId) && record2?.autoselect === false) {
4622
+ chains.add(chainId);
4623
+ }
4624
+ }
4625
+ }
4626
+ return [...chains];
4627
+ }
4628
+ function protocolsSyncLeavesOff(customization, available, assetChains) {
4629
+ const off = /* @__PURE__ */ new Set();
4630
+ for (const protocol of available) {
4631
+ const chains = (protocol.chains ?? []).filter((chainId) => assetChains.includes(chainId));
4632
+ if (chains.length === 0) continue;
4633
+ const decided = chains.every((chainId) => {
4634
+ const records = savedPoolRecords(customization, protocol.id, chainId);
4635
+ return records.length > 0 && !savedRecordsAreAuto(records);
4636
+ });
4637
+ if (decided) off.add(protocol.id);
4638
+ }
4639
+ return off;
4640
+ }
4641
+ function tokenIsAsset(token, asset) {
4642
+ const upper = token.toUpperCase();
4643
+ return asset === "WETH" ? upper === "WETH" || upper === "ETH" : upper === asset;
4644
+ }
4645
+ function savedRecordsAreAuto(records) {
4646
+ return records.length === 0 || records.some((record2) => record2.autoselect !== false);
4647
+ }
4648
+ function protocolsToKeep(params) {
4649
+ const { asset, chains, customization, catalogs } = params;
4650
+ const entries = params.selections.filter(
4651
+ (entry) => entry.asset === asset && entry.availablePools.length > 0
4652
+ );
4653
+ const picked = entries.filter((entry) => entry.pools.length > 0).map((entry) => entry.protocolId);
4654
+ const candidates = [.../* @__PURE__ */ new Set([...params.current, ...picked])];
4655
+ const inUse = (protocolId) => {
4656
+ if (picked.includes(protocolId)) return true;
4657
+ const catalog = catalogs.get(protocolId);
4658
+ if (!catalog || catalog.length === 0) return true;
4659
+ const covered = new Set(
4660
+ entries.filter((entry) => entry.protocolId === protocolId).map((entry) => entry.chainId)
4661
+ );
4662
+ const assetChains = new Set(chains);
4663
+ const toCheck = [.../* @__PURE__ */ new Set([...chains, ...manualChainsOf(customization, protocolId)])];
4664
+ return toCheck.some((chainId) => {
4665
+ if (covered.has(chainId)) return false;
4666
+ const offered = new Set(
4667
+ catalog.filter((pool) => pool.chainId === chainId && tokenIsAsset(pool.token, asset)).map((pool) => pool.name)
4668
+ );
4669
+ if (offered.size === 0) return false;
4670
+ const records = savedPoolRecords(customization, protocolId, chainId);
4671
+ return assetChains.has(chainId) && savedRecordsAreAuto(records) || records.some((record2) => record2.autoselect === false && record2.pools.some((name) => offered.has(name)));
4672
+ });
4673
+ };
4674
+ const kept = candidates.filter(inUse);
4675
+ return kept.length > 0 ? kept : candidates;
4676
+ }
4578
4677
  function mapAvailablePools(raw2) {
4579
4678
  const byChain = raw2 ?? {};
4580
4679
  if (typeof byChain !== "object" || byChain === null) return [];
@@ -5486,7 +5585,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
5486
5585
  );
5487
5586
  return;
5488
5587
  }
5489
- const update = buildProtocolMergeUpdate(available, current, asset);
5588
+ const decided = protocolsSyncLeavesOff(
5589
+ current.customization,
5590
+ available,
5591
+ current.chains ?? []
5592
+ );
5593
+ const update = buildProtocolMergeUpdate(
5594
+ available.filter((protocol) => !decided.has(protocol.id)),
5595
+ current,
5596
+ asset
5597
+ );
5490
5598
  if (!update) return;
5491
5599
  await this.sdk.updateUserProfile(update);
5492
5600
  debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
@@ -5828,14 +5936,23 @@ var ZyfaiAgent = class _ZyfaiAgent {
5828
5936
  group.push(entry);
5829
5937
  byPair.set(pair, group);
5830
5938
  }
5939
+ const catalogReads = /* @__PURE__ */ new Map();
5940
+ const catalogOf = (protocolId) => {
5941
+ let read2 = catalogReads.get(protocolId);
5942
+ if (!read2) {
5943
+ read2 = this.sdk.getAvailablePools(protocolId, "yieldmaxxing").then(mapAvailablePools);
5944
+ catalogReads.set(protocolId, read2);
5945
+ }
5946
+ return read2;
5947
+ };
5831
5948
  const customizations = await Promise.all(
5832
5949
  [...byPair.values()].map(async (scoped) => {
5833
5950
  const { protocolId, chainId } = scoped[0];
5834
- const [current, rawAvailable] = await Promise.all([
5951
+ const [current, catalog] = await Promise.all([
5835
5952
  this.sdk.getSelectedPools(protocolId, chainId),
5836
- this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
5953
+ catalogOf(protocolId)
5837
5954
  ]);
5838
- const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5955
+ const allAvailableNames = catalog.filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5839
5956
  return {
5840
5957
  protocolId,
5841
5958
  chainId,
@@ -5859,13 +5976,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
5859
5976
  await Promise.all(
5860
5977
  selection.strategies.map(async ({ asset, strategy }) => {
5861
5978
  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 });
5979
+ const listed = current.protocols ?? [];
5980
+ const unpicked = listed.filter((protocolId) => !selection.selections.some(
5981
+ (entry) => entry.asset === asset && entry.protocolId === protocolId && entry.pools.length > 0
5982
+ ));
5983
+ const catalogs = new Map(await Promise.all(unpicked.map(async (protocolId) => [protocolId, await catalogOf(protocolId).catch(() => null)])));
5984
+ const protocols = protocolsToKeep({
5985
+ asset,
5986
+ current: listed,
5987
+ chains: current.chains ?? [],
5988
+ selections: selection.selections,
5989
+ customization: current.customization,
5990
+ catalogs
5991
+ });
5992
+ await this.sdk.updateUserProfile({
5993
+ asset,
5994
+ strategy,
5995
+ protocols,
5996
+ autoSelectProtocols: false
5997
+ });
5869
5998
  })
5870
5999
  );
5871
6000
  } catch (error) {
@@ -7726,7 +7855,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
7726
7855
  const update = buildAutoSelectUpdate(
7727
7856
  {
7728
7857
  autoSelectProtocols: current.autoSelectProtocols,
7729
- chains: current.chains
7858
+ chains: current.chains,
7859
+ savedPoolChoices: hasManualPoolChoices(current.customization)
7730
7860
  },
7731
7861
  asset,
7732
7862
  isValidChainId(chainId)
@@ -9781,7 +9911,7 @@ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9781
9911
  var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9782
9912
  var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9783
9913
  var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9784
- var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
9914
+ var WITHDRAWAL_UNDER_WAY_MAX_AGE_MS = 60 * 6e4;
9785
9915
  var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9786
9916
  var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9787
9917
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
@@ -10707,6 +10837,7 @@ var YieldseekerAgent = class {
10707
10837
  }
10708
10838
  async withdraw(state, chainId, asset, amount, onProgress, gasMode = "auto", onBeforeSubmission, assertOperation, submission) {
10709
10839
  let ownerTransferAttempted = false;
10840
+ const startedAt = Date.now();
10710
10841
  let evidence = {
10711
10842
  agentId: this.id,
10712
10843
  chainId,
@@ -10748,6 +10879,10 @@ var YieldseekerAgent = class {
10748
10879
  delivery: "failed"
10749
10880
  });
10750
10881
  throw error;
10882
+ } finally {
10883
+ for (const [wallet, markedAt] of this.releasingWallets) {
10884
+ if (markedAt >= startedAt) this.releasingWallets.delete(wallet);
10885
+ }
10751
10886
  }
10752
10887
  }
10753
10888
  async withdrawInternal(state, chainId, asset, amount, onProgress, onOwnerTransferAttempted, gasMode = "auto", onBeforeSubmission, assertOperation, operationId) {
@@ -11899,7 +12034,6 @@ var YieldseekerAgent = class {
11899
12034
  const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11900
12035
  if (await this.withdrawalUnderWay(state, chainId, slotAsset, context))
11901
12036
  return { notified: false, reason: "WITHDRAWAL_IN_PROGRESS" };
11902
- const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11903
12037
  let notified = false;
11904
12038
  let reason = "NOT_ALLOCATED";
11905
12039
  while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
@@ -11920,14 +12054,6 @@ var YieldseekerAgent = class {
11920
12054
  if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11921
12055
  const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11922
12056
  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
12057
  reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11932
12058
  }
11933
12059
  return { notified: true, attempts, allocated: false, reason };
@@ -11984,11 +12110,6 @@ var YieldseekerAgent = class {
11984
12110
  debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11985
12111
  }
11986
12112
  }
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
12113
  /**
11993
12114
  * A withdrawal from this agent wallet that has started but not finished,
11994
12115
  * within the last hour: released by this page, or listed on the ledger with
@@ -11997,26 +12118,11 @@ var YieldseekerAgent = class {
11997
12118
  */
11998
12119
  async withdrawalUnderWay(state, chainId, asset, context) {
11999
12120
  const wallet = context.wallet.walletAddress.toLowerCase();
12000
- const since = Date.now() - YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
12121
+ const since = Date.now() - WITHDRAWAL_UNDER_WAY_MAX_AGE_MS;
12001
12122
  if ((this.releasingWallets.get(wallet) ?? 0) > since) return true;
12002
12123
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
12003
12124
  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
12125
  }
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
12126
  /**
12021
12127
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
12022
12128
  * not collected from it, read at one block for a balance read. Cached
package/dist/index.d.cts CHANGED
@@ -652,15 +652,13 @@ type AgentFundingLedgerAccess = {
652
652
  /**
653
653
  * What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`).
654
654
  * `attempts` counts the provider calls made. `allocated` is set when the agent
655
- * checked whether the deposit was put to work; `allocatesAfter` (ISO) is when
656
- * the provider will act on it at the earliest, when it said so.
655
+ * checked whether the deposit was put to work.
657
656
  */
658
657
  type DepositNotice = {
659
658
  notified: true;
660
659
  attempts?: number;
661
660
  allocated?: boolean;
662
661
  reason?: string;
663
- allocatesAfter?: string;
664
662
  } | {
665
663
  notified: false;
666
664
  reason: string;
@@ -3489,11 +3487,6 @@ declare class YieldseekerAgent implements IAgent {
3489
3487
  * after a failure that may pass; stops when the session ends. Never throws.
3490
3488
  */
3491
3489
  private rebalanceAfterPoolSave;
3492
- /**
3493
- * When Yieldseeker may move funds again after this agent wallet's last
3494
- * confirmed withdrawal, if that is still ahead; null when there was none in
3495
- * the last hour or the ledger cannot say.
3496
- */
3497
3490
  /**
3498
3491
  * A withdrawal from this agent wallet that has started but not finished,
3499
3492
  * within the last hour: released by this page, or listed on the ledger with
@@ -3501,7 +3494,6 @@ declare class YieldseekerAgent implements IAgent {
3501
3494
  * do not count, so a stuck record cannot hold deposits back for good.
3502
3495
  */
3503
3496
  private withdrawalUnderWay;
3504
- private withdrawalCooldownEnd;
3505
3497
  /**
3506
3498
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
3507
3499
  * not collected from it, read at one block for a balance read. Cached
package/dist/index.d.ts CHANGED
@@ -652,15 +652,13 @@ type AgentFundingLedgerAccess = {
652
652
  /**
653
653
  * What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`).
654
654
  * `attempts` counts the provider calls made. `allocated` is set when the agent
655
- * checked whether the deposit was put to work; `allocatesAfter` (ISO) is when
656
- * the provider will act on it at the earliest, when it said so.
655
+ * checked whether the deposit was put to work.
657
656
  */
658
657
  type DepositNotice = {
659
658
  notified: true;
660
659
  attempts?: number;
661
660
  allocated?: boolean;
662
661
  reason?: string;
663
- allocatesAfter?: string;
664
662
  } | {
665
663
  notified: false;
666
664
  reason: string;
@@ -3489,11 +3487,6 @@ declare class YieldseekerAgent implements IAgent {
3489
3487
  * after a failure that may pass; stops when the session ends. Never throws.
3490
3488
  */
3491
3489
  private rebalanceAfterPoolSave;
3492
- /**
3493
- * When Yieldseeker may move funds again after this agent wallet's last
3494
- * confirmed withdrawal, if that is still ahead; null when there was none in
3495
- * the last hour or the ledger cannot say.
3496
- */
3497
3490
  /**
3498
3491
  * A withdrawal from this agent wallet that has started but not finished,
3499
3492
  * within the last hour: released by this page, or listed on the ledger with
@@ -3501,7 +3494,6 @@ declare class YieldseekerAgent implements IAgent {
3501
3494
  * do not count, so a stuck record cannot hold deposits back for good.
3502
3495
  */
3503
3496
  private withdrawalUnderWay;
3504
- private withdrawalCooldownEnd;
3505
3497
  /**
3506
3498
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
3507
3499
  * not collected from it, read at one block for a balance read. Cached
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.13";
1055
1055
  var SCOPE2 = "funding-ledger";
1056
1056
  var REQUEST_TIMEOUT_MS2 = 5e3;
1057
1057
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -3734,8 +3734,11 @@ var clearSession = (address, _chainId) => {
3734
3734
  function buildAutoSelectUpdate(current, asset, chainId) {
3735
3735
  const chains = current.chains ?? [];
3736
3736
  const chainMissing = chainId !== void 0 && !chains.includes(chainId);
3737
- if (current.autoSelectProtocols === true && !chainMissing) return null;
3738
3737
  const nextChains = chainMissing ? [...chains, chainId] : chains;
3738
+ if (current.savedPoolChoices) {
3739
+ return chainMissing ? { asset, chains: nextChains } : null;
3740
+ }
3741
+ if (current.autoSelectProtocols === true && !chainMissing) return null;
3739
3742
  return {
3740
3743
  asset,
3741
3744
  autoSelectProtocols: true,
@@ -3885,11 +3888,107 @@ function protocolsPolicyNeedsUpdate(current, desiredProtocols, desiredAutoSelect
3885
3888
  }
3886
3889
  function mergeScopedPoolNames(current, scoped, allAvailableNames) {
3887
3890
  const managed = new Set(scoped.flatMap((entry) => entry.availablePools));
3891
+ const offered = new Set(allAvailableNames);
3888
3892
  const existing = current.autoselect ? allAvailableNames : current.pools;
3889
- const preserved = existing.filter((name) => !managed.has(name));
3893
+ const preserved = existing.filter(
3894
+ (name) => !managed.has(name) && (offered.size === 0 || offered.has(name))
3895
+ );
3890
3896
  const selected = scoped.flatMap((entry) => entry.pools);
3891
3897
  return [.../* @__PURE__ */ new Set([...preserved, ...selected])];
3892
3898
  }
3899
+ function savedPoolRecords(customization, protocolId, chainId) {
3900
+ if (!customization || typeof customization !== "object") return [];
3901
+ const records = [];
3902
+ for (const byProtocol of Object.values(customization)) {
3903
+ const byChain = byProtocol?.[protocolId];
3904
+ const record2 = byChain?.[String(chainId)];
3905
+ if (!record2 || typeof record2 !== "object") continue;
3906
+ records.push({
3907
+ pools: Array.isArray(record2.pools) ? record2.pools.filter((name) => typeof name === "string") : [],
3908
+ autoselect: typeof record2.autoselect === "boolean" ? record2.autoselect : void 0
3909
+ });
3910
+ }
3911
+ return records;
3912
+ }
3913
+ function hasManualPoolChoices(customization) {
3914
+ return manuallyChosenProtocols(customization).size > 0;
3915
+ }
3916
+ function manuallyChosenProtocols(customization) {
3917
+ const chosen = /* @__PURE__ */ new Set();
3918
+ if (!customization || typeof customization !== "object") return chosen;
3919
+ for (const byProtocol of Object.values(customization)) {
3920
+ for (const [protocolId, byChain] of Object.entries(byProtocol ?? {})) {
3921
+ const manual = Object.values(byChain ?? {}).some(
3922
+ (record2) => record2?.autoselect === false
3923
+ );
3924
+ if (manual) chosen.add(protocolId);
3925
+ }
3926
+ }
3927
+ return chosen;
3928
+ }
3929
+ function manualChainsOf(customization, protocolId) {
3930
+ if (!customization || typeof customization !== "object") return [];
3931
+ const chains = /* @__PURE__ */ new Set();
3932
+ for (const byProtocol of Object.values(customization)) {
3933
+ const byChain = byProtocol?.[protocolId];
3934
+ for (const [chainKey, record2] of Object.entries(byChain ?? {})) {
3935
+ const chainId = Number(chainKey);
3936
+ if (Number.isFinite(chainId) && record2?.autoselect === false) {
3937
+ chains.add(chainId);
3938
+ }
3939
+ }
3940
+ }
3941
+ return [...chains];
3942
+ }
3943
+ function protocolsSyncLeavesOff(customization, available, assetChains) {
3944
+ const off = /* @__PURE__ */ new Set();
3945
+ for (const protocol of available) {
3946
+ const chains = (protocol.chains ?? []).filter((chainId) => assetChains.includes(chainId));
3947
+ if (chains.length === 0) continue;
3948
+ const decided = chains.every((chainId) => {
3949
+ const records = savedPoolRecords(customization, protocol.id, chainId);
3950
+ return records.length > 0 && !savedRecordsAreAuto(records);
3951
+ });
3952
+ if (decided) off.add(protocol.id);
3953
+ }
3954
+ return off;
3955
+ }
3956
+ function tokenIsAsset(token, asset) {
3957
+ const upper = token.toUpperCase();
3958
+ return asset === "WETH" ? upper === "WETH" || upper === "ETH" : upper === asset;
3959
+ }
3960
+ function savedRecordsAreAuto(records) {
3961
+ return records.length === 0 || records.some((record2) => record2.autoselect !== false);
3962
+ }
3963
+ function protocolsToKeep(params) {
3964
+ const { asset, chains, customization, catalogs } = params;
3965
+ const entries = params.selections.filter(
3966
+ (entry) => entry.asset === asset && entry.availablePools.length > 0
3967
+ );
3968
+ const picked = entries.filter((entry) => entry.pools.length > 0).map((entry) => entry.protocolId);
3969
+ const candidates = [.../* @__PURE__ */ new Set([...params.current, ...picked])];
3970
+ const inUse = (protocolId) => {
3971
+ if (picked.includes(protocolId)) return true;
3972
+ const catalog = catalogs.get(protocolId);
3973
+ if (!catalog || catalog.length === 0) return true;
3974
+ const covered = new Set(
3975
+ entries.filter((entry) => entry.protocolId === protocolId).map((entry) => entry.chainId)
3976
+ );
3977
+ const assetChains = new Set(chains);
3978
+ const toCheck = [.../* @__PURE__ */ new Set([...chains, ...manualChainsOf(customization, protocolId)])];
3979
+ return toCheck.some((chainId) => {
3980
+ if (covered.has(chainId)) return false;
3981
+ const offered = new Set(
3982
+ catalog.filter((pool) => pool.chainId === chainId && tokenIsAsset(pool.token, asset)).map((pool) => pool.name)
3983
+ );
3984
+ if (offered.size === 0) return false;
3985
+ const records = savedPoolRecords(customization, protocolId, chainId);
3986
+ return assetChains.has(chainId) && savedRecordsAreAuto(records) || records.some((record2) => record2.autoselect === false && record2.pools.some((name) => offered.has(name)));
3987
+ });
3988
+ };
3989
+ const kept = candidates.filter(inUse);
3990
+ return kept.length > 0 ? kept : candidates;
3991
+ }
3893
3992
  function mapAvailablePools(raw2) {
3894
3993
  const byChain = raw2 ?? {};
3895
3994
  if (typeof byChain !== "object" || byChain === null) return [];
@@ -4803,7 +4902,16 @@ var ZyfaiAgent = class _ZyfaiAgent {
4803
4902
  );
4804
4903
  return;
4805
4904
  }
4806
- const update = buildProtocolMergeUpdate(available, current, asset);
4905
+ const decided = protocolsSyncLeavesOff(
4906
+ current.customization,
4907
+ available,
4908
+ current.chains ?? []
4909
+ );
4910
+ const update = buildProtocolMergeUpdate(
4911
+ available.filter((protocol) => !decided.has(protocol.id)),
4912
+ current,
4913
+ asset
4914
+ );
4807
4915
  if (!update) return;
4808
4916
  await this.sdk.updateUserProfile(update);
4809
4917
  debugLog("zyfai:protocol-sync", `${asset}: wrote profile update`, update);
@@ -5145,14 +5253,23 @@ var ZyfaiAgent = class _ZyfaiAgent {
5145
5253
  group.push(entry);
5146
5254
  byPair.set(pair, group);
5147
5255
  }
5256
+ const catalogReads = /* @__PURE__ */ new Map();
5257
+ const catalogOf = (protocolId) => {
5258
+ let read2 = catalogReads.get(protocolId);
5259
+ if (!read2) {
5260
+ read2 = this.sdk.getAvailablePools(protocolId, "yieldmaxxing").then(mapAvailablePools);
5261
+ catalogReads.set(protocolId, read2);
5262
+ }
5263
+ return read2;
5264
+ };
5148
5265
  const customizations = await Promise.all(
5149
5266
  [...byPair.values()].map(async (scoped) => {
5150
5267
  const { protocolId, chainId } = scoped[0];
5151
- const [current, rawAvailable] = await Promise.all([
5268
+ const [current, catalog] = await Promise.all([
5152
5269
  this.sdk.getSelectedPools(protocolId, chainId),
5153
- this.sdk.getAvailablePools(protocolId, "yieldmaxxing")
5270
+ catalogOf(protocolId)
5154
5271
  ]);
5155
- const allAvailableNames = mapAvailablePools(rawAvailable).filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5272
+ const allAvailableNames = catalog.filter((pool) => pool.chainId === chainId).map((pool) => pool.name);
5156
5273
  return {
5157
5274
  protocolId,
5158
5275
  chainId,
@@ -5176,13 +5293,25 @@ var ZyfaiAgent = class _ZyfaiAgent {
5176
5293
  await Promise.all(
5177
5294
  selection.strategies.map(async ({ asset, strategy }) => {
5178
5295
  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 });
5296
+ const listed = current.protocols ?? [];
5297
+ const unpicked = listed.filter((protocolId) => !selection.selections.some(
5298
+ (entry) => entry.asset === asset && entry.protocolId === protocolId && entry.pools.length > 0
5299
+ ));
5300
+ const catalogs = new Map(await Promise.all(unpicked.map(async (protocolId) => [protocolId, await catalogOf(protocolId).catch(() => null)])));
5301
+ const protocols = protocolsToKeep({
5302
+ asset,
5303
+ current: listed,
5304
+ chains: current.chains ?? [],
5305
+ selections: selection.selections,
5306
+ customization: current.customization,
5307
+ catalogs
5308
+ });
5309
+ await this.sdk.updateUserProfile({
5310
+ asset,
5311
+ strategy,
5312
+ protocols,
5313
+ autoSelectProtocols: false
5314
+ });
5186
5315
  })
5187
5316
  );
5188
5317
  } catch (error) {
@@ -7043,7 +7172,8 @@ var ZyfaiAgent = class _ZyfaiAgent {
7043
7172
  const update = buildAutoSelectUpdate(
7044
7173
  {
7045
7174
  autoSelectProtocols: current.autoSelectProtocols,
7046
- chains: current.chains
7175
+ chains: current.chains,
7176
+ savedPoolChoices: hasManualPoolChoices(current.customization)
7047
7177
  },
7048
7178
  asset,
7049
7179
  isValidChainId(chainId)
@@ -9121,7 +9251,7 @@ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9121
9251
  var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9122
9252
  var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9123
9253
  var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9124
- var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
9254
+ var WITHDRAWAL_UNDER_WAY_MAX_AGE_MS = 60 * 6e4;
9125
9255
  var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9126
9256
  var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9127
9257
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
@@ -10047,6 +10177,7 @@ var YieldseekerAgent = class {
10047
10177
  }
10048
10178
  async withdraw(state, chainId, asset, amount, onProgress, gasMode = "auto", onBeforeSubmission, assertOperation, submission) {
10049
10179
  let ownerTransferAttempted = false;
10180
+ const startedAt = Date.now();
10050
10181
  let evidence = {
10051
10182
  agentId: this.id,
10052
10183
  chainId,
@@ -10088,6 +10219,10 @@ var YieldseekerAgent = class {
10088
10219
  delivery: "failed"
10089
10220
  });
10090
10221
  throw error;
10222
+ } finally {
10223
+ for (const [wallet, markedAt] of this.releasingWallets) {
10224
+ if (markedAt >= startedAt) this.releasingWallets.delete(wallet);
10225
+ }
10091
10226
  }
10092
10227
  }
10093
10228
  async withdrawInternal(state, chainId, asset, amount, onProgress, onOwnerTransferAttempted, gasMode = "auto", onBeforeSubmission, assertOperation, operationId) {
@@ -11239,7 +11374,6 @@ var YieldseekerAgent = class {
11239
11374
  const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11240
11375
  if (await this.withdrawalUnderWay(state, chainId, slotAsset, context))
11241
11376
  return { notified: false, reason: "WITHDRAWAL_IN_PROGRESS" };
11242
- const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11243
11377
  let notified = false;
11244
11378
  let reason = "NOT_ALLOCATED";
11245
11379
  while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
@@ -11260,14 +11394,6 @@ var YieldseekerAgent = class {
11260
11394
  if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11261
11395
  const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11262
11396
  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
11397
  reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11272
11398
  }
11273
11399
  return { notified: true, attempts, allocated: false, reason };
@@ -11324,11 +11450,6 @@ var YieldseekerAgent = class {
11324
11450
  debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11325
11451
  }
11326
11452
  }
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
11453
  /**
11333
11454
  * A withdrawal from this agent wallet that has started but not finished,
11334
11455
  * within the last hour: released by this page, or listed on the ledger with
@@ -11337,26 +11458,11 @@ var YieldseekerAgent = class {
11337
11458
  */
11338
11459
  async withdrawalUnderWay(state, chainId, asset, context) {
11339
11460
  const wallet = context.wallet.walletAddress.toLowerCase();
11340
- const since = Date.now() - YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11461
+ const since = Date.now() - WITHDRAWAL_UNDER_WAY_MAX_AGE_MS;
11341
11462
  if ((this.releasingWallets.get(wallet) ?? 0) > since) return true;
11342
11463
  const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11343
11464
  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
11465
  }
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
11466
  /**
11361
11467
  * The agent wallet's base-asset balance and the platform fee Yieldseeker has
11362
11468
  * not collected from it, read at one block for a balance read. Cached
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.32-beta.12",
3
+ "version": "0.7.32-beta.13",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",