@owney/sdk 0.7.32-beta.7 → 0.7.32-beta.9

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
@@ -1683,7 +1683,7 @@ var SnapshotHistory = class {
1683
1683
  };
1684
1684
 
1685
1685
  // src/lib/funding-ledger.ts
1686
- var SDK_VERSION = "0.7.32-beta.7";
1686
+ var SDK_VERSION = "0.7.32-beta.9";
1687
1687
  var SCOPE2 = "funding-ledger";
1688
1688
  var REQUEST_TIMEOUT_MS2 = 5e3;
1689
1689
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -5663,9 +5663,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
5663
5663
  * Pool choices are merged into protocol/chain records and each active asset
5664
5664
  * is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
5665
5665
  * The whole operation must succeed before the caller starts moving funds.
5666
+ * A draft that would leave an asset on a chain with no Zyfai pool throws
5667
+ * POOL_SELECTION_REQUIRED before anything is written.
5666
5668
  */
5667
5669
  async setPoolSelection(selection) {
5668
5670
  try {
5671
+ await this.assertEveryTargetKeepsAPool(selection);
5669
5672
  await this.sdk.ensureFirstDepositSetup("aggressive");
5670
5673
  const byPair = /* @__PURE__ */ new Map();
5671
5674
  for (const entry of selection.selections) {
@@ -5722,6 +5725,56 @@ var ZyfaiAgent = class _ZyfaiAgent {
5722
5725
  throw error;
5723
5726
  }
5724
5727
  }
5728
+ /**
5729
+ * Every agent keeps at least one pool (2026-11-11). Throws
5730
+ * POOL_SELECTION_REQUIRED when the draft picks no pool for an asset on a
5731
+ * chain where it shows some, and no other protocol on that chain keeps one.
5732
+ * Zyfai saves per protocol and chain, so a protocol this draft does not
5733
+ * touch still counts: its saved picks for the asset, or autoselect over its
5734
+ * pools for the asset. Those are read only for a target the draft leaves
5735
+ * empty, and a lookup that fails proves nothing.
5736
+ */
5737
+ async assertEveryTargetKeepsAPool(selection) {
5738
+ const targets = /* @__PURE__ */ new Map();
5739
+ for (const entry of selection.selections) {
5740
+ const key2 = `${entry.asset}:${entry.chainId}`;
5741
+ const target = targets.get(key2) ?? { asset: entry.asset, chainId: entry.chainId, protocols: /* @__PURE__ */ new Set(), shown: false, picked: false };
5742
+ target.protocols.add(entry.protocolId);
5743
+ if (entry.availablePools.length > 0) target.shown = true;
5744
+ if (entry.pools.length > 0) target.picked = true;
5745
+ targets.set(key2, target);
5746
+ }
5747
+ for (const { asset, chainId, protocols, shown, picked } of targets.values()) {
5748
+ if (picked || !shown) continue;
5749
+ if (await this.otherProtocolKeepsAPool(asset, chainId, protocols)) continue;
5750
+ throw new OwneyError(
5751
+ "POOL_SELECTION_REQUIRED",
5752
+ `Every agent needs at least one pool. This save would leave Zyfai with no ${asset} pool on chain ${chainId}. Nothing was saved.`,
5753
+ { asset, chainId, reason: "NO_POOL_LEFT" },
5754
+ this.id
5755
+ );
5756
+ }
5757
+ }
5758
+ /** Whether a protocol outside `excluded` keeps a pool for `asset` on `chainId`. */
5759
+ async otherProtocolKeepsAPool(asset, chainId, excluded) {
5760
+ let universe = [];
5761
+ try {
5762
+ ({ protocols: universe } = await this.sdk.getAvailableProtocols(chainId));
5763
+ } catch {
5764
+ return false;
5765
+ }
5766
+ for (const protocol of universe) {
5767
+ if (excluded.has(protocol.id)) continue;
5768
+ try {
5769
+ const names = mapAvailablePools(await this.sdk.getAvailablePools(protocol.id, "yieldmaxxing")).filter((pool) => pool.chainId === chainId && pool.token.toUpperCase() === asset).map((pool) => pool.name);
5770
+ if (names.length === 0) continue;
5771
+ const current = await this.sdk.getSelectedPools(protocol.id, chainId);
5772
+ if (current.autoselect || (current.pools ?? []).some((name) => names.includes(name))) return true;
5773
+ } catch {
5774
+ }
5775
+ }
5776
+ return false;
5777
+ }
5725
5778
  /**
5726
5779
  * Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
5727
5780
  * pools per protocol/chain and the strategy per asset; both are read for the
@@ -7916,7 +7969,15 @@ var YieldseekerApiError = class extends Error {
7916
7969
  providerCode;
7917
7970
  responseFields;
7918
7971
  routing;
7972
+ /**
7973
+ * Owney's proxy refuses a user-level call for a wallet whose Yieldseeker
7974
+ * account was not created through Owney. Permanent: not a sign-in problem.
7975
+ */
7976
+ get isAccountNotOwney() {
7977
+ return this.status === 403 && this.routing?.code === "YIELDSEEKER_ACCOUNT_NOT_OWNEY";
7978
+ }
7919
7979
  get isAuthenticationError() {
7980
+ if (this.isAccountNotOwney) return false;
7920
7981
  return this.status === 401 || this.status === 403;
7921
7982
  }
7922
7983
  };
@@ -8107,6 +8168,27 @@ function position(value, asset, baseAssetDecimals) {
8107
8168
  liquidity: Number(option.withdrawableDepositsUsd)
8108
8169
  };
8109
8170
  }
8171
+ function userFunds(context, assetAddress) {
8172
+ const live = context.liveWallet;
8173
+ if (!live) {
8174
+ return { idle: assetAddressValue(context.snapshot.tokenBalances, assetAddress), positions: context.positions };
8175
+ }
8176
+ const idle = live.idleRaw > live.feesOwedRaw ? live.idleRaw - live.feesOwedRaw : 0n;
8177
+ const pending2 = /^\d+$/.test(context.snapshot.pendingFeesBase ?? "") ? BigInt(context.snapshot.pendingFeesBase) : 0n;
8178
+ let fees = (live.feesOwedRaw > live.idleRaw ? live.feesOwedRaw - live.idleRaw : 0n) + pending2;
8179
+ const amounts = context.positions.map((entry) => balanceRaw(entry.assetsBase, "vault positions"));
8180
+ const order = amounts.map((_, index) => index).sort((a, b) => amounts[b] > amounts[a] ? 1 : amounts[b] < amounts[a] ? -1 : 0);
8181
+ for (const index of order) {
8182
+ if (fees === 0n) break;
8183
+ const taken = amounts[index] < fees ? amounts[index] : fees;
8184
+ amounts[index] = amounts[index] - taken;
8185
+ fees -= taken;
8186
+ }
8187
+ return {
8188
+ idle: idle.toString(),
8189
+ positions: context.positions.map((entry, index) => ({ ...entry, assetsBase: amounts[index].toString() }))
8190
+ };
8191
+ }
8110
8192
  function mapYieldseekerBalances(contexts) {
8111
8193
  const tokens = [];
8112
8194
  const assetBalances = [];
@@ -8120,18 +8202,15 @@ function mapYieldseekerBalances(contexts) {
8120
8202
  asset: context.asset,
8121
8203
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
8122
8204
  });
