@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.js CHANGED
@@ -1011,7 +1011,7 @@ var SnapshotHistory = class {
1011
1011
  };
1012
1012
 
1013
1013
  // src/lib/funding-ledger.ts
1014
- var SDK_VERSION = "0.7.32-beta.7";
1014
+ var SDK_VERSION = "0.7.32-beta.9";
1015
1015
  var SCOPE2 = "funding-ledger";
1016
1016
  var REQUEST_TIMEOUT_MS2 = 5e3;
1017
1017
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -4980,9 +4980,12 @@ var ZyfaiAgent = class _ZyfaiAgent {
4980
4980
  * Pool choices are merged into protocol/chain records and each active asset
4981
4981
  * is kept at aggressive unless the draft includes a yieldmaxxing-only pool.
4982
4982
  * The whole operation must succeed before the caller starts moving funds.
4983
+ * A draft that would leave an asset on a chain with no Zyfai pool throws
4984
+ * POOL_SELECTION_REQUIRED before anything is written.
4983
4985
  */
4984
4986
  async setPoolSelection(selection) {
4985
4987
  try {
4988
+ await this.assertEveryTargetKeepsAPool(selection);
4986
4989
  await this.sdk.ensureFirstDepositSetup("aggressive");
4987
4990
  const byPair = /* @__PURE__ */ new Map();
4988
4991
  for (const entry of selection.selections) {
@@ -5039,6 +5042,56 @@ var ZyfaiAgent = class _ZyfaiAgent {
5039
5042
  throw error;
5040
5043
  }
5041
5044
  }
5045
+ /**
5046
+ * Every agent keeps at least one pool (2026-11-11). Throws
5047
+ * POOL_SELECTION_REQUIRED when the draft picks no pool for an asset on a
5048
+ * chain where it shows some, and no other protocol on that chain keeps one.
5049
+ * Zyfai saves per protocol and chain, so a protocol this draft does not
5050
+ * touch still counts: its saved picks for the asset, or autoselect over its
5051
+ * pools for the asset. Those are read only for a target the draft leaves
5052
+ * empty, and a lookup that fails proves nothing.
5053
+ */
5054
+ async assertEveryTargetKeepsAPool(selection) {
5055
+ const targets = /* @__PURE__ */ new Map();
5056
+ for (const entry of selection.selections) {
5057
+ const key2 = `${entry.asset}:${entry.chainId}`;
5058
+ const target = targets.get(key2) ?? { asset: entry.asset, chainId: entry.chainId, protocols: /* @__PURE__ */ new Set(), shown: false, picked: false };
5059
+ target.protocols.add(entry.protocolId);
5060
+ if (entry.availablePools.length > 0) target.shown = true;
5061
+ if (entry.pools.length > 0) target.picked = true;
5062
+ targets.set(key2, target);
5063
+ }
5064
+ for (const { asset, chainId, protocols, shown, picked } of targets.values()) {
5065
+ if (picked || !shown) continue;
5066
+ if (await this.otherProtocolKeepsAPool(asset, chainId, protocols)) continue;
5067
+ throw new OwneyError(
5068
+ "POOL_SELECTION_REQUIRED",
5069
+ `Every agent needs at least one pool. This save would leave Zyfai with no ${asset} pool on chain ${chainId}. Nothing was saved.`,
5070
+ { asset, chainId, reason: "NO_POOL_LEFT" },
5071
+ this.id
5072
+ );
5073
+ }
5074
+ }
5075
+ /** Whether a protocol outside `excluded` keeps a pool for `asset` on `chainId`. */
5076
+ async otherProtocolKeepsAPool(asset, chainId, excluded) {
5077
+ let universe = [];
5078
+ try {
5079
+ ({ protocols: universe } = await this.sdk.getAvailableProtocols(chainId));
5080
+ } catch {
5081
+ return false;
5082
+ }
5083
+ for (const protocol of universe) {
5084
+ if (excluded.has(protocol.id)) continue;
5085
+ try {
5086
+ const names = mapAvailablePools(await this.sdk.getAvailablePools(protocol.id, "yieldmaxxing")).filter((pool) => pool.chainId === chainId && pool.token.toUpperCase() === asset).map((pool) => pool.name);
5087
+ if (names.length === 0) continue;
5088
+ const current = await this.sdk.getSelectedPools(protocol.id, chainId);
5089
+ if (current.autoselect || (current.pools ?? []).some((name) => names.includes(name))) return true;
5090
+ } catch {
5091
+ }
5092
+ }
5093
+ return false;
5094
+ }
5042
5095
  /**
5043
5096
  * Read back what `setPoolSelection` wrote (ROUT-650). Zyfai keeps the saved
5044
5097
  * pools per protocol/chain and the strategy per asset; both are read for the
@@ -7249,7 +7302,15 @@ var YieldseekerApiError = class extends Error {
7249
7302
  providerCode;
7250
7303
  responseFields;
7251
7304
  routing;
7305
+ /**
7306
+ * Owney's proxy refuses a user-level call for a wallet whose Yieldseeker
7307
+ * account was not created through Owney. Permanent: not a sign-in problem.
7308
+ */
7309
+ get isAccountNotOwney() {
7310
+ return this.status === 403 && this.routing?.code === "YIELDSEEKER_ACCOUNT_NOT_OWNEY";
7311
+ }
7252
7312
  get isAuthenticationError() {
7313
+ if (this.isAccountNotOwney) return false;
7253
7314
  return this.status === 401 || this.status === 403;
7254
7315
  }
7255
7316
  };
@@ -7439,6 +7500,27 @@ function position(value, asset, baseAssetDecimals) {
7439
7500
  liquidity: Number(option.withdrawableDepositsUsd)
7440
7501
  };
7441
7502
  }
7503
+ function userFunds(context, assetAddress) {
7504
+ const live = context.liveWallet;
7505
+ if (!live) {
7506
+ return { idle: assetAddressValue(context.snapshot.tokenBalances, assetAddress), positions: context.positions };
7507
+ }
7508
+ const idle = live.idleRaw > live.feesOwedRaw ? live.idleRaw - live.feesOwedRaw : 0n;
7509
+ const pending = /^\d+$/.test(context.snapshot.pendingFeesBase ?? "") ? BigInt(context.snapshot.pendingFeesBase) : 0n;
7510
+ let fees = (live.feesOwedRaw > live.idleRaw ? live.feesOwedRaw - live.idleRaw : 0n) + pending;
7511
+ const amounts = context.positions.map((entry) => balanceRaw(entry.assetsBase, "vault positions"));
7512
+ const order = amounts.map((_, index) => index).sort((a, b) => amounts[b] > amounts[a] ? 1 : amounts[b] < amounts[a] ? -1 : 0);
7513
+ for (const index of order) {
7514
+ if (fees === 0n) break;
7515
+ const taken = amounts[index] < fees ? amounts[index] : fees;
7516
+ amounts[index] = amounts[index] - taken;
7517
+ fees -= taken;
7518
+ }
7519
+ return {
7520
+ idle: idle.toString(),
7521
+ positions: context.positions.map((entry, index) => ({ ...entry, assetsBase: amounts[index].toString() }))
7522
+ };
7523
+ }
7442
7524
  function mapYieldseekerBalances(contexts) {
7443
7525
  const tokens = [];
7444
7526
  const assetBalances = [];
@@ -7452,18 +7534,15 @@ function mapYieldseekerBalances(contexts) {
7452
7534
  asset: context.asset,
7453
7535
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
7454
7536
  });
7455
- const idle = assetAddressValue(
7456
- context.snapshot.tokenBalances,
7457
- metadata.address
7458
- );
7537
+ const funds = userFunds(context, metadata.address);
7459
7538
  tokens.push({
7460
7539
  chain: "BASE",
7461
7540
  chainId: 8453,
7462
7541
  asset: context.asset,
7463
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
7542
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
7464
7543
  });
7465
7544
  positions.push(
7466
- ...context.positions.map(
7545
+ ...funds.positions.map(
7467
7546
  (entry) => position(
7468
7547
  entry,
7469
7548
  context.asset,
@@ -8783,10 +8862,8 @@ var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
8783
8862
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
8784
8863
  var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
8785
8864
  var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
8786
- var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
8787
8865
  var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
8788
8866
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
8789
- var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
8790
8867
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
8791
8868
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
8792
8869
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
@@ -8840,6 +8917,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
8840
8917
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
8841
8918
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
8842
8919
  var YIELDSEEKER_LEDGER_GRACE_MS = 6e4;
8920
+ var DEPOSIT_NOTICE_ATTEMPTS = 3;
8921
+ var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
8922
+ var DEPOSIT_NOTICE_RETRY_MS = 15e3;
8923
+ var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
8924
+ var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
8925
+ var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
8926
+ var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
8843
8927
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
8844
8928
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
8845
8929
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -8909,6 +8993,18 @@ function query(params) {
8909
8993
  const encoded = search.toString();
8910
8994
  return encoded ? `?${encoded}` : "";
8911
8995
  }
8996
+ var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8997
+ function parseRawAmount(raw2) {
8998
+ if (!raw2 || !/^\d+$/.test(raw2)) return null;
8999
+ const amount = BigInt(raw2);
9000
+ return amount > 0n ? amount : null;
9001
+ }
9002
+ function reportNotice(onNotice, notice) {
9003
+ try {
9004
+ onNotice?.(notice);
9005
+ } catch {
9006
+ }
9007
+ }
8912
9008
  var YieldseekerAgent = class {
8913
9009
  id = "yieldseeker";
8914
9010
  balanceComposition = "tokens-plus-positions";
@@ -8943,7 +9039,13 @@ var YieldseekerAgent = class {
8943
9039
  agentContexts = /* @__PURE__ */ new Map();
8944
9040
  // Every resolved agent wallet, keyed by contextKey (slot + agentId).
8945
9041
  walletContexts = /* @__PURE__ */ new Map();
9042
+ // In-flight stored-account reads keyed by userKey, shared by concurrent
9043
+ // callers; a good read is kept for the session, a failed one is dropped.
8946
9044
  agentAccountReads = /* @__PURE__ */ new Map();
9045
+ // The agentId this session created, or adopted after a create conflict, per
9046
+ // slotKey. The session's account read can predate its record, so a slot with
9047
+ // no verified or superseded record still selects this agent until disconnect.
9048
+ sessionAgents = /* @__PURE__ */ new Map();
8947
9049
  reportedAccounts = /* @__PURE__ */ new Set();
8948
9050
  // Slots whose verified agent is missing even from a re-read list (and could
8949
9051
  // not be reopened), with the error the lookup failed with, until the list
@@ -9004,6 +9106,7 @@ var YieldseekerAgent = class {
9004
9106
  // Refresh when ready and the earnings hold (spec B2). Without ledger access,
9005
9107
  // or while the ledger read is null, settlement and earnings are as before.
9006
9108
  ledgerAccess;
9109
+ accountRefusedListener;
9007
9110
  ledgerReads = /* @__PURE__ */ new Map();
9008
9111
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9009
9112
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -9088,8 +9191,9 @@ var YieldseekerAgent = class {
9088
9191
  * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9089
9192
  * continues only when it is now open with the same address. Only the
9090
9193
  * verified record's agent is reopened: any other closed agent (a
9091
- * superseded-wallet match, or a named agent with no verified record, also
9092
- * when the accounts could not be read) refuses without a request;
9194
+ * superseded-wallet match, or the agent this session created or adopted
9195
+ * before its record exists, also when the accounts could not be read)
9196
+ * refuses without a request;
9093
9197
  * - anything else refuses with nothing sent, before any progress event,
9094
9198
  * signature or callback. Every refusal carries `notSubmitted` and
9095
9199
  * `safeToFallback: false`, so no paid fallback runs.
@@ -9126,6 +9230,7 @@ var YieldseekerAgent = class {
9126
9230
  fresh2 = answer.agentWallet;
9127
9231
  } catch (error) {
9128
9232
  this.assertSession(generation, chainId, asset);
9233
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9129
9234
  throw new OwneyError(
9130
9235
  "YIELDSEEKER_WALLET_UNVERIFIED",
9131
9236
  "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
@@ -9214,6 +9319,7 @@ var YieldseekerAgent = class {
9214
9319
  break;
9215
9320
  } catch (error) {
9216
9321
  this.assertSession(generation, chainId, asset);
9322
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9217
9323
  if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
9218
9324
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
9219
9325
  this.assertSession(generation, chainId, asset);
@@ -9499,6 +9605,7 @@ var YieldseekerAgent = class {
9499
9605
  this.agentContexts.clear();
9500
9606
  this.walletContexts.clear();
9501
9607
  this.agentAccountReads.clear();
9608
+ this.sessionAgents.clear();
9502
9609
  this.reportedAccounts.clear();
9503
9610
  this.pendingSlotInvalidations.clear();
9504
9611
  this.knownContextKeys.clear();
@@ -9746,7 +9853,8 @@ var YieldseekerAgent = class {
9746
9853
  }
9747
9854
  let sponsor = false;
9748
9855
  if (gasMode !== "paid") {
9749
- const status = await this.getWalletStatus(state, chainId, asset, true).catch(() => {
9856
+ const status = await this.getWalletStatus(state, chainId, asset, true).catch((error) => {
9857
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9750
9858
  if (gasMode === "sponsored")
9751
9859
  throw new OwneyError(
9752
9860
  "SPONSOR_REQUEST_FAILED",
@@ -9846,8 +9954,11 @@ var YieldseekerAgent = class {
9846
9954
  let positionsStatus = "empty";
9847
9955
  const validatePositions = (values) => this.validateWithdrawalPositions(values, chainId, asset);
9848
9956
  validatePositions(positions);
9849
- const zeroValuePositions = /* @__PURE__ */ new WeakSet();
9850
- const hasPositions = (values) => values.some((position2) => !zeroValuePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n));
9957
+ const negligibleRaw = 10n ** BigInt(Math.max(metadata.decimals - 6, 0));
9958
+ const negligiblePositions = /* @__PURE__ */ new WeakSet();
9959
+ const negligibleVaults = /* @__PURE__ */ new Set();
9960
+ const hasPositions = (values) => values.some((position2) => !negligiblePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n));
9961
+ const provenNegligible = (position2) => negligibleVaults.has(position2.vaultOption.address.toLowerCase());
9851
9962
  const knownPositions = /* @__PURE__ */ new Map();
9852
9963
  const rememberPositions = (values) => {
9853
9964
  for (const position2 of values) knownPositions.set(position2.vaultOption.address.toLowerCase(), position2);
@@ -9877,6 +9988,7 @@ var YieldseekerAgent = class {
9877
9988
  if (!active || value === void 0) return null;
9878
9989
  this.assertSession(generation, chainId, asset);
9879
9990
  verified.withdrawableAssetsRaw = value.toString();
9991
+ if (value <= negligibleRaw && provenNegligible(position2)) negligiblePositions.add(verified);
9880
9992
  verifiedPositions.push(verified);
9881
9993
  return verified;
9882
9994
  }
@@ -9907,10 +10019,11 @@ var YieldseekerAgent = class {
9907
10019
  const redemptionValue = valuations[1];
9908
10020
  if (redemptionValue !== null && redemptionValue > 0n)
9909
10021
  verified.withdrawableAssetsRaw = redemptionValue.toString();
10022
+ if (valuations.every((value) => value !== null && value <= negligibleRaw) && provenNegligible(position2)) negligiblePositions.add(verified);
9910
10023
  return verified;
9911
10024
  }
9912
10025
  if (blockNumber === void 0 || valuations.some((value) => value !== 0n)) return null;
9913
- zeroValuePositions.add(verified);
10026
+ negligiblePositions.add(verified);
9914
10027
  }
9915
10028
  verifiedPositions.push(verified);
9916
10029
  return verified;
@@ -10013,6 +10126,40 @@ var YieldseekerAgent = class {
10013
10126
  let grossUnwound = 0n;
10014
10127
  let confirmedUnwinds = 0n;
10015
10128
  let latestUnwindBlock;
10129
+ let payFromCurrentFunds = false;
10130
+ const vaultShares = async (position2) => {
10131
+ try {
10132
+ const [underlying, shares] = await this.readVaultShares([position2.vaultOption], agentWallet);
10133
+ this.assertSession(generation, chainId, asset);
10134
+ 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;
10135
+ return shares.result;
10136
+ } catch (error) {
10137
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10138
+ return void 0;
10139
+ }
10140
+ };
10141
+ const releasedOnChain = async (position2, refused) => {
10142
+ const shares = await vaultShares(position2);
10143
+ if (shares === 0n) return true;
10144
+ if (shares === void 0 || !refused) return false;
10145
+ let negligible;
10146
+ try {
10147
+ if (nativeYieldseekerProtocol(position2.vaultOption)) {
10148
+ const value = await readNativeYieldseekerAssets(this.getReceiptClient(), position2.vaultOption, agentWallet, shares);
10149
+ negligible = value !== void 0 && value <= negligibleRaw;
10150
+ } else {
10151
+ const address = getAddress6(position2.vaultOption.address);
10152
+ const values = await Promise.all(["convertToAssets", "previewRedeem"].map((functionName) => this.getReceiptClient().readContract({ address, abi: erc4626Abi3, functionName, args: [shares] }).catch(() => void 0)));
10153
+ negligible = values.every((value) => typeof value === "bigint" && value >= 0n && value <= negligibleRaw);
10154
+ }
10155
+ } catch (error) {
10156
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10157
+ return false;
10158
+ }
10159
+ this.assertSession(generation, chainId, asset);
10160
+ if (negligible) negligibleVaults.add(position2.vaultOption.address.toLowerCase());
10161
+ return negligible;
10162
+ };
10016
10163
  const unwind = async (position2, assetsRaw) => {
10017
10164
  this.assertSession(generation, chainId, asset);
10018
10165
  assertOperation?.();
@@ -10037,6 +10184,13 @@ var YieldseekerAgent = class {
10037
10184
  }
10038
10185
  } catch (error) {
10039
10186
  this.invalidateFundingRead(state, chainId, asset);
10187
+ const refused = error instanceof OwneyError && error.details?.statusCode === 400;
10188
+ if (await releasedOnChain(position2, refused)) {
10189
+ payFromCurrentFunds = true;
10190
+ confirmedMovement = true;
10191
+ grossUnwound += assetsRaw;
10192
+ return;
10193
+ }
10040
10194
  throw new OwneyError(
10041
10195
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10042
10196
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10061,7 +10215,7 @@ var YieldseekerAgent = class {
10061
10215
  let unwound = false;
10062
10216
  for (const position2 of positions) {
10063
10217
  const available = BigInt(position2.withdrawableAssetsRaw);
10064
- if (available <= 0n) continue;
10218
+ if (available <= 0n || negligiblePositions.has(position2)) continue;
10065
10219
  await unwind(position2, available);
10066
10220
  unwound = true;
10067
10221
  }
@@ -10101,7 +10255,7 @@ var YieldseekerAgent = class {
10101
10255
  remaining: remaining.toString()
10102
10256
  });
10103
10257
  }
10104
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10258
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10105
10259
  const availableForOwner = ownerFunds.available;
10106
10260
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10107
10261
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -10254,7 +10408,7 @@ var YieldseekerAgent = class {
10254
10408
  reason: "YIELDSEEKER_MAX_INCOMPLETE",
10255
10409
  asset,
10256
10410
  positionsStatus,
10257
- remainingPositions: positionsStatus === "remaining" ? positions.filter((position2) => !zeroValuePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n)).map((position2) => ({
10411
+ remainingPositions: positionsStatus === "remaining" ? positions.filter((position2) => !negligiblePositions.has(position2) && (BigInt(position2.assetsRaw) > 0n || BigInt(position2.withdrawableAssetsRaw) > 0n)).map((position2) => ({
10258
10412
  vaultAddress: position2.vaultOption.address,
10259
10413
  sharesRaw: position2.assetsRaw,
10260
10414
  withdrawableAmountRaw: position2.withdrawableAssetsRaw
@@ -10688,7 +10842,8 @@ var YieldseekerAgent = class {
10688
10842
  if (asset !== void 0) this.assertAsset(asset);
10689
10843
  const missingAssets = /* @__PURE__ */ new Set();
10690
10844
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
10691
- const balance = mapYieldseekerBalances(contexts);
10845
+ const liveWallets = await Promise.all(contexts.map((context) => this.readLiveWallet(state, chainId, context)));
10846
+ const balance = mapYieldseekerBalances(contexts.map((context, index) => liveWallets[index] === null ? context : { ...context, liveWallet: liveWallets[index] }));
10692
10847
  for (const [index, context] of contexts.entries()) {
10693
10848
  const read2 = balance.readMetadata[index];
10694
10849
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -10795,30 +10950,197 @@ var YieldseekerAgent = class {
10795
10950
  }
10796
10951
  /**
10797
10952
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10798
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
10799
- * anything moves (the funding minimum, a deployed agent, no manual
10800
- * withdrawal in the last hour). Uses the agent this session already knows
10801
- * for the asset and the saved sign-in only: never prompts, never retries,
10802
- * never throws.
10953
+ * it now instead of on its next 30-minute check, and confirms it did.
10954
+ * Yieldseeker decides whether anything moves (the funding minimum, a
10955
+ * deployed agent, no manual withdrawal in the last hour), and its answer
10956
+ * (`{}`) does not say, so a minute after each notice the agent reads its
10957
+ * wallet: the deposit has gone into a vault when less than its amount is
10958
+ * left idle. While it has not, Yieldseeker is told again, up to
10959
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
10960
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
10961
+ * told once, since nothing can move yet. Uses the agent this session already
10962
+ * knows for the asset and the saved sign-in only: never prompts, never
10963
+ * throws. Each call is reported through `onNotice`.
10803
10964
  */
10804
- async depositConfirmed(state, chainId, evidence) {
10965
+ async depositConfirmed(state, chainId, evidence, onNotice) {
10966
+ let attempts = 0;
10805
10967
  try {
10806
10968
  const asset = String(evidence.token).toUpperCase();
10807
10969
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10808
10970
  return { notified: false, reason: "UNSUPPORTED" };
10809
- const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10971
+ const slotAsset = asset;
10972
+ const context = this.agentContexts.get(this.slotKey(state, chainId, slotAsset));
10810
10973
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10811
10974
  return { notified: false, reason: "NO_AGENT" };
10812
10975
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
10976
+ const generation = this.readGeneration;
10977
+ const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
10978
+ const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
10979
+ let notified = false;
10980
+ let reason = "NOT_ALLOCATED";
10981
+ while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
10982
+ if (this.readGeneration !== generation || !this.auth.peekToken(state, chainId))
10983
+ return notified ? { notified: true, attempts, reason: "SESSION_ENDED" } : { notified: false, attempts, reason: "SESSION_ENDED" };
10984
+ attempts += 1;
10985
+ const sent = await this.sendDepositNotice(state, chainId, context);
10986
+ reportNotice(onNotice, sent.ok ? { notified: true, attempt: attempts } : { notified: false, reason: sent.reason, attempt: attempts });
10987
+ if (!sent.ok) {
10988
+ if (!sent.retryAfterMs || attempts >= DEPOSIT_NOTICE_ATTEMPTS)
10989
+ return notified ? { notified: true, attempts, allocated: false, reason: sent.reason } : { notified: false, attempts, reason: sent.reason };
10990
+ await wait2(sent.retryAfterMs);
10991
+ continue;
10992
+ }
10993
+ notified = true;
10994
+ if (amount === null) return { notified: true, attempts };
10995
+ await wait2(DEPOSIT_ALLOCATION_CHECK_MS);
10996
+ if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
10997
+ const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
10998
+ if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
10999
+ if (cooldownEnds !== null)
11000
+ return {
11001
+ notified: true,
11002
+ attempts,
11003
+ allocated: false,
11004
+ reason: "RECENT_WITHDRAWAL",
11005
+ allocatesAfter: new Date(cooldownEnds).toISOString()
11006
+ };
11007
+ reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11008
+ }
11009
+ return { notified: true, attempts, allocated: false, reason };
11010
+ } catch (error) {
11011
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR", ...attempts ? { attempts } : {} };
11012
+ }
11013
+ }
11014
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
11015
+ async sendDepositNotice(state, chainId, context) {
11016
+ try {
10813
11017
  await this.walletRequest(
10814
11018
  state,
10815
11019
  chainId,
10816
11020
  this.agentPath(context, "deposit-made"),
10817
11021
  { method: "POST", body: {}, promptless: true }
10818
11022
  );
10819
- return { notified: true };
11023
+ return { ok: true };
10820
11024
  } catch (error) {
10821
- return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
11025
+ if (!(error instanceof OwneyError)) return { ok: false, reason: "ERROR" };
11026
+ const details = error.details ?? {};
11027
+ const status = typeof details.statusCode === "number" ? details.statusCode : void 0;
11028
+ const transient = error.code === "AGENT_TIMEOUT" || error.code === "AGENT_API_ERROR" && (status === void 0 || status === 0 || status === 408 || status === 429 || status >= 500);
11029
+ const reason = status ? `HTTP_${status}` : error.code === "AGENT_API_ERROR" ? "NETWORK" : error.code;
11030
+ if (!transient) return { ok: false, reason };
11031
+ const named = Number(details.fields?.headers?.["Retry-After"]) * 1e3;
11032
+ return {
11033
+ ok: false,
11034
+ reason,
11035
+ retryAfterMs: Number.isFinite(named) && named > 0 ? Math.min(named, DEPOSIT_NOTICE_RETRY_MAX_MS) : DEPOSIT_NOTICE_RETRY_MS
11036
+ };
11037
+ }
11038
+ }
11039
+ /**
11040
+ * Tells Yieldseeker (`deposit-made`) after a pool save, so the agent runs
11041
+ * now and rebalances money already in a vault the list no longer allows.
11042
+ * Up to DEPOSIT_NOTICE_ATTEMPTS calls in all, waiting between them only
11043
+ * after a failure that may pass; stops when the session ends. Never throws.
11044
+ */
11045
+ async rebalanceAfterPoolSave(state, context, asset) {
11046
+ const generation = this.readGeneration;
11047
+ try {
11048
+ for (let attempt = 1; attempt <= DEPOSIT_NOTICE_ATTEMPTS; attempt += 1) {
11049
+ if (this.readGeneration !== generation) return;
11050
+ const sent = await this.sendDepositNotice(state, 8453, context);
11051
+ if (sent.ok) {
11052
+ debugLog("yieldseeker:pools", `${asset}: agent ${context.agent.agentId} told to rebalance`, { attempt });
11053
+ return;
11054
+ }
11055
+ debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { attempt, reason: sent.reason });
11056
+ if (!sent.retryAfterMs || attempt >= DEPOSIT_NOTICE_ATTEMPTS) return;
11057
+ await wait2(sent.retryAfterMs);
11058
+ }
11059
+ } catch (error) {
11060
+ debugLog("yieldseeker:pools", `${asset}: rebalance notice failed`, { error: String(error) });
11061
+ }
11062
+ }
11063
+ /**
11064
+ * When Yieldseeker may move funds again after this agent wallet's last
11065
+ * confirmed withdrawal, if that is still ahead; null when there was none in
11066
+ * the last hour or the ledger cannot say.
11067
+ */
11068
+ async withdrawalCooldownEnd(state, chainId, asset, context) {
11069
+ const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11070
+ const wallet = context.wallet.walletAddress.toLowerCase();
11071
+ let latest = 0;
11072
+ for (const row of rows ?? []) {
11073
+ if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
11074
+ for (const leg of row.legs) {
11075
+ if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
11076
+ const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
11077
+ if (Number.isFinite(at)) latest = Math.max(latest, at);
11078
+ }
11079
+ }
11080
+ const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11081
+ return latest > 0 && ends > Date.now() ? ends : null;
11082
+ }
11083
+ /**
11084
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
11085
+ * not collected from it, read at one block for a balance read. Cached
11086
+ * briefly per agent wallet and dropped by funding and allocation
11087
+ * invalidations. Null when any read fails or is slow: the snapshot's
11088
+ * amounts are used instead.
11089
+ */
11090
+ readLiveWallet(state, chainId, context) {
11091
+ const contextKey = this.contextKey(state, chainId, context);
11092
+ return this.cachedRead(`idle:${contextKey}`, YIELDSEEKER_LIVE_IDLE_CACHE_MS, () => withinBudget(
11093
+ this.readWalletFunds(chainId, context.asset, context.wallet.walletAddress),
11094
+ YIELDSEEKER_LIVE_IDLE_BUDGET_MS,
11095
+ null
11096
+ ));
11097
+ }
11098
+ async readWalletFunds(chainId, asset, walletAddress) {
11099
+ try {
11100
+ const client = this.getReceiptClient();
11101
+ const wallet = getAddress6(walletAddress);
11102
+ const read2 = (operation) => withPaidRpcDiagnostics(operation, chainId, "eth_call", this.id);
11103
+ const blockNumber = await read2(() => client.getBlockNumber());
11104
+ const feeTracker = await read2(() => client.readContract({
11105
+ address: wallet,
11106
+ abi: YIELDSEEKER_AGENT_WALLET_ABI,
11107
+ functionName: "feeTracker",
11108
+ blockNumber
11109
+ }));
11110
+ if (!isAddress4(feeTracker) || /^0x0{40}$/i.test(feeTracker)) return null;
11111
+ const [idle, owed] = await Promise.all([
11112
+ read2(() => client.readContract({
11113
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11114
+ abi: erc20Abi5,
11115
+ functionName: "balanceOf",
11116
+ args: [wallet],
11117
+ blockNumber
11118
+ })),
11119
+ read2(() => client.readContract({
11120
+ address: getAddress6(feeTracker),
11121
+ abi: YIELDSEEKER_FEE_TRACKER_ABI,
11122
+ functionName: "getFeesOwed",
11123
+ args: [wallet],
11124
+ blockNumber
11125
+ }))
11126
+ ]);
11127
+ return typeof idle === "bigint" && idle >= 0n && typeof owed === "bigint" && owed >= 0n ? { idleRaw: idle, feesOwedRaw: owed } : null;
11128
+ } catch {
11129
+ return null;
11130
+ }
11131
+ }
11132
+ /** The agent wallet's idle base asset; null when the read fails. */
11133
+ async readIdleBalance(chainId, asset, wallet) {
11134
+ try {
11135
+ const idle = await withPaidRpcDiagnostics(() => this.getReceiptClient().readContract({
11136
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11137
+ abi: erc20Abi5,
11138
+ functionName: "balanceOf",
11139
+ args: [getAddress6(wallet)]
11140
+ }), chainId, "eth_call", this.id);
11141
+ return typeof idle === "bigint" && idle >= 0n ? idle : null;
11142
+ } catch {
11143
+ return null;
10822
11144
  }
10823
11145
  }
10824
11146
  async getFundingWallet(state, chainId, asset) {
@@ -11021,13 +11343,11 @@ var YieldseekerAgent = class {
11021
11343
  *
11022
11344
  * - Only Base entries are ours. An asset with no picks whose entries showed
11023
11345
  * no vault is skipped and nothing is sent.
11346
+ * - None picked (vaults shown) for any asset: every agent keeps at least one
11347
+ * pool (2026-11-11), so the whole save throws POOL_SELECTION_REQUIRED
11348
+ * before anything is written, for any asset.
11024
11349
  * - Some vaults picked: the managed list names them. Saving it again
11025
11350
  * replaces it, so there is only ever one.
11026
- * - None picked (vaults shown): the managed list names no vault, and the
11027
- * rules must read back as an empty allow-list. Yieldseeker then keeps the
11028
- * agent's money out of every vault, as Zyfai does with an empty pool list,
11029
- * and the next Pools step reads "none". Only an agent that already exists
11030
- * is written: one is never created just to hold "none".
11031
11351
  * - Every vault picked: the managed list is deleted, and no allow-list may
11032
11352
  * remain, so vaults Yieldseeker adds later are allowed too.
11033
11353
  * - A free-text allow-list we saved before the managed list existed is
@@ -11060,21 +11380,27 @@ var YieldseekerAgent = class {
11060
11380
  group.shown.push(...entry.availablePools);
11061
11381
  byAsset.set(entry.asset, group);
11062
11382
  }
11383
+ for (const [asset, group] of byAsset) {
11384
+ if (uniqueAddresses(group.picked).length === 0 && uniqueAddresses(group.shown).length > 0) {
11385
+ throw new OwneyError(
11386
+ "POOL_SELECTION_REQUIRED",
11387
+ `Every agent needs at least one pool. This save would leave the Yieldseeker ${asset} agent with no vault on Base. Nothing was saved.`,
11388
+ { asset, chainId: 8453, reason: "NO_POOL_LEFT" },
11389
+ this.id
11390
+ );
11391
+ }
11392
+ }
11063
11393
  for (const [asset, group] of byAsset) {
11064
11394
  const picks = uniqueAddresses(group.picked);
11065
11395
  const shown = uniqueAddresses(group.shown);
11066
- if (picks.length === 0 && shown.length === 0) continue;
11396
+ if (picks.length === 0) continue;
11067
11397
  const picked = new Set(picks.map((address) => address.toLowerCase()));
11068
11398
  const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11069
11399
  await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11070
11400
  }
11071
11401
  }
11072
11402
  async savePoolPicks(state, asset, picks, everyVaultPicked) {
11073
- const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11074
- if (!context) {
11075
- debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11076
- return;
11077
- }
11403
+ const context = await this.ensureAgent(state, 8453, asset);
11078
11404
  const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11079
11405
  const managed = active.find(isManagedVaultList);
11080
11406
  const legacy = active.filter(isLegacyPoolSelectionMemory);
@@ -11096,6 +11422,7 @@ var YieldseekerAgent = class {
11096
11422
  });
11097
11423
  change.written = true;
11098
11424
  }
11425
+ } else if (managed?.content === content) {
11099
11426
  } else {
11100
11427
  const answer = await this.memoryRequest(state, context, "memories", {
11101
11428
  method: "POST",
@@ -11113,7 +11440,10 @@ var YieldseekerAgent = class {
11113
11440
  } catch {
11114
11441
  failure = "READ_BACK_FAILED";
11115
11442
  }
11116
- if (!failure) return;
11443
+ if (!failure) {
11444
+ if (change.written) void this.rebalanceAfterPoolSave(state, context, asset);
11445
+ return;
11446
+ }
11117
11447
  const restored = await this.restorePoolMemory(state, context, change);
11118
11448
  throw new OwneyError(
11119
11449
  "POOL_SELECTION_NOT_APPLIED",
@@ -11144,10 +11474,10 @@ var YieldseekerAgent = class {
11144
11474
  }
11145
11475
  /**
11146
11476
  * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11147
- * has no brackets. No picks names no vault.
11477
+ * has no brackets. There is always at least one pick (setPoolSelection
11478
+ * refuses a save with none).
11148
11479
  */
11149
11480
  async poolMemoryContent(asset, picks) {
11150
- if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11151
11481
  const vaults = new Map(
11152
11482
  (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11153
11483
  );
@@ -11394,29 +11724,26 @@ var YieldseekerAgent = class {
11394
11724
  }
11395
11725
  /**
11396
11726
  * The routing API's stored accounts for owner+chain, read once per session.
11397
- * Resolves null when unavailable (callers keep name matching) and never
11398
- * rejects. A failure is retried after a short window.
11727
+ * Resolves null when unavailable and never rejects; callers then refuse
11728
+ * (AGENT_ACCOUNTS_UNAVAILABLE) and create nothing. A failure is not kept:
11729
+ * concurrent callers share the in-flight read, and the next call reads again.
11399
11730
  */
11400
11731
  agentAccounts(state, chainId) {
11401
11732
  const key2 = this.userKey(state, chainId);
11402
11733
  const cached = this.agentAccountReads.get(key2);
11403
- if (cached && cached.expiresAt > Date.now()) return cached.value;
11404
- const generation = this.readGeneration;
11734
+ if (cached) return cached;
11405
11735
  const value = fetchAgentAccounts({
11406
11736
  apiKey: this.owneyApiKey,
11407
11737
  baseUrl: this.routingApiBaseUrl,
11408
11738
  owner: state.walletAddress,
11409
11739
  chainId
11410
11740
  }).catch(() => null).then((accounts) => {
11411
- if (accounts === null && this.readGeneration === generation && this.agentAccountReads.get(key2)?.value === value) {
11412
- this.agentAccountReads.set(key2, {
11413
- value,
11414
- expiresAt: Date.now() + YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS
11415
- });
11741
+ if (accounts === null && this.agentAccountReads.get(key2) === value) {
11742
+ this.agentAccountReads.delete(key2);
11416
11743
  }
11417
11744
  return accounts;
11418
11745
  });
11419
- this.agentAccountReads.set(key2, { value, expiresAt: Number.POSITIVE_INFINITY });
11746
+ this.agentAccountReads.set(key2, value);
11420
11747
  return value;
11421
11748
  }
11422
11749
  /** Yieldseeker accounts for one slot (returned addresses are compared lowercase). */
@@ -11688,16 +12015,28 @@ var YieldseekerAgent = class {
11688
12015
  * 1. the listed fitting agent whose wallet is the verified account's wallet,
11689
12016
  * whatever its name; the stored agentId is only a hint;
11690
12017
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
11691
- * 3. else the fitting agent named "owney" (first use, migration, or a
11692
- * verified wallet that is not a fitting listed agent), unless step 1/2
11693
- * read its wallet and it is closed (deactivated): that agent is not listed;
11694
- * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
11695
- * create); without one, undefined (the caller may create).
12018
+ * 3. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
12019
+ * create);
12020
+ * 4. else, with no record at all, the listed agent this session created or
12021
+ * adopted for the slot (sessionAgents); without one, undefined (the
12022
+ * caller creates an agent named "owney"). An agent is never picked by
12023
+ * its name: only our records, and this session's own create, say which
12024
+ * agents are Owney's.
12025
+ * Without the account records (`null`: the read failed) nothing can be
12026
+ * known, so the call is refused and nothing is created.
11696
12027
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
11697
12028
  * wallet reads. The account report then records the selected wallet; the
11698
12029
  * server marks it superseded when it differs from the verified wallet.
11699
12030
  */
11700
12031
  async chooseAgent(state, chainId, user, agents, accounts, asset) {
12032
+ if (accounts === null) {
12033
+ throw new OwneyError(
12034
+ "AGENT_API_ERROR",
12035
+ "Owney could not read this account's agents. Nothing was created. Please try again.",
12036
+ { rpcSource: "owney-api", reason: "AGENT_ACCOUNTS_UNAVAILABLE", chainId, asset },
12037
+ this.id
12038
+ );
12039
+ }
11701
12040
  const slot = this.slotAccounts(accounts, chainId, asset);
11702
12041
  const verified = slot.find((account) => account.status === "verified");
11703
12042
  const superseded = slot.filter((account) => account.status === "superseded");
@@ -11719,9 +12058,11 @@ var YieldseekerAgent = class {
11719
12058
  closed
11720
12059
  );
11721
12060
  if (match) return match;
12061
+ } else {
12062
+ const agentId = this.sessionAgents.get(this.slotKey(state, chainId, asset));
12063
+ const made = agentId && agents.find((agent) => agent.agentId === agentId && this.agentFits(agent, chainId, asset));
12064
+ if (made) return made;
11722
12065
  }
11723
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
11724
- if (named) return named;
11725
12066
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
11726
12067
  return void 0;
11727
12068
  }
@@ -11955,7 +12296,12 @@ var YieldseekerAgent = class {
11955
12296
  this.assertAgent(agent);
11956
12297
  return this.contextForAgent(state, chainId, user, agent, asset);
11957
12298
  }
11958
- /** Create the slot's agent. Only reached when no stored or named agent matched. */
12299
+ /**
12300
+ * Create the slot's agent, named "owney". Only reached when the slot has no
12301
+ * account record and no agent this session made; the created agent is
12302
+ * remembered for the session (sessionAgents) so reads select it before its
12303
+ * record exists.
12304
+ */
11959
12305
  async createAgent(state, chainId, user, agents, asset) {
11960
12306
  const generation = this.readGeneration;
11961
12307
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
@@ -12000,6 +12346,9 @@ var YieldseekerAgent = class {
12000
12346
  agents: [...agents, agent]
12001
12347
  }
12002
12348
  });
12349
+ if (typeof agent.agentId === "string") {
12350
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
12351
+ }
12003
12352
  }
12004
12353
  return agent;
12005
12354
  }
@@ -12016,6 +12365,10 @@ var YieldseekerAgent = class {
12016
12365
  const accounts = await this.agentAccounts(state, chainId);
12017
12366
  this.assertSession(generation, chainId, asset);
12018
12367
  const verified = this.slotAccounts(accounts, chainId, asset).some((account) => account.status === "verified");
12368
+ const adopt = (agent) => {
12369
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
12370
+ return agent;
12371
+ };
12019
12372
  for (let attempt = 0; attempt < 2; attempt += 1) {
12020
12373
  if (attempt > 0) {
12021
12374
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_CREATE_CONFLICT_RETRY_MS));
@@ -12025,12 +12378,12 @@ var YieldseekerAgent = class {
12025
12378
  this.assertSession(generation, chainId, asset);
12026
12379
  if (!verified && agentId) {
12027
12380
  const agent = agents.find((candidate) => candidate.agentId === agentId && this.agentFits(candidate, chainId, asset));
12028
- if (agent) return agent;
12381
+ if (agent) return adopt(agent);
12029
12382
  continue;
12030
12383
  }
12031
12384
  try {
12032
12385
  const agent = await this.chooseAgent(state, chainId, user, agents, accounts, asset);
12033
- if (agent) return agent;
12386
+ if (agent) return adopt(agent);
12034
12387
  } catch (error) {
12035
12388
  if (!this.isAgentMissing(error) || attempt > 0) throw error;
12036
12389
  }
@@ -12150,7 +12503,7 @@ var YieldseekerAgent = class {
12150
12503
  this.portfolioVersions.set(contextKey, version);
12151
12504
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12152
12505
  this.snapshotFailures.delete(contextKey);
12153
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12506
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12154
12507
  for (const kind of kinds) {
12155
12508
  const key2 = `${kind}:${contextKey}`;
12156
12509
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -12359,6 +12712,9 @@ var YieldseekerAgent = class {
12359
12712
  if (this.recentDeployments.size > 32)
12360
12713
  this.recentDeployments.delete(this.recentDeployments.keys().next().value);
12361
12714
  }
12715
+ setAccountRefusedListener(listener) {
12716
+ this.accountRefusedListener = listener;
12717
+ }
12362
12718
  setFundingLedgerAccess(access) {
12363
12719
  this.ledgerAccess = access;
12364
12720
  this.ledgerReads.clear();
@@ -12777,6 +13133,24 @@ var YieldseekerAgent = class {
12777
13133
  return isWalletRejection(error) ? error : this.mapApiError(error);
12778
13134
  }
12779
13135
  mapApiError(error) {
13136
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") return error;
13137
+ if (error instanceof YieldseekerApiError && error.isAccountNotOwney) {
13138
+ try {
13139
+ this.accountRefusedListener?.();
13140
+ } catch {
13141
+ }
13142
+ return new OwneyError(
13143
+ "AGENT_ACCOUNT_NOT_OWNEY",
13144
+ "This wallet's Yieldseeker account was not created through Owney.",
13145
+ {
13146
+ rpcSource: "agent-api",
13147
+ statusCode: 403,
13148
+ providerCode: "YIELDSEEKER_ACCOUNT_NOT_OWNEY",
13149
+ permanent: true
13150
+ },
13151
+ this.id
13152
+ );
13153
+ }
12780
13154
  if (!(error instanceof YieldseekerApiError)) {
12781
13155
  return new OwneyError(
12782
13156
  "AGENT_API_ERROR",
@@ -12940,9 +13314,6 @@ var YieldseekerAgent = class {
12940
13314
  throw this.invalidResponse("agent");
12941
13315
  }
12942
13316
  }
12943
- isOwneyAgent(agent) {
12944
- return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
12945
- }
12946
13317
  assetForAgent(agent) {
12947
13318
  for (const asset of ["USDC", "WETH"]) {
12948
13319
  if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
@@ -16028,6 +16399,47 @@ function withWalletConnectSwitch(provider) {
16028
16399
  });
16029
16400
  }
16030
16401
 
16402
+ // src/lib/wallet-prompts.ts
16403
+ var PROMPT_METHODS = /* @__PURE__ */ new Set([
16404
+ "personal_sign",
16405
+ "eth_sign",
16406
+ "eth_signTypedData",
16407
+ "eth_signTypedData_v1",
16408
+ "eth_signTypedData_v3",
16409
+ "eth_signTypedData_v4",
16410
+ "eth_signTransaction",
16411
+ "eth_sendTransaction",
16412
+ "wallet_sendCalls"
16413
+ ]);
16414
+ var WALLET_PROMPT_HOLD_MS = 12e4;
16415
+ var WRAPPED = /* @__PURE__ */ Symbol.for("owney.oneWalletPrompt");
16416
+ function withOneWalletPrompt(provider) {
16417
+ const target = provider;
16418
+ if (target[WRAPPED] || typeof target.request !== "function") return provider;
16419
+ let tail = Promise.resolve();
16420
+ const request2 = (args) => {
16421
+ if (!PROMPT_METHODS.has(args?.method)) return target.request(args);
16422
+ const turn = tail.then(() => target.request(args));
16423
+ tail = new Promise((release) => {
16424
+ const timer = setTimeout(release, WALLET_PROMPT_HOLD_MS);
16425
+ const done = () => {
16426
+ clearTimeout(timer);
16427
+ release();
16428
+ };
16429
+ turn.then(done, done);
16430
+ });
16431
+ return turn;
16432
+ };
16433
+ return new Proxy(target, {
16434
+ get(obj, prop) {
16435
+ if (prop === WRAPPED) return true;
16436
+ if (prop === "request") return request2;
16437
+ const value = Reflect.get(obj, prop, obj);
16438
+ return typeof value === "function" ? value.bind(obj) : value;
16439
+ }
16440
+ });
16441
+ }
16442
+
16031
16443
  // src/lib/sponsored-calls-deposit.ts
16032
16444
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
16033
16445
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -16298,6 +16710,7 @@ var OwneySDK = class {
16298
16710
  * withdraw, but they are excluded from new deposits / activations.
16299
16711
  */
16300
16712
  disabledAgents = /* @__PURE__ */ new Set();
16713
+ accountRefusedListeners = /* @__PURE__ */ new Set();
16301
16714
  /**
16302
16715
  * Agents whose sign-in the user cancelled this session (the wallet rejected
16303
16716
  * the prompt), keyed by chain. Until the app ends the session they are read
@@ -16520,6 +16933,32 @@ var OwneySDK = class {
16520
16933
  } catch {
16521
16934
  }
16522
16935
  }
16936
+ /**
16937
+ * Listens for an agent refusing the connected wallet because its provider
16938
+ * account was not created through Owney (`AGENT_ACCOUNT_NOT_OWNEY`). Fires
16939
+ * each time an agent maps such a refusal. Returns the unsubscribe function.
16940
+ */
16941
+ onAccountRefused(listener) {
16942
+ this.accountRefusedListeners.add(listener);
16943
+ return () => {
16944
+ this.accountRefusedListeners.delete(listener);
16945
+ };
16946
+ }
16947
+ /** Wires the optional hooks the SDK offers an agent. */
16948
+ attachAgentHooks(agent) {
16949
+ try {
16950
+ agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
16951
+ } catch {
16952
+ }
16953
+ agent.setAccountRefusedListener?.(() => {
16954
+ for (const listener of [...this.accountRefusedListeners]) {
16955
+ try {
16956
+ listener(agent.id);
16957
+ } catch {
16958
+ }
16959
+ }
16960
+ });
16961
+ }
16523
16962
  /**
16524
16963
  * Funding-ledger read access handed to agents for earnings holds. Reads only
16525
16964
  * for the connected owner; null otherwise and on any failure.
@@ -16603,7 +17042,7 @@ var OwneySDK = class {
16603
17042
  if (revision !== this.connectionRevision)
16604
17043
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
16605
17044
  this.state = {
16606
- provider: withWalletConnectSwitch(provider),
17045
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
16607
17046
  walletAddress,
16608
17047
  chainId: null
16609
17048
  };
@@ -16971,10 +17410,7 @@ var OwneySDK = class {
16971
17410
  if (!configured) continue;
16972
17411
  const agent = this.createAgent(agent_type, key2);
16973
17412
  if (!agent) continue;
16974
- try {
16975
- agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
16976
- } catch {
16977
- }
17413
+ this.attachAgentHooks(agent);
16978
17414
  this.agents.set(agent_type, agent);
16979
17415
  if (is_enabled === false) {
16980
17416
  this.disabledAgents.add(agent_type);
@@ -18026,6 +18462,11 @@ var OwneySDK = class {
18026
18462
  * deposit's ledger operation when there is one. In the background: never
18027
18463
  * throws and never delays the deposit. A missed notice only leaves the
18028
18464
  * provider on its own schedule.
18465
+ *
18466
+ * An agent that reports its provider calls (`onNotice`) gets one
18467
+ * `provider.deposit_notified` event per call and a final
18468
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
18469
+ * Otherwise the outcome is the one `provider.deposit_notified`.
18029
18470
  */
18030
18471
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18031
18472
  try {
@@ -18038,12 +18479,18 @@ var OwneySDK = class {
18038
18479
  this.announcedDeposits.add(key2);
18039
18480
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18040
18481
  const legKey = `agent:${evidence.agentId}`;
18041
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18482
+ const record2 = (type, notice) => {
18042
18483
  try {
18043
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18484
+ ledgerOp?.event?.(type, { legKey, ...notice });
18044
18485
  } catch {
18045
18486
  }
18046
- });
18487
+ };
18488
+ let reported = false;
18489
+ const onNotice = (notice) => {
18490
+ reported = true;
18491
+ record2("provider.deposit_notified", notice);
18492
+ };
18493
+ 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));
18047
18494
  } catch {
18048
18495
  }
18049
18496
  }
@@ -19533,6 +19980,7 @@ var OwneySDK = class {
19533
19980
  let record2;
19534
19981
  let ledgerOp;
19535
19982
  let hadDurableRecord = false;
19983
+ let nothingSent = false;
19536
19984
  const startedAt = Date.now();
19537
19985
  let confirmationDeadline = Infinity;
19538
19986
  const assertCurrent = () => {
@@ -19693,7 +20141,10 @@ var OwneySDK = class {
19693
20141
  } catch (error) {
19694
20142
  const details = error instanceof OwneyError ? error.details : void 0;
19695
20143
  const moved = [...evidence.values()].some((value) => value.transfer !== "failed" && (value.delivery === "confirmed" || value.transfer === "unknown" || value.txHash || value.userOpHash || value.callsId || value.withdrawalRequest?.attempted));
19696
- if (!moved && !details?.partialResults && !details?.pendingSubmissions) throw error;
20144
+ if (!moved && !details?.partialResults && !details?.pendingSubmissions) {
20145
+ nothingSent = details?.rejectedBeforeSubmission === true && evidence.size === 0;
20146
+ throw error;
20147
+ }
19697
20148
  throw new OwneyError(
19698
20149
  "WITHDRAW_SWAP_INCOMPLETE",
19699
20150
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -19861,7 +20312,11 @@ var OwneySDK = class {
19861
20312
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
19862
20313
  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";
19863
20314
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
19864
- saveWithdrawSwap(record2);
20315
+ if (nothingSent && record2.recovery?.phase === "withdrawing" && !record2.recovery.results) {
20316
+ record2.status = "not-swapped";
20317
+ saveWithdrawSwap(record2);
20318
+ clearWithdrawSwap(record2.orderHash);
20319
+ } else saveWithdrawSwap(record2);
19865
20320
  }
19866
20321
  this.ledgerFailed(ledgerOp, error);
19867
20322
  throw error;