@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.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.8";
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
  };
@@ -8801,10 +8862,8 @@ var YIELDSEEKER_VAULT_OPTIONS_CACHE_MS = 6e4;
8801
8862
  var YIELDSEEKER_APY_STATS_CACHE_MS = 6e4;
8802
8863
  var YIELDSEEKER_MANAGED_VAULT_RULE = "ignored_vault";
8803
8864
  var YIELDSEEKER_POOL_MEMORY_PREFIX = "Only allocate to these vaults and never to any other vault:";
8804
- var YIELDSEEKER_NO_POOLS_CONTENT = `${YIELDSEEKER_POOL_MEMORY_PREFIX} none.`;
8805
8865
  var YIELDSEEKER_MAX_ACTIVE_MEMORIES = 3;
8806
8866
  var YIELDSEEKER_AGENT_LIST_CACHE_MS = 12e4;
8807
- var YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS = 6e4;
8808
8867
  var YIELDSEEKER_CREATE_CONFLICT_RETRY_MS = 2e3;
8809
8868
  var YIELDSEEKER_DEPLOY_VISIBILITY_WINDOW_MS = 12e4;
8810
8869
  var YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS = [1e3, 2e3];
@@ -8980,7 +9039,13 @@ var YieldseekerAgent = class {
8980
9039
  agentContexts = /* @__PURE__ */ new Map();
8981
9040
  // Every resolved agent wallet, keyed by contextKey (slot + agentId).
8982
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.
8983
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();
8984
9049
  reportedAccounts = /* @__PURE__ */ new Set();
8985
9050
  // Slots whose verified agent is missing even from a re-read list (and could
8986
9051
  // not be reopened), with the error the lookup failed with, until the list
@@ -9041,6 +9106,7 @@ var YieldseekerAgent = class {
9041
9106
  // Refresh when ready and the earnings hold (spec B2). Without ledger access,
9042
9107
  // or while the ledger read is null, settlement and earnings are as before.
9043
9108
  ledgerAccess;
9109
+ accountRefusedListener;
9044
9110
  ledgerReads = /* @__PURE__ */ new Map();
9045
9111
  /** contextKey -> movements this instance started settling (by tx hash) and how they refresh:
9046
9112
  * awaiting the ledger, refreshed when ready (ledger), or on the timed backoff (legacy). */
@@ -9125,8 +9191,9 @@ var YieldseekerAgent = class {
9125
9191
  * - closed (`deactivatedDate` set): reactivates it, re-reads the wallet, and
9126
9192
  * continues only when it is now open with the same address. Only the
9127
9193
  * verified record's agent is reopened: any other closed agent (a
9128
- * superseded-wallet match, or a named agent with no verified record, also
9129
- * 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;
9130
9197
  * - anything else refuses with nothing sent, before any progress event,
9131
9198
  * signature or callback. Every refusal carries `notSubmitted` and
9132
9199
  * `safeToFallback: false`, so no paid fallback runs.
@@ -9163,6 +9230,7 @@ var YieldseekerAgent = class {
9163
9230
  fresh2 = answer.agentWallet;
9164
9231
  } catch (error) {
9165
9232
  this.assertSession(generation, chainId, asset);
9233
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9166
9234
  throw new OwneyError(
9167
9235
  "YIELDSEEKER_WALLET_UNVERIFIED",
9168
9236
  "Could not check that the Yieldseeker agent is open. Nothing was sent. Please retry.",
@@ -9251,6 +9319,7 @@ var YieldseekerAgent = class {
9251
9319
  break;
9252
9320
  } catch (error) {
9253
9321
  this.assertSession(generation, chainId, asset);
9322
+ if (error instanceof OwneyError && error.code === "AGENT_ACCOUNT_NOT_OWNEY") throw error;
9254
9323
  if (justDeployed && attempt < YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS.length && isYieldseekerWalletCodeMissing(error)) {
9255
9324
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_DEPLOY_VISIBILITY_RETRY_MS[attempt]));
9256
9325
  this.assertSession(generation, chainId, asset);
@@ -9536,6 +9605,7 @@ var YieldseekerAgent = class {
9536
9605
  this.agentContexts.clear();
9537
9606
  this.walletContexts.clear();
9538
9607
  this.agentAccountReads.clear();
9608
+ this.sessionAgents.clear();
9539
9609
  this.reportedAccounts.clear();
9540
9610
  this.pendingSlotInvalidations.clear();
9541
9611
  this.knownContextKeys.clear();
@@ -9783,7 +9853,8 @@ var YieldseekerAgent = class {
9783
9853
  }
9784
9854
  let sponsor = false;
9785
9855
  if (gasMode !== "paid") {
9786
- 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;
9787
9858
  if (gasMode === "sponsored")
9788
9859
  throw new OwneyError(
9789
9860
  "SPONSOR_REQUEST_FAILED",
@@ -9883,8 +9954,11 @@ var YieldseekerAgent = class {
9883
9954
  let positionsStatus = "empty";
9884
9955
  const validatePositions = (values) => this.validateWithdrawalPositions(values, chainId, asset);
9885
9956
  validatePositions(positions);
9886
- const zeroValuePositions = /* @__PURE__ */ new WeakSet();
9887
- 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());
9888
9962
  const knownPositions = /* @__PURE__ */ new Map();
9889
9963
  const rememberPositions = (values) => {
9890
9964
  for (const position2 of values) knownPositions.set(position2.vaultOption.address.toLowerCase(), position2);
@@ -9914,6 +9988,7 @@ var YieldseekerAgent = class {
9914
9988
  if (!active || value === void 0) return null;
9915
9989
  this.assertSession(generation, chainId, asset);
9916
9990
  verified.withdrawableAssetsRaw = value.toString();
9991
+ if (value <= negligibleRaw && provenNegligible(position2)) negligiblePositions.add(verified);
9917
9992
  verifiedPositions.push(verified);
9918
9993
  return verified;
9919
9994
  }
@@ -9944,10 +10019,11 @@ var YieldseekerAgent = class {
9944
10019
  const redemptionValue = valuations[1];
9945
10020
  if (redemptionValue !== null && redemptionValue > 0n)
9946
10021
  verified.withdrawableAssetsRaw = redemptionValue.toString();
10022
+ if (valuations.every((value) => value !== null && value <= negligibleRaw) && provenNegligible(position2)) negligiblePositions.add(verified);
9947
10023
  return verified;
9948
10024
  }
9949
10025
  if (blockNumber === void 0 || valuations.some((value) => value !== 0n)) return null;
9950
- zeroValuePositions.add(verified);
10026
+ negligiblePositions.add(verified);
9951
10027
  }
9952
10028
  verifiedPositions.push(verified);
9953
10029
  return verified;
@@ -10062,6 +10138,28 @@ var YieldseekerAgent = class {
10062
10138
  return void 0;
10063
10139
  }
10064
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
+ };
10065
10163
  const unwind = async (position2, assetsRaw) => {
10066
10164
  this.assertSession(generation, chainId, asset);
10067
10165
  assertOperation?.();
@@ -10086,7 +10184,8 @@ var YieldseekerAgent = class {
10086
10184
  }
10087
10185
  } catch (error) {
10088
10186
  this.invalidateFundingRead(state, chainId, asset);
10089
- if (await vaultShares(position2) === 0n) {
10187
+ const refused = error instanceof OwneyError && error.details?.statusCode === 400;
10188
+ if (await releasedOnChain(position2, refused)) {
10090
10189
  payFromCurrentFunds = true;
10091
10190
  confirmedMovement = true;
10092
10191
  grossUnwound += assetsRaw;
@@ -10116,7 +10215,7 @@ var YieldseekerAgent = class {
10116
10215
  let unwound = false;
10117
10216
  for (const position2 of positions) {
10118
10217
  const available = BigInt(position2.withdrawableAssetsRaw);
10119
- if (available <= 0n) continue;
10218
+ if (available <= 0n || negligiblePositions.has(position2)) continue;
10120
10219
  await unwind(position2, available);
10121
10220
  unwound = true;
10122
10221
  }
@@ -10309,7 +10408,7 @@ var YieldseekerAgent = class {
10309
10408
  reason: "YIELDSEEKER_MAX_INCOMPLETE",
10310
10409
  asset,
10311
10410
  positionsStatus,
10312
- 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) => ({
10313
10412
  vaultAddress: position2.vaultOption.address,
10314
10413
  sharesRaw: position2.assetsRaw,
10315
10414
  withdrawableAmountRaw: position2.withdrawableAssetsRaw
@@ -10937,6 +11036,30 @@ var YieldseekerAgent = class {
10937
11036
  };
10938
11037
  }
10939
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
+ }
10940
11063
  /**
10941
11064
  * When Yieldseeker may move funds again after this agent wallet's last
10942
11065
  * confirmed withdrawal, if that is still ahead; null when there was none in
@@ -11220,13 +11343,11 @@ var YieldseekerAgent = class {
11220
11343
  *
11221
11344
  * - Only Base entries are ours. An asset with no picks whose entries showed
11222
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.
11223
11349
  * - Some vaults picked: the managed list names them. Saving it again
11224
11350
  * replaces it, so there is only ever one.
11225
- * - None picked (vaults shown): the managed list names no vault, and the
11226
- * rules must read back as an empty allow-list. Yieldseeker then keeps the
11227
- * agent's money out of every vault, as Zyfai does with an empty pool list,
11228
- * and the next Pools step reads "none". Only an agent that already exists
11229
- * is written: one is never created just to hold "none".
11230
11351
  * - Every vault picked: the managed list is deleted, and no allow-list may
11231
11352
  * remain, so vaults Yieldseeker adds later are allowed too.
11232
11353
  * - A free-text allow-list we saved before the managed list existed is
@@ -11259,21 +11380,27 @@ var YieldseekerAgent = class {
11259
11380
  group.shown.push(...entry.availablePools);
11260
11381
  byAsset.set(entry.asset, group);
11261
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
+ }
11262
11393
  for (const [asset, group] of byAsset) {
11263
11394
  const picks = uniqueAddresses(group.picked);
11264
11395
  const shown = uniqueAddresses(group.shown);
11265
- if (picks.length === 0 && shown.length === 0) continue;
11396
+ if (picks.length === 0) continue;
11266
11397
  const picked = new Set(picks.map((address) => address.toLowerCase()));
11267
11398
  const everyVaultPicked = shown.length > 0 && shown.every((address) => picked.has(address.toLowerCase()));
11268
11399
  await this.savePoolPicks(state, asset, picks, everyVaultPicked);
11269
11400
  }
11270
11401
  }
11271
11402
  async savePoolPicks(state, asset, picks, everyVaultPicked) {
11272
- const context = picks.length === 0 ? await this.findAgent(state, 8453, asset) : await this.ensureAgent(state, 8453, asset);
11273
- if (!context) {
11274
- debugLog("yieldseeker:pools", `${asset}: no agent yet, "no pools" not saved`);
11275
- return;
11276
- }
11403
+ const context = await this.ensureAgent(state, 8453, asset);
11277
11404
  const active = (await this.listMemories(state, context)).filter(isActiveMemory);
11278
11405
  const managed = active.find(isManagedVaultList);
11279
11406
  const legacy = active.filter(isLegacyPoolSelectionMemory);
@@ -11295,6 +11422,7 @@ var YieldseekerAgent = class {
11295
11422
  });
11296
11423
  change.written = true;
11297
11424
  }
11425
+ } else if (managed?.content === content) {
11298
11426
  } else {
11299
11427
  const answer = await this.memoryRequest(state, context, "memories", {
11300
11428
  method: "POST",
@@ -11312,7 +11440,10 @@ var YieldseekerAgent = class {
11312
11440
  } catch {
11313
11441
  failure = "READ_BACK_FAILED";
11314
11442
  }
11315
- if (!failure) return;
11443
+ if (!failure) {
11444
+ if (change.written) void this.rebalanceAfterPoolSave(state, context, asset);
11445
+ return;
11446
+ }
11316
11447
  const restored = await this.restorePoolMemory(state, context, change);
11317
11448
  throw new OwneyError(
11318
11449
  "POOL_SELECTION_NOT_APPLIED",
@@ -11343,10 +11474,10 @@ var YieldseekerAgent = class {
11343
11474
  }
11344
11475
  /**
11345
11476
  * `<address> (<name>)` for each pick, under the prefix. An unnamed address
11346
- * 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).
11347
11479
  */
11348
11480
  async poolMemoryContent(asset, picks) {
11349
- if (picks.length === 0) return YIELDSEEKER_NO_POOLS_CONTENT;
11350
11481
  const vaults = new Map(
11351
11482
  (await this.loadVaultOptions(asset)).map((vault) => [vault.address.toLowerCase(), vault])
11352
11483
  );
@@ -11593,29 +11724,26 @@ var YieldseekerAgent = class {
11593
11724
  }
11594
11725
  /**
11595
11726
  * The routing API's stored accounts for owner+chain, read once per session.
11596
- * Resolves null when unavailable (callers keep name matching) and never
11597
- * 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.
11598
11730
  */
11599
11731
  agentAccounts(state, chainId) {
11600
11732
  const key2 = this.userKey(state, chainId);
11601
11733
  const cached = this.agentAccountReads.get(key2);
11602
- if (cached && cached.expiresAt > Date.now()) return cached.value;
11603
- const generation = this.readGeneration;
11734
+ if (cached) return cached;
11604
11735
  const value = fetchAgentAccounts({
11605
11736
  apiKey: this.owneyApiKey,
11606
11737
  baseUrl: this.routingApiBaseUrl,
11607
11738
  owner: state.walletAddress,
11608
11739
  chainId
11609
11740
  }).catch(() => null).then((accounts) => {
11610
- if (accounts === null && this.readGeneration === generation && this.agentAccountReads.get(key2)?.value === value) {
11611
- this.agentAccountReads.set(key2, {
11612
- value,
11613
- expiresAt: Date.now() + YIELDSEEKER_AGENT_ACCOUNTS_FAILURE_CACHE_MS
11614
- });
11741
+ if (accounts === null && this.agentAccountReads.get(key2) === value) {
11742
+ this.agentAccountReads.delete(key2);
11615
11743
  }
11616
11744
  return accounts;
11617
11745
  });
11618
- this.agentAccountReads.set(key2, { value, expiresAt: Number.POSITIVE_INFINITY });
11746
+ this.agentAccountReads.set(key2, value);
11619
11747
  return value;
11620
11748
  }
11621
11749
  /** Yieldseeker accounts for one slot (returned addresses are compared lowercase). */
@@ -11887,16 +12015,28 @@ var YieldseekerAgent = class {
11887
12015
  * 1. the listed fitting agent whose wallet is the verified account's wallet,
11888
12016
  * whatever its name; the stored agentId is only a hint;
11889
12017
  * 2. else a listed fitting agent whose wallet is a superseded account's wallet;
11890
- * 3. else the fitting agent named "owney" (first use, migration, or a
11891
- * verified wallet that is not a fitting listed agent), unless step 1/2
11892
- * read its wallet and it is closed (deactivated): that agent is not listed;
11893
- * 4. else, with a verified account, throw YIELDSEEKER_AGENT_MISSING (never
11894
- * 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.
11895
12027
  * Steps 1 and 2 share one search of at most YIELDSEEKER_WALLET_MATCH_LIMIT
11896
12028
  * wallet reads. The account report then records the selected wallet; the
11897
12029
  * server marks it superseded when it differs from the verified wallet.
11898
12030
  */
11899
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
+ }
11900
12040
  const slot = this.slotAccounts(accounts, chainId, asset);
11901
12041
  const verified = slot.find((account) => account.status === "verified");
11902
12042
  const superseded = slot.filter((account) => account.status === "superseded");
@@ -11918,9 +12058,11 @@ var YieldseekerAgent = class {
11918
12058
  closed
11919
12059
  );
11920
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;
11921
12065
  }
11922
- const named = agents.find((agent) => this.isOwneyAgent(agent) && this.agentFits(agent, chainId, asset) && !closed.has(agent.agentId));
11923
- if (named) return named;
11924
12066
  if (verified) throw this.agentMissing(chainId, asset, verified.providerAgentId);
11925
12067
  return void 0;
11926
12068
  }
@@ -12154,7 +12296,12 @@ var YieldseekerAgent = class {
12154
12296
  this.assertAgent(agent);
12155
12297
  return this.contextForAgent(state, chainId, user, agent, asset);
12156
12298
  }
12157
- /** 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
+ */
12158
12305
  async createAgent(state, chainId, user, agents, asset) {
12159
12306
  const generation = this.readGeneration;
12160
12307
  const metadata = YIELDSEEKER_ASSET_METADATA[asset];
@@ -12199,6 +12346,9 @@ var YieldseekerAgent = class {
12199
12346
  agents: [...agents, agent]
12200
12347
  }
12201
12348
  });
12349
+ if (typeof agent.agentId === "string") {
12350
+ this.sessionAgents.set(this.slotKey(state, chainId, asset), agent.agentId);
12351
+ }
12202
12352
  }
12203
12353
  return agent;
12204
12354
  }
@@ -12215,6 +12365,10 @@ var YieldseekerAgent = class {
12215
12365
  const accounts = await this.agentAccounts(state, chainId);
12216
12366
  this.assertSession(generation, chainId, asset);
12217
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
+ };
12218
12372
  for (let attempt = 0; attempt < 2; attempt += 1) {
12219
12373
  if (attempt > 0) {
12220
12374
  await new Promise((resolve) => setTimeout(resolve, YIELDSEEKER_CREATE_CONFLICT_RETRY_MS));
@@ -12224,12 +12378,12 @@ var YieldseekerAgent = class {
12224
12378
  this.assertSession(generation, chainId, asset);
12225
12379
  if (!verified && agentId) {
12226
12380
  const agent = agents.find((candidate) => candidate.agentId === agentId && this.agentFits(candidate, chainId, asset));
12227
- if (agent) return agent;
12381
+ if (agent) return adopt(agent);
12228
12382
  continue;
12229
12383
  }
12230
12384
  try {
12231
12385
  const agent = await this.chooseAgent(state, chainId, user, agents, accounts, asset);
12232
- if (agent) return agent;
12386
+ if (agent) return adopt(agent);
12233
12387
  } catch (error) {
12234
12388
  if (!this.isAgentMissing(error) || attempt > 0) throw error;
12235
12389
  }
@@ -12558,6 +12712,9 @@ var YieldseekerAgent = class {
12558
12712
  if (this.recentDeployments.size > 32)
12559
12713
  this.recentDeployments.delete(this.recentDeployments.keys().next().value);
12560
12714
  }
12715
+ setAccountRefusedListener(listener) {
12716
+ this.accountRefusedListener = listener;
12717
+ }
12561
12718
  setFundingLedgerAccess(access) {
12562
12719
  this.ledgerAccess = access;
12563
12720
  this.ledgerReads.clear();
@@ -12976,6 +13133,24 @@ var YieldseekerAgent = class {
12976
13133
  return isWalletRejection(error) ? error : this.mapApiError(error);
12977
13134
  }
12978
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
+ }
12979
13154
  if (!(error instanceof YieldseekerApiError)) {
12980
13155
  return new OwneyError(
12981
13156
  "AGENT_API_ERROR",
@@ -13139,9 +13314,6 @@ var YieldseekerAgent = class {
13139
13314
  throw this.invalidResponse("agent");
13140
13315
  }
13141
13316
  }
13142
- isOwneyAgent(agent) {
13143
- return typeof agent.name === "string" && agent.name.trim().toLowerCase() === OWNEY_AGENT_NAME;
13144
- }
13145
13317
  assetForAgent(agent) {
13146
13318
  for (const asset of ["USDC", "WETH"]) {
13147
13319
  if (agent.assetAddress.toLowerCase() === YIELDSEEKER_ASSET_METADATA[asset].address.toLowerCase()) {
@@ -16538,6 +16710,7 @@ var OwneySDK = class {
16538
16710
  * withdraw, but they are excluded from new deposits / activations.
16539
16711
  */
16540
16712
  disabledAgents = /* @__PURE__ */ new Set();
16713
+ accountRefusedListeners = /* @__PURE__ */ new Set();
16541
16714
  /**
16542
16715
  * Agents whose sign-in the user cancelled this session (the wallet rejected
16543
16716
  * the prompt), keyed by chain. Until the app ends the session they are read
@@ -16760,6 +16933,32 @@ var OwneySDK = class {
16760
16933
  } catch {
16761
16934
  }
16762
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
+ }
16763
16962
  /**
16764
16963
  * Funding-ledger read access handed to agents for earnings holds. Reads only
16765
16964
  * for the connected owner; null otherwise and on any failure.
@@ -17211,10 +17410,7 @@ var OwneySDK = class {
17211
17410
  if (!configured) continue;
17212
17411
  const agent = this.createAgent(agent_type, key2);
17213
17412
  if (!agent) continue;
17214
- try {
17215
- agent.setFundingLedgerAccess?.(this.agentLedgerAccess());
17216
- } catch {
17217
- }
17413
+ this.attachAgentHooks(agent);
17218
17414
  this.agents.set(agent_type, agent);
17219
17415
  if (is_enabled === false) {
17220
17416
  this.disabledAgents.add(agent_type);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.32-beta.8",
3
+ "version": "0.7.32-beta.9",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",