8123
- const idle = assetAddressValue(
8124
- context.snapshot.tokenBalances,
8125
- metadata.address
8126
- );
8205
+ const funds = userFunds(context, metadata.address);
8127
8206
  tokens.push({
8128
8207
  chain: "BASE",
8129
8208
  chainId: 8453,
8130
8209
  asset: context.asset,
8131
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
8210
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
8132
8211
  });
8133
8212
  positions.push(
8134
- ...context.positions.map(
8213
+ ...funds.positions.map(
8135
8214
  (entry) => position(
8136
8215
  entry,
8137
8216
  context.asset,
@@ -9443,10 +9522,8 @@ var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
9443
9522
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
9444
9523
  var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
9445
9524
  var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
9446
- var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
9447
9525
  var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
9448
9526
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
9449
- var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
9450
9527
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
9451
9528
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
9452
9529
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
@@ -9500,6 +9577,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
9500
9577
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
9501
9578
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
9502
9579
  var YIELDSEEKER_LEDGER_GRACE_MS = 6e4;
9580
+ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9581
+ var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9582
+ var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9583
+ var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9584
+ var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
9585
+ var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9586
+ var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9503
9587
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
9504
9588
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
9505
9589
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -9569,6 +9653,18 @@ function query(params) {
9569
9653
  const encoded = search.toString();
9570
9654
  return encoded ? `?${encoded}` : "";
9571
9655
  }
9656
+ var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9657
+ function parseRawAmount(raw2) {
9658
+ if (!raw2 || !/^\d+$/.test(raw2)) return null;
9659
+ const amount = BigInt(raw2);
9660
+ return amount > 0n ? amount : null;
9661
+ }
9662
+ function reportNotice(onNotice, notice) {
9663
+ try {
9664
+ onNotice?.(notice);
9665
+ } catch {
9666
+ }
9667
+ }
9572
9668
  var YieldseekerAgent = class {
9573
9669
  id = "yieldseeker";
9574
9670
  balanceComposition = "tokens-plus-positions";
@@ -9603,7 +9699,13 @@ var YieldseekerAgent = class {
9603
9699
  agentContexts = /* @__PURE__ */ new Map();
9604
9700
  // Every resolved agent wallet, keyed by contextKey (slot + agentId).
9605
9701
  walletContexts = /* @__PURE__ */ new Map();
9702
+ // In-flight stored-account reads keyed by userKey, shared by concurrent
9703
+ // callers; a good read is kept for the session, a failed one is dropped.
9606
9704
  agentAccountReads = /* @__PURE__ */ new Map();
9705
+ // The agentId this session created, or adopted after a create conflict, per
9706
+ // slotKey. The session's account read can predate its record, so a slot with
9707
+ // no verified or superseded record still selects this agent until disconnect.
9708
+ sessionAgents = /* @__PURE__ */ new Map();
9607
9709
  reportedAccounts = /* @__PURE__ */ new Set();
9608
9710
  // Slots whose verified agent is missing even from a re-read list (and could
9609
9711
  // not be reopened), with the error the lookup failed with, until the list
@@ -9664,6 +9766,7 @@ var YieldseekerAgent = class {
9664
9766
  // Refresh when ready and the earnings hold (spec B2). Without ledger access,
9665
9767
  // or while the ledger read is null, settlement and earnings are as before.
9666
9768
  ledgerAccess;
9769
+ accountRefusedListener;
9667
9770
  ledgerReads = /* @__PURE__ */ new Map();
9668
9771
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9669
9772
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -9748,8 +9851,9 @@ var YieldseekerAgent = class {
9748
9851
  * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9749
9852
  * continues only when it is now open with the same address. Only the
9750
9853
  * verified record's agent is reopened: any other closed agent (a
9751
- * superseded-wallet match, or a named agent with no verified record, also
9752
- * when the accounts could not be read) refuses without a request;
9854
+ * superseded-wallet match, or the agent this session created or adopted
9855
+ * before its record exists, also when the accounts could not be read)
9856
+ * refuses without a request;
9753
9857
  * - anything else refuses with nothing sent, before any progress event,
9754
9858
  * signature or callback. Every refusal carries `notSubmitted` and
9755
9859
  * `safeToFallback: false`, so no paid fallback runs.
@@ -9786,6 +9890,7 @@ var YieldseekerAgent = class {
9786
9890
  fresh2 = answer.agentWallet;
9787
9891
  } catch (error) {
9788
9892
  this.assertSession(generation, chainId, asset);
9893
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9789
9894
  throw new OwneyError(
9790
9895
  "YIELDSEEKER_WALLET_UNVERIFIED",
9791
9896
  "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
@@ -9874,6 +9979,7 @@ var YieldseekerAgent = class {
9874
9979
  break;
9875
9980
  } catch (error) {
9876
9981
  this.assertSession(generation, chainId, asset);
9982
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9877
9983
  if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
9878
9984
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
9879
9985
  this.assertSession(generation, chainId, asset);
@@ -10159,6 +10265,7 @@ var YieldseekerAgent = class {
10159
10265
  this.agentContexts.clear();
10160
10266
  this.walletContexts.clear();
10161
10267
  this.agentAccountReads.clear();
10268
+ this.sessionAgents.clear();
10162
10269
  this.reportedAccounts.clear();
10163
10270
  this.pendingSlotInvalidations.clear();
10164
10271
  this.knownContextKeys.clear();
@@ -10406,7 +10513,8 @@ var YieldseekerAgent = class {
10406
10513
  }
10407
10514
  let sponsor = false;
10408
10515
  if (gasMode !== "paid") {
10409
- const status = await this.getWalletStatus(state, chainId, asset, true).catch(() => {
10516
+ const status = await this.getWalletStatus(state, chainId, asset, true).catch((error) => {
10517
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
10410
10518
  if (gasMode === "sponsored")
10411
10519
  throw new OwneyError(
10412
10520
  "SPONSOR_REQUEST_FAILED",
@@ -10506,8 +10614,11 @@ var YieldseekerAgent = class {
10506
10614
  let positionsStatus = "empty";
10507
10615
  const validatePositions = (values) => this.validateWithdrawalPositions(values, chainId, asset);
10508
10616
  validatePositions(positions);
10509
- const zeroValuePositions = /* @__PURE__ */ new WeakSet();
10510
- const hasPositions = (values) => values.some((position2) => !zeroValuePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n));
10617
+ const negligibleRaw = 10n ** BigInt(Math.max(metadata.decimals - 6, 0));
10618
+ const negligiblePositions = /* @__PURE__ */ new WeakSet();
10619
+ const negligibleVaults = /* @__PURE__ */ new Set();
10620
+ const hasPositions = (values) => values.some((position2) => !negligiblePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n));
10621
+ const provenNegligible = (position2) => negligibleVaults.has(position2.vaultOption.address.toLowerCase());
10511
10622
  const knownPositions = /* @__PURE__ */ new Map();
10512
10623
  const rememberPositions = (values) => {
10513
10624
  for (const position2 of values) knownPositions.set(position2.vaultOption.address.toLowerCase(), position2);
@@ -10537,6 +10648,7 @@ var YieldseekerAgent = class {
10537
10648
  if (!active || value === void 0) return null;
10538
10649
  this.assertSession(generation, chainId, asset);
10539
10650
  verified.withdrawableAssetsRaw = value.toString();
10651
+ if (value <= negligibleRaw && provenNegligible(position2)) negligiblePositions.add(verified);
10540
10652
  verifiedPositions.push(verified);
10541
10653
  return verified;
10542
10654
  }
@@ -10567,10 +10679,11 @@ var YieldseekerAgent = class {
10567
10679
  const redemptionValue = valuations[1];
10568
10680
  if (redemptionValue !== null && redemptionValue > 0n)
10569
10681
  verified.withdrawableAssetsRaw = redemptionValue.toString();
10682
+ if (valuations.every((value) => value !== null && value <= negligibleRaw) && provenNegligible(position2)) negligiblePositions.add(verified);
10570
10683
  return verified;
10571
10684
  }
10572
10685
  if (blockNumber === void 0 || valuations.some((value) => value !== 0n)) return null;
10573
- zeroValuePositions.add(verified);
10686
+ negligiblePositions.add(verified);
10574
10687
  }
10575
10688
  verifiedPositions.push(verified);
10576
10689
  return verified;
@@ -10673,6 +10786,40 @@ var YieldseekerAgent = class {
10673
10786
  let grossUnwound = 0n;
10674
10787
  let confirmedUnwinds = 0n;
10675
10788
  let latestUnwindBlock;
10789
+ let payFromCurrentFunds = false;
10790
+ const vaultShares = async (position2) => {
10791
+ try {
10792
+ const [underlying, shares] = await this.readVaultShares([position2.vaultOption], agentWallet);
10793
+ this.assertSession(generation, chainId, asset);
10794
+ if (underlying?.status !== "success" || shares?.status !== "success" || typeof underlying.result !== "string" || underlying.result.toLowerCase() !== metadata.address.toLowerCase() || typeof shares.result !== "bigint" || shares.result < 0n) return void 0;
10795
+ return shares.result;
10796
+ } catch (error) {
10797
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10798
+ return void 0;
10799
+ }
10800
+ };
10801
+ const releasedOnChain = async (position2, refused) => {
10802
+ const shares = await vaultShares(position2);
10803
+ if (shares === 0n) return true;
10804
+ if (shares === void 0 || !refused) return false;
10805
+ let negligible;
10806
+ try {
10807
+ if (nativeYieldseekerProtocol(position2.vaultOption)) {
10808
+ const value = await readNativeYieldseekerAssets(this.getReceiptClient(), position2.vaultOption, agentWallet, shares);
10809
+ negligible = value !== void 0 && value <= negligibleRaw;
10810
+ } else {
10811
+ const address = (0, import_viem17.getAddress)(position2.vaultOption.address);
10812
+ const values = await Promise.all(["convertToAssets", "previewRedeem"].map((functionName) => this.getReceiptClient().readContract({ address, abi: import_viem17.erc4626Abi, functionName, args: [shares] }).catch(() => void 0)));
10813
+ negligible = values.every((value) => typeof value === "bigint" && value >= 0n && value <= negligibleRaw);
10814
+ }
10815
+ } catch (error) {
10816
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10817
+ return false;
10818
+ }
10819
+ this.assertSession(generation, chainId, asset);
10820
+ if (negligible) negligibleVaults.add(position2.vaultOption.address.toLowerCase());
10821
+ return negligible;
10822
+ };
10676
10823
  const unwind = async (position2, assetsRaw) => {
10677
10824
  this.assertSession(generation, chainId, asset);
10678
10825
  assertOperation?.();
@@ -10697,6 +10844,13 @@ var YieldseekerAgent = class {
10697
10844
  }
10698
10845
  } catch (error) {
10699
10846
  this.invalidateFundingRead(state, chainId, asset);
10847
+ const refused = error instanceof OwneyError && error.details?.statusCode === 400;
10848
+ if (await releasedOnChain(position2, refused)) {
10849
+ payFromCurrentFunds = true;
10850
+ confirmedMovement = true;
10851
+ grossUnwound += assetsRaw;
10852
+ return;
10853
+ }
10700
10854
  throw new OwneyError(
10701
10855
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10702
10856
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10721,7 +10875,7 @@ var YieldseekerAgent = class {
10721
10875
  let unwound = false;
10722
10876
  for (const position2 of positions) {
10723
10877
  const available = BigInt(position2.withdrawableAssetsRaw);
10724
- if (available <= 0n) continue;
10878
+ if (available <= 0n || negligiblePositions.has(position2)) continue;
10725
10879
  await unwind(position2, available);
10726
10880
  unwound = true;
10727
10881
  }
@@ -10761,7 +10915,7 @@ var YieldseekerAgent = class {
10761
10915
  remaining: remaining.toString()
10762
10916
  });
10763
10917
  }
10764
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10918
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10765
10919
  const availableForOwner = ownerFunds.available;
10766
10920
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10767
10921
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -10914,7 +11068,7 @@ var YieldseekerAgent = class {
10914
11068
  reason: "YIELDSEEKER_MAX_INCOMPLETE",
10915
11069
  asset,
10916
11070
  positionsStatus,
10917
- remainingPositions: positionsStatus === "remaining" ? positions.filter((position2) => !zeroValuePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n)).map((position2) => ({
11071
+ remainingPositions: positionsStatus === "remaining" ? positions.filter((position2) => !negligiblePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n)).map((position2) => ({
10918
11072
  vaultAddress: position2.vaultOption.address,
10919
11073
  sharesRaw: position2.assetsRaw,
10920
11074
  withdrawableAmountRaw: position2.withdrawableAssetsRaw
@@ -11348,7 +11502,8 @@ var YieldseekerAgent = class {
11348
11502
  if (asset !== void 0) this.assertAsset(asset);
11349
11503
  const missingAssets = /* @__PURE__ */ new Set();
11350
11504
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
11351
- const balance = mapYieldseekerBalances(contexts);
11505
+ const liveWallets = await Promise.all(contexts.map((context) => this.readLiveWallet(state, chainId, context)));
11506
+ const balance = mapYieldseekerBalances(contexts.map((context, index) => liveWallets[index] === null ? context : { ...context, liveWallet: liveWallets[index] }));
11352
11507
  for (const [index, context] of contexts.entries()) {
11353
11508
  const read2 = balance.readMetadata[index];
11354
11509
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -11455,30 +11610,197 @@ var YieldseekerAgent = class {
11455
11610
  }
11456
11611
  /**
11457
11612
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
11458
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
11459
- * anything moves (the funding minimum, a deployed agent, no manual
11460
- * withdrawal in the last hour). Uses the agent this session already knows
11461
- * for the asset and the saved sign-in only: never prompts, never retries,
11462
- * never throws.
11613
+ * it now instead of on its next 30-minute check, and confirms it did.
11614
+ * Yieldseeker decides whether anything moves (the funding minimum, a
11615
+ * deployed agent, no manual withdrawal in the last hour), and its answer
11616
+ * (`{}`) does not say, so a minute after each notice the agent reads its
11617
+ * wallet: the deposit has gone into a vault when less than its amount is
11618
+ * left idle. While it has not, Yieldseeker is told again, up to
11619
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
11620
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
11621
+ * told once, since nothing can move yet. Uses the agent this session already
11622
+ * knows for the asset and the saved sign-in only: never prompts, never
11623
+ * throws. Each call is reported through `onNotice`.
11463
11624
  */
11464
- async depositConfirmed(state, chainId, evidence) {
11625
+ async depositConfirmed(state, chainId, evidence, onNotice) {
11626
+ let attempts = 0;
11465
11627
  try {
11466
11628
  const asset = String(evidence.token).toUpperCase();
11467
11629
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
11468
11630
  return { notified: false, reason: "UNSUPPORTED" };
11469
- const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11631
+ const slotAsset = asset;
11632
+ const context = this.agentContexts.get(this.slotKey(state, chainId, slotAsset));
11470
11633
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
11471
11634
  return { notified: false, reason: "NO_AGENT" };
11472
11635
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11636
+ const generation = this.readGeneration;
11637
+ const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11638
+ const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11639
+ let notified = false;
11640
+ let reason = "NOT_ALLOCATED";
11641
+ while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
11642
+ if (this.readGeneration !== generation || !this.auth.peekToken(state, chainId))
11643
+ return notified ? { notified: true, attempts, reason: "SESSION_ENDED" } : { notified: false, attempts, reason: "SESSION_ENDED" };
11644
+ attempts += 1;
11645
+ const sent = await this.sendDepositNotice(state, chainId, context);
11646
+ reportNotice(onNotice, sent.ok ? { notified: true, attempt: attempts } : { notified: false, reason: sent.reason, attempt: attempts });
11647
+ if (!sent.ok) {
11648
+ if (!sent.retryAfterMs || attempts >= DEPOSIT_NOTICE_ATTEMPTS)
11649
+ return notified ? { notified: true, attempts, allocated: false, reason: sent.reason } : { notified: false, attempts, reason: sent.reason };
11650
+ await wait2(sent.retryAfterMs);
11651
+ continue;
11652
+ }
11653
+ notified = true;
11654
+ if (amount === null) return { notified: true, attempts };
11655
+ await wait2(DEPOSIT_ALLOCATION_CHECK_MS);
11656
+ if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11657
+ const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11658
+ if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
11659
+ if (cooldownEnds !== null)
11660
+ return {
11661
+ notified: true,
11662
+ attempts,
11663
+ allocated: false,
11664
+ reason: "RECENT_WITHDRAWAL",
11665
+ allocatesAfter: new Date(cooldownEnds).toISOString()
11666
+ };
11667
+ reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11668
+ }
11669
+ return { notified: true, attempts, allocated: false, reason };
11670
+ } catch (error) {
11671
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR", ...attempts ? { attempts } : {} };
11672
+ }
11673
+ }
11674
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
11675
+ async sendDepositNotice(state, chainId, context) {
11676
+ try {
11473
11677
  await this.walletRequest(
11474
11678
  state,
11475
11679
  chainId,
11476
11680
  this.agentPath(context, "deposit-made"),
11477
11681
  { method: "POST", body: {}, promptless: true }
11478
11682
  );
11479
- return { notified: true };
11683
+ return { ok: true };
11480
11684
  } catch (error) {
11481
- return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
11685
+ if (!(error instanceof OwneyError)) return { ok: false, reason: "ERROR" };
11686
+ const details = error.details ?? {};
11687
+ const status = typeof details.statusCode === "number" ? details.statusCode : void 0;
11688
+ const transient = error.code === "AGENT_TIMEOUT" || error.code === "AGENT_API_ERROR" && (status === void 0 || status === 0 || status === 408 || status === 429 || status >= 500);
11689
+ const reason = status ? `HTTP_${status}` : error.code === "AGENT_API_ERROR" ? "NETWORK" : error.code;
11690
+ if (!transient) return { ok: false, reason };
11691
+ const named = Number(details.fields?.headers?.["Retry-After"]) * 1e3;
11692
+ return {
11693
+ ok: false,
11694
+ reason,
11695
+ retryAfterMs: Number.isFinite(named) && named > 0 ? Math.min(named, DEPOSIT_NOTICE_RETRY_MAX_MS) : DEPOSIT_NOTICE_RETRY_MS
11696
+ };
11697
+ }
11698
+ }
11699
+ /**
11700
+ * Tells Yieldseeker (`deposit-made`) after a pool save, so the agent runs
11701
+ * now and rebalances money already in a vault the list no longer allows.
11702
+ * Up to DEPOSIT_NOTICE_ATTEMPTS calls in all, waiting between them only
11703
+ * after a failure that may pass; stops when the session ends. Never throws.
11704
+ */
11705
+ async rebalanceAfterPoolSave(state, context, asset) {
11706
+ const generation = this.readGeneration;
11707
+ try {
11708
+ for (let attempt = 1; attempt <= DEPOSIT_NOTICE_ATTEMPTS; attempt += 1) {
11709
+ if (this.readGeneration !== generation) return;
11710
+ const sent = await this.sendDepositNotice(state, 8453, context);
11711
+ if (sent.ok) {
11712
+ debugLog("yieldseeker:pools", `${asset}: agent ${context.agent.agentId} told to rebalance`, { attempt });
11713
+ return;
11714
+ }
11715
+ debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { attempt, reason: sent.reason });
11716
+ if (!sent.retryAfterMs || attempt >= DEPOSIT_NOTICE_ATTEMPTS) return;
11717
+ await wait2(sent.retryAfterMs);
11718
+ }
11719
+ } catch (error) {
11720
+ debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11721
+ }
11722
+ }
11723
+ /**
11724
+ * When Yieldseeker may move funds again after this agent wallet's last
11725
+ * confirmed withdrawal, if that is still ahead; null when there was none in
11726
+ * the last hour or the ledger cannot say.
11727
+ */
11728
+ async withdrawalCooldownEnd(state, chainId, asset, context) {
11729
+ const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11730
+ const wallet = context.wallet.walletAddress.toLowerCase();
11731
+ let latest = 0;
11732
+ for (const row of rows ?? []) {
11733
+ if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
11734
+ for (const leg of row.legs) {
11735
+ if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
11736
+ const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
11737
+ if (Number.isFinite(at)) latest = Math.max(latest, at);
11738
+ }
11739
+ }
11740
+ const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11741
+ return latest > 0 && ends > Date.now() ? ends : null;
11742
+ }
11743
+ /**
11744
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
11745
+ * not collected from it, read at one block for a balance read. Cached
11746
+ * briefly per agent wallet and dropped by funding and allocation
11747
+ * invalidations. Null when any read fails or is slow: the snapshot's
11748
+ * amounts are used instead.
11749
+ */
11750
+ readLiveWallet(state, chainId, context) {
11751
+ const contextKey = this.contextKey(state, chainId, context);
11752
+ return this.cachedRead(`idle:${contextKey}`, YIELDSEEKER_LIVE_IDLE_CACHE_MS, () => withinBudget(
11753
+ this.readWalletFunds(chainId, context.asset, context.wallet.walletAddress),
11754
+ YIELDSEEKER_LIVE_IDLE_BUDGET_MS,
11755
+ null
11756
+ ));
11757
+ }
11758
+ async readWalletFunds(chainId, asset, walletAddress) {
11759
+ try {
11760
+ const client = this.getReceiptClient();
11761
+ const wallet = (0, import_viem17.getAddress)(walletAddress);
11762
+ const read2 = (operation) => withPaidRpcDiagnostics(operation, chainId, "eth_call", this.id);
11763
+ const blockNumber = await read2(() => client.getBlockNumber());
11764
+ const feeTracker = await read2(() => client.readContract({
11765
+ address: wallet,
11766
+ abi: YIELDSEEKER_AGENT_WALLET_ABI,
11767
+ functionName: "feeTracker",
11768
+ blockNumber
11769
+ }));
11770
+ if (!(0, import_viem17.isAddress)(feeTracker) || /^0x0{40}$/i.test(feeTracker)) return null;
11771
+ const [idle, owed] = await Promise.all([
11772
+ read2(() => client.readContract({
11773
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11774
+ abi: import_viem17.erc20Abi,
11775
+ functionName: "balanceOf",
11776
+ args: [wallet],
11777
+ blockNumber
11778
+ })),
11779
+ read2(() => client.readContract({
11780
+ address: (0, import_viem17.getAddress)(feeTracker),
11781
+ abi: YIELDSEEKER_FEE_TRACKER_ABI,
11782
+ functionName: "getFeesOwed",
11783
+ args: [wallet],
11784
+ blockNumber
11785
+ }))
11786
+ ]);
11787
+ return typeof idle === "bigint" && idle >= 0n && typeof owed === "bigint" && owed >= 0n ? { idleRaw: idle, feesOwedRaw: owed } : null;
11788
+ } catch {
11789
+ return null;
11790
+ }
11791
+ }
11792
+ /** The agent wallet's idle base asset; null when the read fails. */
11793
+ async readIdleBalance(chainId, asset, wallet) {
11794
+ try {
11795
+ const idle = await withPaidRpcDiagnostics(() => this.getReceiptClient().readContract({
11796
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11797
+ abi: import_viem17.erc20Abi,
11798
+ functionName: "balanceOf",
11799
+ args: [(0, import_viem17.getAddress)(wallet)]
11800
+ }), chainId, "eth_call", this.id);
11801
+ return typeof idle === "bigint" && idle >= 0n ? idle : null;
11802
+ } catch {
11803
+ return null;
11482
11804
  }
11483
11805
  }
11484
11806
  async getFundingWallet(state, chainId, asset) {
@@ -11681,13 +12003,11 @@ var YieldseekerAgent = class {
11681
12003
  *
11682
12004
  * - Only Base entries are ours. An asset with no picks whose entries showed
11683
12005
  * no vault is skipped and nothing is sent.
12006
+ * - None picked (vaults shown) for any asset: every agent keeps at least one
12007
+ * pool (2026-11-11), so the whole save throws POOL_SELECTION_REQUIRED
12008
+ * before anything is written, for any asset.
11684
12009
  * - Some vaults picked: the managed list names them. Saving it again
11685
12010
  * replaces it, so there is only ever one.
11686
- * - None picked (vaults shown): the managed list names no vault, and the
11687
- * rules must read back as an empty allow-list. Yieldseeker then keeps the
11688
- * agent's money out of every vault, as Zyfai does with an empty pool list,
11689
- * and the next Pools step reads "none". Only an agent that already exists
11690
- * is written: one is never created just to hold "none".
11691
12011
  * - Every vault picked: the managed list is deleted, and no allow-list may
11692
12012
  * remain, so vaults Yieldseeker adds later are allowed too.
11693
12013
  * - A free-text allow-list we saved before the managed list existed is
@@ -11720,21 +12040,27 @@ var YieldseekerAgent = class {
11720
12040
  group.shown.push(...entry.availablePools);
11721
12041
  byAsset.set(entry.asset, group);
11722
12042
  }
12043
+ for (const [asset, group] of byAsset) {
12044
+ if (uniqueAddresses(group.picked).length === 0 && uniqueAddresses(group.shown).length > 0) {
12045
+ throw new OwneyError(
12046
+ "POOL_SELECTION_REQUIRED",
12047
+ `Every agent needs at least one pool. This save would leave the Yieldseeker ${asset} agent with no vault on Base. Nothing was saved.`,
12048
+ { asset, chainId: 8453, reason: "NO_POOL_LEFT" },
12049
+ this.id
12050
+ );
12051
+ }
12052
+ }
11723
12053
  for (const [asset, group] of byAsset) {
11724
12054
  const picks = uniqueAddresses(group.picked);
11725
12055
  const shown = uniqueAddresses(group.shown);
11726
- if (picks.length === 0 && shown.length === 0) continue;
12056
+ if (picks.length === 0) continue;
11727
12057
  const picked = new Set(picks.map((address) => address.toLowerCase()));
11728
12058
  const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11729
12059
  await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11730
12060
  }
11731
12061
  }
11732
12062
  async savePoolPicks(state, asset, picks, everyVaultPicked) {
11733
- const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11734
- if (!context) {
11735
- debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11736
- return;
11737
- }
12063
+ const context = await this.ensureAgent(state, 8453, asset);
11738
12064
  const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11739
12065
  const managed = active.find(isManagedVaultList);
11740
12066
  const legacy = active.filter(isLegacyPoolSelectionMemory);
@@ -11756,6 +12082,7 @@ var YieldseekerAgent = class {
11756
12082
  });
11757
12083
  change.written = true;
11758
12084
  }
12085
+ } else if (managed?.content === content) {
11759
12086
  } else {
11760
12087
  const answer = await this.memoryRequest(state, context, "memories", {
11761
12088
  method: "POST",
@@ -11773,7 +12100,10 @@ var YieldseekerAgent = class {
11773
12100
  } catch {
11774
12101
  failure = "READ_BACK_FAILED";
11775
12102
  }
11776
- if (!failure) return;
12103
+ if (!failure) {
12104
+ if (change.written) void this.rebalanceAfterPoolSave(state, context, asset);
12105
+ return;
12106
+ }
11777
12107
  const restored = await this.restorePoolMemory(state, context, change);
11778
12108
  throw new OwneyError(
11779
12109
  "POOL_SELECTION_NOT_APPLIED",
@@ -11804,10 +12134,10 @@ var YieldseekerAgent = class {
11804
12134
  }
11805
12135
  /**
11806
12136
  * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11807
- * has no brackets. No picks names no vault.
12137
+ * has no brackets. There is always at least one pick (setPoolSelection
12138
+ * refuses a save with none).
11808
12139
  */
11809
12140
  async poolMemoryContent(asset, picks) {
11810
- if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11811
12141
  const vaults = new Map(
11812
12142
  (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11813
12143
  );
@@ -12054,29 +12384,26 @@ var YieldseekerAgent = class {
12054
12384
  }
12055
12385
  /**
12056
12386
  * The routing API's stored accounts for owner+chain, read once per session.
12057
- * Resolves null when unavailable (callers keep name matching) and never
12058
- * rejects. A failure is retried after a short window.
12387
+ * Resolves null when unavailable and never rejects; callers then refuse
12388
+ * (AGENT_ACCOUNTS_UNAVAILABLE) and create nothing. A failure is not kept:
12389
+ * concurrent callers share the in-flight read, and the next call reads again.
12059
12390
  */
12060
12391
  agentAccounts(state, chainId) {
12061
12392
  const key2 = this.userKey(state, chainId);
12062
12393
  const cached = this.agentAccountReads.get(key2);
12063
- if (cached && cached.expiresAt > Date.now()) return cached.value;
12064
- const generation = this.readGeneration;
12394
+ if (cached) return cached;
12065
12395
  const value = fetchAgentAccounts({
12066
12396
  apiKey: this.owneyApiKey,
12067
12397
  baseUrl: this.routingApiBaseUrl,
12068
12398
  owner: state.walletAddress,
12069
12399
  chainId
12070
12400
  }).catch(() => null).then((accounts) => {
12071
- if (accounts === null && this.readGeneration === generation && this.agentAccountReads.get(key2)?.value === value) {
12072
- this.agentAccountReads.set(key2, {
12073
- value,
12074
- expiresAt: Date.now() + YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS
12075
- });
12401
+ if (accounts === null && this.agentAccountReads.get(key2) === value) {
12402
+ this.agentAccountReads.delete(key2);
12076
12403
  }
12077
12404
  return accounts;
12078
12405
  });
12079
- this.agentAccountReads.set(key2, { value, expiresAt: Number.POSITIVE_INFINITY });
12406
+ this.agentAccountReads.set(key2, value);
12080
12407
  return value;
12081
12408
  }
12082
12409
  /** Yieldseeker accounts for one slot (returned addresses are compared lowercase). */
@@ -12348,16 +12675,28 @@ var YieldseekerAgent = class {
12348
12675
  * 1. the listed fitting agent whose wallet is the verified account's wallet,
12349
12676
  * whatever its name; the stored agentId is only a hint;
12350
12677
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
12351
- * 3. else the fitting agent named "owney" (first use, migration, or a
12352
- * verified wallet that is not a fitting listed agent), unless step 1/2
12353
- * read its wallet and it is closed (deactivated): that agent is not listed;
12354
- * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
12355
- * create); without one, undefined (the caller may create).
12678
+ * 3. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
12679
+ * create);
12680
+ * 4. else, with no record at all, the listed agent this session created or
12681
+ * adopted for the slot (sessionAgents); without one, undefined (the
12682
+ * caller creates an agent named "owney"). An agent is never picked by
12683
+ * its name: only our records, and this session's own create, say which
12684
+ * agents are Owney's.
12685
+ * Without the account records (`null`: the read failed) nothing can be
12686
+ * known, so the call is refused and nothing is created.
12356
12687
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
12357
12688
  * wallet reads. The account report then records the selected wallet; the
12358
12689
  * server marks it superseded when it differs from the verified wallet.
12359
12690
  */
12360
12691
  async chooseAgent(state, chainId, user, agents, accounts, asset) {
12692
+ if (accounts === null) {
12693
+ throw new OwneyError(
12694
+ "AGENT_API_ERROR",
12695
+ "Owney could not read this account's agents. Nothing was created. Please try again.",
12696
+ { rpcSource: "owney-api", reason: "AGENT_ACCOUNTS_UNAVAILABLE", chainId, asset },
12697
+ this.id
12698
+ );
12699
+ }
12361
12700
  const slot = this.slotAccounts(accounts, chainId, asset);
12362
12701
  const verified = slot.find((account) => account.status === "verified");
12363
12702
  const superseded = slot.filter((account) => account.status === "superseded");
@@ -12379,9 +12718,11 @@ var YieldseekerAgent = class {
12379
12718
  closed
12380
12719
  );
12381
12720
  if (match) return match;
12721
+ } else {
12722
+ const agentId = this.sessionAgents.get(this.slotKey(state, chainId, asset));
12723
+ const made = agentId && agents.find((agent) => agent.agentId === agentId && this.agentFits(agent, chainId, asset));
12724
+ if (made) return made;
12382
12725
  }
12383
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
12384
- if (named) return named;
12385
12726
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
12386
12727
  return void 0;
12387
12728
  }
@@ -12615,7 +12956,12 @@ var YieldseekerAgent = class {
12615
12956
  this.assertAgent(agent);
12616
12957
  return this.contextForAgent(state, chainId, user, agent, asset);
12617
12958
  }
12618
- /** Create the slot's agent. Only reached when no stored or named agent matched. */
12959
+ /**
12960
+ * Create the slot's agent, named "owney". Only reached when the slot has no
12961
+ * account record and no agent this session made; the created agent is
12962
+ * remembered for the session (sessionAgents) so reads select it before its
12963
+ * record exists.
12964
+ */
12619
12965
  async createAgent(state, chainId, user, agents, asset) {
12620
12966
  const generation = this.readGeneration;
12621
12967
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
@@ -12660,6 +13006,9 @@ var YieldseekerAgent = class {
12660
13006
  agents: [...agents, agent]
12661
13007
  }
12662
13008
  });
13009
+ if (typeof agent.agentId === "string") {
13010
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
13011
+ }
12663
13012
  }
12664
13013
  return agent;
12665
13014
  }
@@ -12676,6 +13025,10 @@ var YieldseekerAgent = class {
12676
13025
  const accounts = await this.agentAccounts(state, chainId);
12677
13026
  this.assertSession(generation, chainId, asset);
12678
13027
  const verified = this.slotAccounts(accounts, chainId, asset).some((account) => account.status === "verified");
13028
+ const adopt = (agent) => {
13029
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
13030
+ return agent;
13031
+ };
12679
13032
  for (let attempt = 0; attempt < 2; attempt += 1) {
12680
13033
  if (attempt > 0) {
12681
13034
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_CREATE_CONFLICT_RETRY_MS));
@@ -12685,12 +13038,12 @@ var YieldseekerAgent = class {
12685
13038
  this.assertSession(generation, chainId, asset);
12686
13039
  if (!verified && agentId) {
12687
13040
  const agent = agents.find((candidate) => candidate.agentId === agentId && this.agentFits(candidate, chainId, asset));
12688
- if (agent) return agent;
13041
+ if (agent) return adopt(agent);
12689
13042
  continue;
12690
13043
  }
12691
13044
  try {
12692
13045
  const agent = await this.chooseAgent(state, chainId, user, agents, accounts, asset);
12693
- if (agent) return agent;
13046
+ if (agent) return adopt(agent);
12694
13047
  } catch (error) {
12695
13048
  if (!this.isAgentMissing(error) || attempt > 0) throw error;
12696
13049
  }
@@ -12810,7 +13163,7 @@ var YieldseekerAgent = class {
12810
13163
  this.portfolioVersions.set(contextKey, version);
12811
13164
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12812
13165
  this.snapshotFailures.delete(contextKey);
12813
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
13166
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12814
13167
  for (const kind of kinds) {
12815
13168
  const key2 = `${kind}:${contextKey}`;
12816
13169
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -13019,6 +13372,9 @@ var YieldseekerAgent = class {
13019
13372
  if (this.recentDeployments.size > 32)
13020
13373
  this.recentDeployments.delete(this.recentDeployments.keys().next().value);
13021
13374
  }
13375
+ setAccountRefusedListener(listener) {
13376
+ this.accountRefusedListener = listener;
13377
+ }
13022
13378
  setFundingLedgerAccess(access) {
13023
13379
  this.ledgerAccess = access;
13024
13380
  this.ledgerReads.clear();
@@ -13437,6 +13793,24 @@ var YieldseekerAgent = class {
13437
13793
  return isWalletRejection(error) ? error : this.mapApiError(error);
13438
13794
  }
13439
13795
  mapApiError(error) {
13796
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") return error;
13797
+ if (error instanceof YieldseekerApiError && error.isAccountNotOwney) {
13798
+ try {
13799
+ this.accountRefusedListener?.();
13800
+ } catch {
13801
+ }
13802
+ return new OwneyError(
13803
+ "AGENT_ACCOUNT_NOT_OWNEY",
13804
+ "This wallet's Yieldseeker account was not created through Owney.",
13805
+ {
13806
+ rpcSource: "agent-api",
13807
+ statusCode: 403,
13808
+ providerCode: "YIELDSEEKER_ACCOUNT_NOT_OWNEY",
13809
+ permanent: true
13810
+ },
13811
+ this.id
13812
+ );
13813
+ }
13440
13814
  if (!(error instanceof YieldseekerApiError)) {
13441
13815
  return new OwneyError(
13442
13816
  "AGENT_API_ERROR",
@@ -13600,9 +13974,6 @@ var YieldseekerAgent = class {
13600
13974
  throw this.invalidResponse("agent");
13601
13975
  }
13602
13976
  }
13603
- isOwneyAgent(agent) {
13604
- return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
13605
- }
13606
13977
  assetForAgent(agent) {
13607
13978
  for (const asset of ["USDC", "WETH"]) {
13608
13979
  if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
@@ -16682,6 +17053,47 @@ function withWalletConnectSwitch(provider) {
16682
17053
  });
16683
17054
  }
16684
17055
 
17056
+ // src/lib/wallet-prompts.ts
17057
+ var PROMPT_METHODS = /* @__PURE__ */ new Set([
17058
+ "personal_sign",
17059
+ "eth_sign",
17060
+ "eth_signTypedData",
17061
+ "eth_signTypedData_v1",
17062
+ "eth_signTypedData_v3",
17063
+ "eth_signTypedData_v4",
17064
+ "eth_signTransaction",
17065
+ "eth_sendTransaction",
17066
+ "wallet_sendCalls"
17067
+ ]);
17068
+ var WALLET_PROMPT_HOLD_MS = 12e4;
17069
+ var WRAPPED = /* @__PURE__ */ Symbol.for("owney.oneWalletPrompt");
17070
+ function withOneWalletPrompt(provider) {
17071
+ const target = provider;
17072
+ if (target[WRAPPED] || typeof target.request !== "function") return provider;
17073
+ let tail = Promise.resolve();
17074
+ const request2 = (args) => {
17075
+ if (!PROMPT_METHODS.has(args?.method)) return target.request(args);
17076
+ const turn = tail.then(() => target.request(args));
17077
+ tail = new Promise((release) => {
17078
+ const timer = setTimeout(release, WALLET_PROMPT_HOLD_MS);
17079
+ const done = () => {
17080
+ clearTimeout(timer);
17081
+ release();
17082
+ };
17083
+ turn.then(done, done);
17084
+ });
17085
+ return turn;
17086
+ };
17087
+ return new Proxy(target, {
17088
+ get(obj, prop) {
17089
+ if (prop === WRAPPED) return true;
17090
+ if (prop === "request") return request2;
17091
+ const value = Reflect.get(obj, prop, obj);
17092
+ return typeof value === "function" ? value.bind(obj) : value;
17093
+ }
17094
+ });
17095
+ }
17096
+
16685
17097
  // src/lib/sponsored-calls-deposit.ts
16686
17098
  var import_viem24 = require("viem");
16687
17099
  init_errors();
@@ -16953,6 +17365,7 @@ var OwneySDK = class {
16953
17365
  * withdraw, but they are excluded from new deposits / activations.
16954
17366
  */
16955
17367
  disabledAgents = /* @__PURE__ */ new Set();
17368
+ accountRefusedListeners = /* @__PURE__ */ new Set();
16956
17369
  /**
16957
17370
  * Agents whose sign-in the user cancelled this session (the wallet rejected
16958
17371
  * the prompt), keyed by chain. Until the app ends the session they are read
@@ -17175,6 +17588,32 @@ var OwneySDK = class {
17175
17588
  } catch {
17176
17589
  }
17177
17590
  }
17591
+ /**
17592
+ * Listens for an agent refusing the connected wallet because its provider
17593
+ * account was not created through Owney (`AGENT_ACCOUNT_NOT_OWNEY`). Fires
17594
+ * each time an agent maps such a refusal. Returns the unsubscribe function.
17595
+ */
17596
+ onAccountRefused(listener) {
17597
+ this.accountRefusedListeners.add(listener);
17598
+ return () => {
17599
+ this.accountRefusedListeners.delete(listener);
17600
+ };
17601
+ }
17602
+ /** Wires the optional hooks the SDK offers an agent. */
17603
+ attachAgentHooks(agent) {
17604
+ try {
17605
+ agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
17606
+ } catch {
17607
+ }
17608
+ agent.setAccountRefusedListener?.(() => {
17609
+ for (const listener of [...this.accountRefusedListeners]) {
17610
+ try {
17611
+ listener(agent.id);
17612
+ } catch {
17613
+ }
17614
+ }
17615
+ });
17616
+ }
17178
17617
  /**
17179
17618
  * Funding-ledger read access handed to agents for earnings holds. Reads only
17180
17619
  * for the connected owner; null otherwise and on any failure.
@@ -17258,7 +17697,7 @@ var OwneySDK = class {
17258
17697
  if (revision !== this.connectionRevision)
17259
17698
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
17260
17699
  this.state = {
17261
- provider: withWalletConnectSwitch(provider),
17700
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
17262
17701
  walletAddress,
17263
17702
  chainId: null
17264
17703
  };
@@ -17626,10 +18065,7 @@ var OwneySDK = class {
17626
18065
  if (!configured) continue;
17627
18066
  const agent = this.createAgent(agent_type, key2);
17628
18067
  if (!agent) continue;
17629
- try {
17630
- agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
17631
- } catch {
17632
- }
18068
+ this.attachAgentHooks(agent);
17633
18069
  this.agents.set(agent_type, agent);
17634
18070
  if (is_enabled === false) {
17635
18071
  this.disabledAgents.add(agent_type);
@@ -18681,6 +19117,11 @@ var OwneySDK = class {
18681
19117
  * deposit's ledger operation when there is one. In the background: never
18682
19118
  * throws and never delays the deposit. A missed notice only leaves the
18683
19119
  * provider on its own schedule.
19120
+ *
19121
+ * An agent that reports its provider calls (`onNotice`) gets one
19122
+ * `provider.deposit_notified` event per call and a final
19123
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
19124
+ * Otherwise the outcome is the one `provider.deposit_notified`.
18684
19125
  */
18685
19126
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18686
19127
  try {
@@ -18693,12 +19134,18 @@ var OwneySDK = class {
18693
19134
  this.announcedDeposits.add(key2);
18694
19135
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18695
19136
  const legKey = `agent:${evidence.agentId}`;
18696
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
19137
+ const record2 = (type, notice) => {
18697
19138
  try {
18698
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
19139
+ ledgerOp?.event?.(type, { legKey, ...notice });
18699
19140
  } catch {
18700
19141
  }
18701
- });
19142
+ };
19143
+ let reported = false;
19144
+ const onNotice = (notice) => {
19145
+ reported = true;
19146
+ record2("provider.deposit_notified", notice);
19147
+ };
19148
+ void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence, onNotice)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => record2(reported ? "provider.deposit_allocation" : "provider.deposit_notified", notice));
18702
19149
  } catch {
18703
19150
  }
18704
19151
  }
@@ -20188,6 +20635,7 @@ var OwneySDK = class {
20188
20635
  let record2;
20189
20636
  let ledgerOp;
20190
20637
  let hadDurableRecord = false;
20638
+ let nothingSent = false;
20191
20639
  const startedAt = Date.now();
20192
20640
  let confirmationDeadline = Infinity;
20193
20641
  const assertCurrent = () => {
@@ -20348,7 +20796,10 @@ var OwneySDK = class {
20348
20796
  } catch (error) {
20349
20797
  const details = error instanceof OwneyError ? error.details : void 0;
20350
20798
  const moved = [...evidence.values()].some((value) => value.transfer !== "failed" && (value.delivery === "confirmed" || value.transfer === "unknown" || value.txHash || value.userOpHash || value.callsId || value.withdrawalRequest?.attempted));
20351
- if (!moved && !details?.partialResults && !details?.pendingSubmissions) throw error;
20799
+ if (!moved && !details?.partialResults && !details?.pendingSubmissions) {
20800
+ nothingSent = details?.rejectedBeforeSubmission === true && evidence.size === 0;
20801
+ throw error;
20802
+ }
20352
20803
  throw new OwneyError(
20353
20804
  "WITHDRAW_SWAP_INCOMPLETE",
20354
20805
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -20516,7 +20967,11 @@ var OwneySDK = class {
20516
20967
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
20517
20968
  record2.status = outcome === "refunded" ? "refunded" : outcome === "refund-pending" ? "refund-pending" : outcome === "partially-filled" ? "partially-filled" : record2.recovery?.phase === "submitted" || details?.settlementUnconfirmed ? "unknown" : record2.recovery?.phase === "ready" ? "ready" : "withdrawal-incomplete";
20518
20969
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
20519
- saveWithdrawSwap(record2);
20970
+ if (nothingSent && record2.recovery?.phase === "withdrawing" && !record2.recovery.results) {
20971
+ record2.status = "not-swapped";
20972
+ saveWithdrawSwap(record2);
20973
+ clearWithdrawSwap(record2.orderHash);
20974
+ } else saveWithdrawSwap(record2);
20520
20975
  }
20521
20976
  this.ledgerFailed(ledgerOp, error);
20522
20977
  throw error;