@owney/sdk 0.7.32-beta.8 → 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.8";
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
  };
@@ -9461,10 +9522,8 @@ var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
9461
9522
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
9462
9523
  var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
9463
9524
  var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
9464
- var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
9465
9525
  var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
9466
9526
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
9467
- var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
9468
9527
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
9469
9528
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
9470
9529
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
@@ -9640,7 +9699,13 @@ var YieldseekerAgent = class {
9640
9699
  agentContexts = /* @__PURE__ */ new Map();
9641
9700
  // Every resolved agent wallet, keyed by contextKey (slot + agentId).
9642
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.
9643
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();
9644
9709
  reportedAccounts = /* @__PURE__ */ new Set();
9645
9710
  // Slots whose verified agent is missing even from a re-read list (and could
9646
9711
  // not be reopened), with the error the lookup failed with, until the list
@@ -9701,6 +9766,7 @@ var YieldseekerAgent = class {
9701
9766
  // Refresh when ready and the earnings hold (spec B2). Without ledger access,
9702
9767
  // or while the ledger read is null, settlement and earnings are as before.
9703
9768
  ledgerAccess;
9769
+ accountRefusedListener;
9704
9770
  ledgerReads = /* @__PURE__ */ new Map();
9705
9771
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9706
9772
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -9785,8 +9851,9 @@ var YieldseekerAgent = class {
9785
9851
  * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9786
9852
  * continues only when it is now open with the same address. Only the
9787
9853
  * verified record's agent is reopened: any other closed agent (a
9788
- * superseded-wallet match, or a named agent with no verified record, also
9789
- * 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;
9790
9857
  * - anything else refuses with nothing sent, before any progress event,
9791
9858
  * signature or callback. Every refusal carries `notSubmitted` and
9792
9859
  * `safeToFallback: false`, so no paid fallback runs.
@@ -9823,6 +9890,7 @@ var YieldseekerAgent = class {
9823
9890
  fresh2 = answer.agentWallet;
9824
9891
  } catch (error) {
9825
9892
  this.assertSession(generation, chainId, asset);
9893
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9826
9894
  throw new OwneyError(
9827
9895
  "YIELDSEEKER_WALLET_UNVERIFIED",
9828
9896
  "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
@@ -9911,6 +9979,7 @@ var YieldseekerAgent = class {
9911
9979
  break;
9912
9980
  } catch (error) {
9913
9981
  this.assertSession(generation, chainId, asset);
9982
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9914
9983
  if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
9915
9984
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
9916
9985
  this.assertSession(generation, chainId, asset);
@@ -10196,6 +10265,7 @@ var YieldseekerAgent = class {
10196
10265
  this.agentContexts.clear();
10197
10266
  this.walletContexts.clear();
10198
10267
  this.agentAccountReads.clear();
10268
+ this.sessionAgents.clear();
10199
10269
  this.reportedAccounts.clear();
10200
10270
  this.pendingSlotInvalidations.clear();
10201
10271
  this.knownContextKeys.clear();
@@ -10443,7 +10513,8 @@ var YieldseekerAgent = class {
10443
10513
  }
10444
10514
  let sponsor = false;
10445
10515
  if (gasMode !== "paid") {
10446
- 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;
10447
10518
  if (gasMode === "sponsored")
10448
10519
  throw new OwneyError(
10449
10520
  "SPONSOR_REQUEST_FAILED",
@@ -10543,8 +10614,11 @@ var YieldseekerAgent = class {
10543
10614
  let positionsStatus = "empty";
10544
10615
  const validatePositions = (values) => this.validateWithdrawalPositions(values, chainId, asset);
10545
10616
  validatePositions(positions);
10546
- const zeroValuePositions = /* @__PURE__ */ new WeakSet();
10547
- 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());
10548
10622
  const knownPositions = /* @__PURE__ */ new Map();
10549
10623
  const rememberPositions = (values) => {
10550
10624
  for (const position2 of values) knownPositions.set(position2.vaultOption.address.toLowerCase(), position2);
@@ -10574,6 +10648,7 @@ var YieldseekerAgent = class {
10574
10648
  if (!active || value === void 0) return null;
10575
10649
  this.assertSession(generation, chainId, asset);
10576
10650
  verified.withdrawableAssetsRaw = value.toString();
10651
+ if (value <= negligibleRaw && provenNegligible(position2)) negligiblePositions.add(verified);
10577
10652
  verifiedPositions.push(verified);
10578
10653
  return verified;
10579
10654
  }
@@ -10604,10 +10679,11 @@ var YieldseekerAgent = class {
10604
10679
  const redemptionValue = valuations[1];
10605
10680
  if (redemptionValue !== null && redemptionValue > 0n)
10606
10681
  verified.withdrawableAssetsRaw = redemptionValue.toString();
10682
+ if (valuations.every((value) => value !== null && value <= negligibleRaw) && provenNegligible(position2)) negligiblePositions.add(verified);
10607
10683
  return verified;
10608
10684
  }
10609
10685
  if (blockNumber === void 0 || valuations.some((value) => value !== 0n)) return null;
10610
- zeroValuePositions.add(verified);
10686
+ negligiblePositions.add(verified);
10611
10687
  }
10612
10688
  verifiedPositions.push(verified);
10613
10689
  return verified;
@@ -10722,6 +10798,28 @@ var YieldseekerAgent = class {
10722
10798
  return void 0;
10723
10799
  }
10724
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
+ };
10725
10823
  const unwind = async (position2, assetsRaw) => {
10726
10824
  this.assertSession(generation, chainId, asset);
10727
10825
  assertOperation?.();
@@ -10746,7 +10844,8 @@ var YieldseekerAgent = class {
10746
10844
  }
10747
10845
  } catch (error) {
10748
10846
  this.invalidateFundingRead(state, chainId, asset);
10749
- if (await vaultShares(position2) === 0n) {
10847
+ const refused = error instanceof OwneyError && error.details?.statusCode === 400;
10848
+ if (await releasedOnChain(position2, refused)) {
10750
10849
  payFromCurrentFunds = true;
10751
10850
  confirmedMovement = true;
10752
10851
  grossUnwound += assetsRaw;
@@ -10776,7 +10875,7 @@ var YieldseekerAgent = class {
10776
10875
  let unwound = false;
10777
10876
  for (const position2 of positions) {
10778
10877
  const available = BigInt(position2.withdrawableAssetsRaw);
10779
- if (available <= 0n) continue;
10878
+ if (available <= 0n || negligiblePositions.has(position2)) continue;
10780
10879
  await unwind(position2, available);
10781
10880
  unwound = true;
10782
10881
  }
@@ -10969,7 +11068,7 @@ var YieldseekerAgent = class {
10969
11068
  reason: "YIELDSEEKER_MAX_INCOMPLETE",
10970
11069
  asset,
10971
11070
  positionsStatus,
10972
- 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) => ({
10973
11072
  vaultAddress: position2.vaultOption.address,
10974
11073
  sharesRaw: position2.assetsRaw,
10975
11074
  withdrawableAmountRaw: position2.withdrawableAssetsRaw
@@ -11597,6 +11696,30 @@ var YieldseekerAgent = class {
11597
11696
  };
11598
11697
  }
11599
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
+ }
11600
11723
  /**
11601
11724
  * When Yieldseeker may move funds again after this agent wallet's last
11602
11725
  * confirmed withdrawal, if that is still ahead; null when there was none in
@@ -11880,13 +12003,11 @@ var YieldseekerAgent = class {
11880
12003
  *
11881
12004
  * - Only Base entries are ours. An asset with no picks whose entries showed
11882
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.
11883
12009
  * - Some vaults picked: the managed list names them. Saving it again
11884
12010
  * replaces it, so there is only ever one.
11885
- * - None picked (vaults shown): the managed list names no vault, and the
11886
- * rules must read back as an empty allow-list. Yieldseeker then keeps the
11887
- * agent's money out of every vault, as Zyfai does with an empty pool list,
11888
- * and the next Pools step reads "none". Only an agent that already exists
11889
- * is written: one is never created just to hold "none".
11890
12011
  * - Every vault picked: the managed list is deleted, and no allow-list may
11891
12012
  * remain, so vaults Yieldseeker adds later are allowed too.
11892
12013
  * - A free-text allow-list we saved before the managed list existed is
@@ -11919,21 +12040,27 @@ var YieldseekerAgent = class {
11919
12040
  group.shown.push(...entry.availablePools);
11920
12041
  byAsset.set(entry.asset, group);
11921
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
+ }
11922
12053
  for (const [asset, group] of byAsset) {
11923
12054
  const picks = uniqueAddresses(group.picked);
11924
12055
  const shown = uniqueAddresses(group.shown);
11925
- if (picks.length === 0 && shown.length === 0) continue;
12056
+ if (picks.length === 0) continue;
11926
12057
  const picked = new Set(picks.map((address) => address.toLowerCase()));
11927
12058
  const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11928
12059
  await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11929
12060
  }
11930
12061
  }
11931
12062
  async savePoolPicks(state, asset, picks, everyVaultPicked) {
11932
- const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11933
- if (!context) {
11934
- debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11935
- return;
11936
- }
12063
+ const context = await this.ensureAgent(state, 8453, asset);
11937
12064
  const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11938
12065
  const managed = active.find(isManagedVaultList);
11939
12066
  const legacy = active.filter(isLegacyPoolSelectionMemory);
@@ -11955,6 +12082,7 @@ var YieldseekerAgent = class {
11955
12082
  });
11956
12083
  change.written = true;
11957
12084
  }
12085
+ } else if (managed?.content === content) {
11958
12086
  } else {
11959
12087
  const answer = await this.memoryRequest(state, context, "memories", {
11960
12088
  method: "POST",
@@ -11972,7 +12100,10 @@ var YieldseekerAgent = class {
11972
12100
  } catch {
11973
12101
  failure = "READ_BACK_FAILED";
11974
12102
  }
11975
- if (!failure) return;
12103
+ if (!failure) {
12104
+ if (change.written) void this.rebalanceAfterPoolSave(state, context, asset);
12105
+ return;
12106
+ }
11976
12107
  const restored = await this.restorePoolMemory(state, context, change);
11977
12108
  throw new OwneyError(
11978
12109
  "POOL_SELECTION_NOT_APPLIED",
@@ -12003,10 +12134,10 @@ var YieldseekerAgent = class {
12003
12134
  }
12004
12135
  /**
12005
12136
  * `<address> (<name>)` for each pick, under the prefix. An unnamed address
12006
- * 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).
12007
12139
  */
12008
12140
  async poolMemoryContent(asset, picks) {
12009
- if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
12010
12141
  const vaults = new Map(
12011
12142
  (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
12012
12143
  );
@@ -12253,29 +12384,26 @@ var YieldseekerAgent = class {
12253
12384
  }
12254
12385
  /**
12255
12386
  * The routing API's stored accounts for owner+chain, read once per session.
12256
- * Resolves null when unavailable (callers keep name matching) and never
12257
- * 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.
12258
12390
  */
12259
12391
  agentAccounts(state, chainId) {
12260
12392
  const key2 = this.userKey(state, chainId);
12261
12393
  const cached = this.agentAccountReads.get(key2);
12262
- if (cached && cached.expiresAt > Date.now()) return cached.value;
12263
- const generation = this.readGeneration;
12394
+ if (cached) return cached;
12264
12395
  const value = fetchAgentAccounts({
12265
12396
  apiKey: this.owneyApiKey,
12266
12397
  baseUrl: this.routingApiBaseUrl,
12267
12398
  owner: state.walletAddress,
12268
12399
  chainId
12269
12400
  }).catch(() => null).then((accounts) => {
12270
- if (accounts === null && this.readGeneration === generation && this.agentAccountReads.get(key2)?.value === value) {
12271
- this.agentAccountReads.set(key2, {
12272
- value,
12273
- expiresAt: Date.now() + YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS
12274
- });
12401
+ if (accounts === null && this.agentAccountReads.get(key2) === value) {
12402
+ this.agentAccountReads.delete(key2);
12275
12403
  }
12276
12404
  return accounts;
12277
12405
  });
12278
- this.agentAccountReads.set(key2, { value, expiresAt: Number.POSITIVE_INFINITY });
12406
+ this.agentAccountReads.set(key2, value);
12279
12407
  return value;
12280
12408
  }
12281
12409
  /** Yieldseeker accounts for one slot (returned addresses are compared lowercase). */
@@ -12547,16 +12675,28 @@ var YieldseekerAgent = class {
12547
12675
  * 1. the listed fitting agent whose wallet is the verified account's wallet,
12548
12676
  * whatever its name; the stored agentId is only a hint;
12549
12677
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
12550
- * 3. else the fitting agent named "owney" (first use, migration, or a
12551
- * verified wallet that is not a fitting listed agent), unless step 1/2
12552
- * read its wallet and it is closed (deactivated): that agent is not listed;
12553
- * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
12554
- * 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.
12555
12687
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
12556
12688
  * wallet reads. The account report then records the selected wallet; the
12557
12689
  * server marks it superseded when it differs from the verified wallet.
12558
12690
  */
12559
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
+ }
12560
12700
  const slot = this.slotAccounts(accounts, chainId, asset);
12561
12701
  const verified = slot.find((account) => account.status === "verified");
12562
12702
  const superseded = slot.filter((account) => account.status === "superseded");
@@ -12578,9 +12718,11 @@ var YieldseekerAgent = class {
12578
12718
  closed
12579
12719
  );
12580
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;
12581
12725
  }
12582
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
12583
- if (named) return named;
12584
12726
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
12585
12727
  return void 0;
12586
12728
  }
@@ -12814,7 +12956,12 @@ var YieldseekerAgent = class {
12814
12956
  this.assertAgent(agent);
12815
12957
  return this.contextForAgent(state, chainId, user, agent, asset);
12816
12958
  }
12817
- /** 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
+ */
12818
12965
  async createAgent(state, chainId, user, agents, asset) {
12819
12966
  const generation = this.readGeneration;
12820
12967
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
@@ -12859,6 +13006,9 @@ var YieldseekerAgent = class {
12859
13006
  agents: [...agents, agent]
12860
13007
  }
12861
13008
  });
13009
+ if (typeof agent.agentId === "string") {
13010
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
13011
+ }
12862
13012
  }
12863
13013
  return agent;
12864
13014
  }
@@ -12875,6 +13025,10 @@ var YieldseekerAgent = class {
12875
13025
  const accounts = await this.agentAccounts(state, chainId);
12876
13026
  this.assertSession(generation, chainId, asset);
12877
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
+ };
12878
13032
  for (let attempt = 0; attempt < 2; attempt += 1) {
12879
13033
  if (attempt > 0) {
12880
13034
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_CREATE_CONFLICT_RETRY_MS));
@@ -12884,12 +13038,12 @@ var YieldseekerAgent = class {
12884
13038
  this.assertSession(generation, chainId, asset);
12885
13039
  if (!verified && agentId) {
12886
13040
  const agent = agents.find((candidate) => candidate.agentId === agentId && this.agentFits(candidate, chainId, asset));
12887
- if (agent) return agent;
13041
+ if (agent) return adopt(agent);
12888
13042
  continue;
12889
13043
  }
12890
13044
  try {
12891
13045
  const agent = await this.chooseAgent(state, chainId, user, agents, accounts, asset);
12892
- if (agent) return agent;
13046
+ if (agent) return adopt(agent);
12893
13047
  } catch (error) {
12894
13048
  if (!this.isAgentMissing(error) || attempt > 0) throw error;
12895
13049
  }
@@ -13218,6 +13372,9 @@ var YieldseekerAgent = class {
13218
13372
  if (this.recentDeployments.size > 32)
13219
13373
  this.recentDeployments.delete(this.recentDeployments.keys().next().value);
13220
13374
  }
13375
+ setAccountRefusedListener(listener) {
13376
+ this.accountRefusedListener = listener;
13377
+ }
13221
13378
  setFundingLedgerAccess(access) {
13222
13379
  this.ledgerAccess = access;
13223
13380
  this.ledgerReads.clear();
@@ -13636,6 +13793,24 @@ var YieldseekerAgent = class {
13636
13793
  return isWalletRejection(error) ? error : this.mapApiError(error);
13637
13794
  }
13638
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
+ }
13639
13814
  if (!(error instanceof YieldseekerApiError)) {
13640
13815
  return new OwneyError(
13641
13816
  "AGENT_API_ERROR",
@@ -13799,9 +13974,6 @@ var YieldseekerAgent = class {
13799
13974
  throw this.invalidResponse("agent");
13800
13975
  }
13801
13976
  }
13802
- isOwneyAgent(agent) {
13803
- return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
13804
- }
13805
13977
  assetForAgent(agent) {
13806
13978
  for (const asset of ["USDC", "WETH"]) {
13807
13979
  if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
@@ -17193,6 +17365,7 @@ var OwneySDK = class {
17193
17365
  * withdraw, but they are excluded from new deposits / activations.
17194
17366
  */
17195
17367
  disabledAgents = /* @__PURE__ */ new Set();
17368
+ accountRefusedListeners = /* @__PURE__ */ new Set();
17196
17369
  /**
17197
17370
  * Agents whose sign-in the user cancelled this session (the wallet rejected
17198
17371
  * the prompt), keyed by chain. Until the app ends the session they are read
@@ -17415,6 +17588,32 @@ var OwneySDK = class {
17415
17588
  } catch {
17416
17589
  }
17417
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
+ }
17418
17617
  /**
17419
17618
  * Funding-ledger read access handed to agents for earnings holds. Reads only
17420
17619
  * for the connected owner; null otherwise and on any failure.
@@ -17866,10 +18065,7 @@ var OwneySDK = class {
17866
18065
  if (!configured) continue;
17867
18066
  const agent = this.createAgent(agent_type, key2);
17868
18067
  if (!agent) continue;
17869
- try {
17870
- agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
17871
- } catch {
17872
- }
18068
+ this.attachAgentHooks(agent);
17873
18069
  this.agents.set(agent_type, agent);
17874
18070
  if (is_enabled === false) {
17875
18071
  this.disabledAgents.add(agent_type);