@owney/sdk 0.7.32-beta.6 → 0.7.32-beta.8

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.6";
1686
+ var SDK_VERSION = "0.7.32-beta.8";
1687
1687
  var SCOPE2 = "funding-ledger";
1688
1688
  var REQUEST_TIMEOUT_MS2 = 5e3;
1689
1689
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -4545,19 +4545,31 @@ function mapAvailablePools(raw2) {
4545
4545
  for (const [token, entry] of Object.entries(byToken ?? {})) {
4546
4546
  for (const pool of entry?.pools ?? []) {
4547
4547
  if (!pool?.name) continue;
4548
+ const link = pool.info?.url || pool.info?.link || null;
4549
+ const address = vaultAddressFromLink(link);
4548
4550
  result.push({
4549
4551
  chainId,
4550
4552
  token,
4551
4553
  name: pool.name,
4552
4554
  apy: pool.info?.combined_apy ?? null,
4553
4555
  tvlUsd: pool.info?.tvlUsd ?? null,
4554
- link: pool.info?.link ?? null
4556
+ link,
4557
+ ...address !== void 0 && { address }
4555
4558
  });
4556
4559
  }
4557
4560
  }
4558
4561
  }
4559
4562
  return result;
4560
4563
  }
4564
+ var VAULT_IN_PATH = /\/(?:vault|lend)\/(0x[0-9a-fA-F]{40})(?=\/|$)/;
4565
+ function vaultAddressFromLink(link) {
4566
+ if (!link) return void 0;
4567
+ try {
4568
+ return new URL(link).pathname.match(VAULT_IN_PATH)?.[1];
4569
+ } catch {
4570
+ return void 0;
4571
+ }
4572
+ }
4561
4573
  function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
4562
4574
  const wanted = asset.toUpperCase();
4563
4575
  const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
@@ -8095,6 +8107,27 @@ function position(value, asset, baseAssetDecimals) {
8095
8107
  liquidity: Number(option.withdrawableDepositsUsd)
8096
8108
  };
8097
8109
  }
8110
+ function userFunds(context, assetAddress) {
8111
+ const live = context.liveWallet;
8112
+ if (!live) {
8113
+ return { idle: assetAddressValue(context.snapshot.tokenBalances, assetAddress), positions: context.positions };
8114
+ }
8115
+ const idle = live.idleRaw > live.feesOwedRaw ? live.idleRaw - live.feesOwedRaw : 0n;
8116
+ const pending2 = /^\d+$/.test(context.snapshot.pendingFeesBase ?? "") ? BigInt(context.snapshot.pendingFeesBase) : 0n;
8117
+ let fees = (live.feesOwedRaw > live.idleRaw ? live.feesOwedRaw - live.idleRaw : 0n) + pending2;
8118
+ const amounts = context.positions.map((entry) => balanceRaw(entry.assetsBase, "vault positions"));
8119
+ const order = amounts.map((_, index) => index).sort((a, b) => amounts[b] > amounts[a] ? 1 : amounts[b] < amounts[a] ? -1 : 0);
8120
+ for (const index of order) {
8121
+ if (fees === 0n) break;
8122
+ const taken = amounts[index] < fees ? amounts[index] : fees;
8123
+ amounts[index] = amounts[index] - taken;
8124
+ fees -= taken;
8125
+ }
8126
+ return {
8127
+ idle: idle.toString(),
8128
+ positions: context.positions.map((entry, index) => ({ ...entry, assetsBase: amounts[index].toString() }))
8129
+ };
8130
+ }
8098
8131
  function mapYieldseekerBalances(contexts) {
8099
8132
  const tokens = [];
8100
8133
  const assetBalances = [];
@@ -8108,18 +8141,15 @@ function mapYieldseekerBalances(contexts) {
8108
8141
  asset: context.asset,
8109
8142
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
8110
8143
  });
8111
- const idle = assetAddressValue(
8112
- context.snapshot.tokenBalances,
8113
- metadata.address
8114
- );
8144
+ const funds = userFunds(context, metadata.address);
8115
8145
  tokens.push({
8116
8146
  chain: "BASE",
8117
8147
  chainId: 8453,
8118
8148
  asset: context.asset,
8119
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
8149
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
8120
8150
  });
8121
8151
  positions.push(
8122
- ...context.positions.map(
8152
+ ...funds.positions.map(
8123
8153
  (entry) => position(
8124
8154
  entry,
8125
8155
  context.asset,
@@ -9488,6 +9518,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
9488
9518
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
9489
9519
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
9490
9520
  var YIELDSEEKER_LEDGER_GRACE_MS = 6e4;
9521
+ var DEPOSIT_NOTICE_ATTEMPTS = 3;
9522
+ var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
9523
+ var DEPOSIT_NOTICE_RETRY_MS = 15e3;
9524
+ var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
9525
+ var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
9526
+ var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
9527
+ var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
9491
9528
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
9492
9529
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
9493
9530
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -9557,6 +9594,18 @@ function query(params) {
9557
9594
  const encoded = search.toString();
9558
9595
  return encoded ? `?${encoded}` : "";
9559
9596
  }
9597
+ var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
9598
+ function parseRawAmount(raw2) {
9599
+ if (!raw2 || !/^\d+$/.test(raw2)) return null;
9600
+ const amount = BigInt(raw2);
9601
+ return amount > 0n ? amount : null;
9602
+ }
9603
+ function reportNotice(onNotice, notice) {
9604
+ try {
9605
+ onNotice?.(notice);
9606
+ } catch {
9607
+ }
9608
+ }
9560
9609
  var YieldseekerAgent = class {
9561
9610
  id = "yieldseeker";
9562
9611
  balanceComposition = "tokens-plus-positions";
@@ -10661,6 +10710,18 @@ var YieldseekerAgent = class {
10661
10710
  let grossUnwound = 0n;
10662
10711
  let confirmedUnwinds = 0n;
10663
10712
  let latestUnwindBlock;
10713
+ let payFromCurrentFunds = false;
10714
+ const vaultShares = async (position2) => {
10715
+ try {
10716
+ const [underlying, shares] = await this.readVaultShares([position2.vaultOption], agentWallet);
10717
+ this.assertSession(generation, chainId, asset);
10718
+ 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;
10719
+ return shares.result;
10720
+ } catch (error) {
10721
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10722
+ return void 0;
10723
+ }
10724
+ };
10664
10725
  const unwind = async (position2, assetsRaw) => {
10665
10726
  this.assertSession(generation, chainId, asset);
10666
10727
  assertOperation?.();
@@ -10685,6 +10746,12 @@ var YieldseekerAgent = class {
10685
10746
  }
10686
10747
  } catch (error) {
10687
10748
  this.invalidateFundingRead(state, chainId, asset);
10749
+ if (await vaultShares(position2) === 0n) {
10750
+ payFromCurrentFunds = true;
10751
+ confirmedMovement = true;
10752
+ grossUnwound += assetsRaw;
10753
+ return;
10754
+ }
10688
10755
  throw new OwneyError(
10689
10756
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10690
10757
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10749,7 +10816,7 @@ var YieldseekerAgent = class {
10749
10816
  remaining: remaining.toString()
10750
10817
  });
10751
10818
  }
10752
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10819
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10753
10820
  const availableForOwner = ownerFunds.available;
10754
10821
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10755
10822
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -11336,7 +11403,8 @@ var YieldseekerAgent = class {
11336
11403
  if (asset !== void 0) this.assertAsset(asset);
11337
11404
  const missingAssets = /* @__PURE__ */ new Set();
11338
11405
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
11339
- const balance = mapYieldseekerBalances(contexts);
11406
+ const liveWallets = await Promise.all(contexts.map((context) => this.readLiveWallet(state, chainId, context)));
11407
+ const balance = mapYieldseekerBalances(contexts.map((context, index) => liveWallets[index] === null ? context : { ...context, liveWallet: liveWallets[index] }));
11340
11408
  for (const [index, context] of contexts.entries()) {
11341
11409
  const read2 = balance.readMetadata[index];
11342
11410
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -11443,30 +11511,173 @@ var YieldseekerAgent = class {
11443
11511
  }
11444
11512
  /**
11445
11513
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
11446
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
11447
- * anything moves (the funding minimum, a deployed agent, no manual
11448
- * withdrawal in the last hour). Uses the agent this session already knows
11449
- * for the asset and the saved sign-in only: never prompts, never retries,
11450
- * never throws.
11514
+ * it now instead of on its next 30-minute check, and confirms it did.
11515
+ * Yieldseeker decides whether anything moves (the funding minimum, a
11516
+ * deployed agent, no manual withdrawal in the last hour), and its answer
11517
+ * (`{}`) does not say, so a minute after each notice the agent reads its
11518
+ * wallet: the deposit has gone into a vault when less than its amount is
11519
+ * left idle. While it has not, Yieldseeker is told again, up to
11520
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
11521
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
11522
+ * told once, since nothing can move yet. Uses the agent this session already
11523
+ * knows for the asset and the saved sign-in only: never prompts, never
11524
+ * throws. Each call is reported through `onNotice`.
11451
11525
  */
11452
- async depositConfirmed(state, chainId, evidence) {
11526
+ async depositConfirmed(state, chainId, evidence, onNotice) {
11527
+ let attempts = 0;
11453
11528
  try {
11454
11529
  const asset = String(evidence.token).toUpperCase();
11455
11530
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
11456
11531
  return { notified: false, reason: "UNSUPPORTED" };
11457
- const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
11532
+ const slotAsset = asset;
11533
+ const context = this.agentContexts.get(this.slotKey(state, chainId, slotAsset));
11458
11534
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
11459
11535
  return { notified: false, reason: "NO_AGENT" };
11460
11536
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
11537
+ const generation = this.readGeneration;
11538
+ const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
11539
+ const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
11540
+ let notified = false;
11541
+ let reason = "NOT_ALLOCATED";
11542
+ while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
11543
+ if (this.readGeneration !== generation || !this.auth.peekToken(state, chainId))
11544
+ return notified ? { notified: true, attempts, reason: "SESSION_ENDED" } : { notified: false, attempts, reason: "SESSION_ENDED" };
11545
+ attempts += 1;
11546
+ const sent = await this.sendDepositNotice(state, chainId, context);
11547
+ reportNotice(onNotice, sent.ok ? { notified: true, attempt: attempts } : { notified: false, reason: sent.reason, attempt: attempts });
11548
+ if (!sent.ok) {
11549
+ if (!sent.retryAfterMs || attempts >= DEPOSIT_NOTICE_ATTEMPTS)
11550
+ return notified ? { notified: true, attempts, allocated: false, reason: sent.reason } : { notified: false, attempts, reason: sent.reason };
11551
+ await wait2(sent.retryAfterMs);
11552
+ continue;
11553
+ }
11554
+ notified = true;
11555
+ if (amount === null) return { notified: true, attempts };
11556
+ await wait2(DEPOSIT_ALLOCATION_CHECK_MS);
11557
+ if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
11558
+ const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
11559
+ if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
11560
+ if (cooldownEnds !== null)
11561
+ return {
11562
+ notified: true,
11563
+ attempts,
11564
+ allocated: false,
11565
+ reason: "RECENT_WITHDRAWAL",
11566
+ allocatesAfter: new Date(cooldownEnds).toISOString()
11567
+ };
11568
+ reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
11569
+ }
11570
+ return { notified: true, attempts, allocated: false, reason };
11571
+ } catch (error) {
11572
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR", ...attempts ? { attempts } : {} };
11573
+ }
11574
+ }
11575
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
11576
+ async sendDepositNotice(state, chainId, context) {
11577
+ try {
11461
11578
  await this.walletRequest(
11462
11579
  state,
11463
11580
  chainId,
11464
11581
  this.agentPath(context, "deposit-made"),
11465
11582
  { method: "POST", body: {}, promptless: true }
11466
11583
  );
11467
- return { notified: true };
11584
+ return { ok: true };
11468
11585
  } catch (error) {
11469
- return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
11586
+ if (!(error instanceof OwneyError)) return { ok: false, reason: "ERROR" };
11587
+ const details = error.details ?? {};
11588
+ const status = typeof details.statusCode === "number" ? details.statusCode : void 0;
11589
+ const transient = error.code === "AGENT_TIMEOUT" || error.code === "AGENT_API_ERROR" && (status === void 0 || status === 0 || status === 408 || status === 429 || status >= 500);
11590
+ const reason = status ? `HTTP_${status}` : error.code === "AGENT_API_ERROR" ? "NETWORK" : error.code;
11591
+ if (!transient) return { ok: false, reason };
11592
+ const named = Number(details.fields?.headers?.["Retry-After"]) * 1e3;
11593
+ return {
11594
+ ok: false,
11595
+ reason,
11596
+ retryAfterMs: Number.isFinite(named) && named > 0 ? Math.min(named, DEPOSIT_NOTICE_RETRY_MAX_MS) : DEPOSIT_NOTICE_RETRY_MS
11597
+ };
11598
+ }
11599
+ }
11600
+ /**
11601
+ * When Yieldseeker may move funds again after this agent wallet's last
11602
+ * confirmed withdrawal, if that is still ahead; null when there was none in
11603
+ * the last hour or the ledger cannot say.
11604
+ */
11605
+ async withdrawalCooldownEnd(state, chainId, asset, context) {
11606
+ const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
11607
+ const wallet = context.wallet.walletAddress.toLowerCase();
11608
+ let latest = 0;
11609
+ for (const row of rows ?? []) {
11610
+ if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
11611
+ for (const leg of row.legs) {
11612
+ if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
11613
+ const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
11614
+ if (Number.isFinite(at)) latest = Math.max(latest, at);
11615
+ }
11616
+ }
11617
+ const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
11618
+ return latest > 0 && ends > Date.now() ? ends : null;
11619
+ }
11620
+ /**
11621
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
11622
+ * not collected from it, read at one block for a balance read. Cached
11623
+ * briefly per agent wallet and dropped by funding and allocation
11624
+ * invalidations. Null when any read fails or is slow: the snapshot's
11625
+ * amounts are used instead.
11626
+ */
11627
+ readLiveWallet(state, chainId, context) {
11628
+ const contextKey = this.contextKey(state, chainId, context);
11629
+ return this.cachedRead(`idle:${contextKey}`, YIELDSEEKER_LIVE_IDLE_CACHE_MS, () => withinBudget(
11630
+ this.readWalletFunds(chainId, context.asset, context.wallet.walletAddress),
11631
+ YIELDSEEKER_LIVE_IDLE_BUDGET_MS,
11632
+ null
11633
+ ));
11634
+ }
11635
+ async readWalletFunds(chainId, asset, walletAddress) {
11636
+ try {
11637
+ const client = this.getReceiptClient();
11638
+ const wallet = (0, import_viem17.getAddress)(walletAddress);
11639
+ const read2 = (operation) => withPaidRpcDiagnostics(operation, chainId, "eth_call", this.id);
11640
+ const blockNumber = await read2(() => client.getBlockNumber());
11641
+ const feeTracker = await read2(() => client.readContract({
11642
+ address: wallet,
11643
+ abi: YIELDSEEKER_AGENT_WALLET_ABI,
11644
+ functionName: "feeTracker",
11645
+ blockNumber
11646
+ }));
11647
+ if (!(0, import_viem17.isAddress)(feeTracker) || /^0x0{40}$/i.test(feeTracker)) return null;
11648
+ const [idle, owed] = await Promise.all([
11649
+ read2(() => client.readContract({
11650
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11651
+ abi: import_viem17.erc20Abi,
11652
+ functionName: "balanceOf",
11653
+ args: [wallet],
11654
+ blockNumber
11655
+ })),
11656
+ read2(() => client.readContract({
11657
+ address: (0, import_viem17.getAddress)(feeTracker),
11658
+ abi: YIELDSEEKER_FEE_TRACKER_ABI,
11659
+ functionName: "getFeesOwed",
11660
+ args: [wallet],
11661
+ blockNumber
11662
+ }))
11663
+ ]);
11664
+ return typeof idle === "bigint" && idle >= 0n && typeof owed === "bigint" && owed >= 0n ? { idleRaw: idle, feesOwedRaw: owed } : null;
11665
+ } catch {
11666
+ return null;
11667
+ }
11668
+ }
11669
+ /** The agent wallet's idle base asset; null when the read fails. */
11670
+ async readIdleBalance(chainId, asset, wallet) {
11671
+ try {
11672
+ const idle = await withPaidRpcDiagnostics(() => this.getReceiptClient().readContract({
11673
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11674
+ abi: import_viem17.erc20Abi,
11675
+ functionName: "balanceOf",
11676
+ args: [(0, import_viem17.getAddress)(wallet)]
11677
+ }), chainId, "eth_call", this.id);
11678
+ return typeof idle === "bigint" && idle >= 0n ? idle : null;
11679
+ } catch {
11680
+ return null;
11470
11681
  }
11471
11682
  }
11472
11683
  async getFundingWallet(state, chainId, asset) {
@@ -12798,7 +13009,7 @@ var YieldseekerAgent = class {
12798
13009
  this.portfolioVersions.set(contextKey, version);
12799
13010
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12800
13011
  this.snapshotFailures.delete(contextKey);
12801
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
13012
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12802
13013
  for (const kind of kinds) {
12803
13014
  const key2 = `${kind}:${contextKey}`;
12804
13015
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -16670,6 +16881,47 @@ function withWalletConnectSwitch(provider) {
16670
16881
  });
16671
16882
  }
16672
16883
 
16884
+ // src/lib/wallet-prompts.ts
16885
+ var PROMPT_METHODS = /* @__PURE__ */ new Set([
16886
+ "personal_sign",
16887
+ "eth_sign",
16888
+ "eth_signTypedData",
16889
+ "eth_signTypedData_v1",
16890
+ "eth_signTypedData_v3",
16891
+ "eth_signTypedData_v4",
16892
+ "eth_signTransaction",
16893
+ "eth_sendTransaction",
16894
+ "wallet_sendCalls"
16895
+ ]);
16896
+ var WALLET_PROMPT_HOLD_MS = 12e4;
16897
+ var WRAPPED = /* @__PURE__ */ Symbol.for("owney.oneWalletPrompt");
16898
+ function withOneWalletPrompt(provider) {
16899
+ const target = provider;
16900
+ if (target[WRAPPED] || typeof target.request !== "function") return provider;
16901
+ let tail = Promise.resolve();
16902
+ const request2 = (args) => {
16903
+ if (!PROMPT_METHODS.has(args?.method)) return target.request(args);
16904
+ const turn = tail.then(() => target.request(args));
16905
+ tail = new Promise((release) => {
16906
+ const timer = setTimeout(release, WALLET_PROMPT_HOLD_MS);
16907
+ const done = () => {
16908
+ clearTimeout(timer);
16909
+ release();
16910
+ };
16911
+ turn.then(done, done);
16912
+ });
16913
+ return turn;
16914
+ };
16915
+ return new Proxy(target, {
16916
+ get(obj, prop) {
16917
+ if (prop === WRAPPED) return true;
16918
+ if (prop === "request") return request2;
16919
+ const value = Reflect.get(obj, prop, obj);
16920
+ return typeof value === "function" ? value.bind(obj) : value;
16921
+ }
16922
+ });
16923
+ }
16924
+
16673
16925
  // src/lib/sponsored-calls-deposit.ts
16674
16926
  var import_viem24 = require("viem");
16675
16927
  init_errors();
@@ -17246,7 +17498,7 @@ var OwneySDK = class {
17246
17498
  if (revision !== this.connectionRevision)
17247
17499
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
17248
17500
  this.state = {
17249
- provider: withWalletConnectSwitch(provider),
17501
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
17250
17502
  walletAddress,
17251
17503
  chainId: null
17252
17504
  };
@@ -18669,6 +18921,11 @@ var OwneySDK = class {
18669
18921
  * deposit's ledger operation when there is one. In the background: never
18670
18922
  * throws and never delays the deposit. A missed notice only leaves the
18671
18923
  * provider on its own schedule.
18924
+ *
18925
+ * An agent that reports its provider calls (`onNotice`) gets one
18926
+ * `provider.deposit_notified` event per call and a final
18927
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
18928
+ * Otherwise the outcome is the one `provider.deposit_notified`.
18672
18929
  */
18673
18930
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18674
18931
  try {
@@ -18681,12 +18938,18 @@ var OwneySDK = class {
18681
18938
  this.announcedDeposits.add(key2);
18682
18939
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18683
18940
  const legKey = `agent:${evidence.agentId}`;
18684
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18941
+ const record2 = (type, notice) => {
18685
18942
  try {
18686
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18943
+ ledgerOp?.event?.(type, { legKey, ...notice });
18687
18944
  } catch {
18688
18945
  }
18689
- });
18946
+ };
18947
+ let reported = false;
18948
+ const onNotice = (notice) => {
18949
+ reported = true;
18950
+ record2("provider.deposit_notified", notice);
18951
+ };
18952
+ 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));
18690
18953
  } catch {
18691
18954
  }
18692
18955
  }
@@ -20176,6 +20439,7 @@ var OwneySDK = class {
20176
20439
  let record2;
20177
20440
  let ledgerOp;
20178
20441
  let hadDurableRecord = false;
20442
+ let nothingSent = false;
20179
20443
  const startedAt = Date.now();
20180
20444
  let confirmationDeadline = Infinity;
20181
20445
  const assertCurrent = () => {
@@ -20336,7 +20600,10 @@ var OwneySDK = class {
20336
20600
  } catch (error) {
20337
20601
  const details = error instanceof OwneyError ? error.details : void 0;
20338
20602
  const moved = [...evidence.values()].some((value) => value.transfer !== "failed" && (value.delivery === "confirmed" || value.transfer === "unknown" || value.txHash || value.userOpHash || value.callsId || value.withdrawalRequest?.attempted));
20339
- if (!moved && !details?.partialResults && !details?.pendingSubmissions) throw error;
20603
+ if (!moved && !details?.partialResults && !details?.pendingSubmissions) {
20604
+ nothingSent = details?.rejectedBeforeSubmission === true && evidence.size === 0;
20605
+ throw error;
20606
+ }
20340
20607
  throw new OwneyError(
20341
20608
  "WITHDRAW_SWAP_INCOMPLETE",
20342
20609
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -20504,7 +20771,11 @@ var OwneySDK = class {
20504
20771
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
20505
20772
  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";
20506
20773
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
20507
- saveWithdrawSwap(record2);
20774
+ if (nothingSent && record2.recovery?.phase === "withdrawing" && !record2.recovery.results) {
20775
+ record2.status = "not-swapped";
20776
+ saveWithdrawSwap(record2);
20777
+ clearWithdrawSwap(record2.orderHash);
20778
+ } else saveWithdrawSwap(record2);
20508
20779
  }
20509
20780
  this.ledgerFailed(ledgerOp, error);
20510
20781
  throw error;
package/dist/index.d.cts CHANGED
@@ -560,9 +560,11 @@ type AvailablePool = {
560
560
  /** Per-pool deep link (e.g. the Morpho vault page). null when absent. */
561
561
  link: string | null;
562
562
  /**
563
- * The pool's on-chain vault address. Set for Yieldseeker, whose pools are
564
- * identified by vault address; unset for Zyfai, whose pools are identified
565
- * by name.
563
+ * The pool's on-chain vault address. Yieldseeker identifies its pools by it.
564
+ * Zyfai identifies its pools by name and sends no address, so for Zyfai it is
565
+ * read from the pool's link where that names a vault (Morpho and Euler
566
+ * vaults) and is unset otherwise. It is how the same vault offered by two
567
+ * agents is recognised.
566
568
  */
567
569
  address?: string;
568
570
  };
@@ -649,12 +651,22 @@ type AgentFundingLedgerAccess = {
649
651
  before: Date;
650
652
  }): Promise<ProviderSnapshotSample | null>;
651
653
  };
652
- /** What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`). */
654
+ /**
655
+ * What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`).
656
+ * `attempts` counts the provider calls made. `allocated` is set when the agent
657
+ * checked whether the deposit was put to work; `allocatesAfter` (ISO) is when
658
+ * the provider will act on it at the earliest, when it said so.
659
+ */
653
660
  type DepositNotice = {
654
661
  notified: true;
662
+ attempts?: number;
663
+ allocated?: boolean;
664
+ reason?: string;
665
+ allocatesAfter?: string;
655
666
  } | {
656
667
  notified: false;
657
668
  reason: string;
669
+ attempts?: number;
658
670
  };
659
671
  interface IAgent {
660
672
  readonly id: string;
@@ -784,8 +796,12 @@ interface IAgent {
784
796
  * instead of waiting for its next scheduled check). The client calls it once
785
797
  * per confirmed transfer, in the background: it must never prompt the wallet
786
798
  * and never throw. Agents without it rely on their provider's own discovery.
799
+ * An agent that calls its provider more than once, or checks the outcome,
800
+ * reports each call through `onNotice` and resolves with the final outcome.
787
801
  */
788
- depositConfirmed?(state: ConnectionState, chainId: number, evidence: FundingEvidence): Promise<DepositNotice>;
802
+ depositConfirmed?(state: ConnectionState, chainId: number, evidence: FundingEvidence, onNotice?: (notice: DepositNotice & {
803
+ attempt: number;
804
+ }) => void): Promise<DepositNotice>;
789
805
  /** Invalidate only the confirmed asset. This hook must not sign or submit transactions. */
790
806
  invalidateFundingRead?(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, refreshUntil?: number, txHash?: string): void;
791
807
  /** End accelerated balance reads only for the exact snapshot the caller displayed. */
@@ -2319,6 +2335,11 @@ declare class OwneySDK {
2319
2335
  * deposit's ledger operation when there is one. In the background: never
2320
2336
  * throws and never delays the deposit. A missed notice only leaves the
2321
2337
  * provider on its own schedule.
2338
+ *
2339
+ * An agent that reports its provider calls (`onNotice`) gets one
2340
+ * `provider.deposit_notified` event per call and a final
2341
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
2342
+ * Otherwise the outcome is the one `provider.deposit_notified`.
2322
2343
  */
2323
2344
  private announceDepositConfirmed;
2324
2345
  private noteFundingRefresh;
@@ -3315,13 +3336,40 @@ declare class YieldseekerAgent implements IAgent {
3315
3336
  endFundingBalanceRefresh(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, read: AssetReadMetadata): boolean;
3316
3337
  /**
3317
3338
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
3318
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
3319
- * anything moves (the funding minimum, a deployed agent, no manual
3320
- * withdrawal in the last hour). Uses the agent this session already knows
3321
- * for the asset and the saved sign-in only: never prompts, never retries,
3322
- * never throws.
3323
- */
3324
- depositConfirmed(state: ConnectionState, chainId: number, evidence: FundingEvidence): Promise<DepositNotice>;
3339
+ * it now instead of on its next 30-minute check, and confirms it did.
3340
+ * Yieldseeker decides whether anything moves (the funding minimum, a
3341
+ * deployed agent, no manual withdrawal in the last hour), and its answer
3342
+ * (`{}`) does not say, so a minute after each notice the agent reads its
3343
+ * wallet: the deposit has gone into a vault when less than its amount is
3344
+ * left idle. While it has not, Yieldseeker is told again, up to
3345
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
3346
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
3347
+ * told once, since nothing can move yet. Uses the agent this session already
3348
+ * knows for the asset and the saved sign-in only: never prompts, never
3349
+ * throws. Each call is reported through `onNotice`.
3350
+ */
3351
+ depositConfirmed(state: ConnectionState, chainId: number, evidence: FundingEvidence, onNotice?: (notice: DepositNotice & {
3352
+ attempt: number;
3353
+ }) => void): Promise<DepositNotice>;
3354
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
3355
+ private sendDepositNotice;
3356
+ /**
3357
+ * When Yieldseeker may move funds again after this agent wallet's last
3358
+ * confirmed withdrawal, if that is still ahead; null when there was none in
3359
+ * the last hour or the ledger cannot say.
3360
+ */
3361
+ private withdrawalCooldownEnd;
3362
+ /**
3363
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
3364
+ * not collected from it, read at one block for a balance read. Cached
3365
+ * briefly per agent wallet and dropped by funding and allocation
3366
+ * invalidations. Null when any read fails or is slow: the snapshot's
3367
+ * amounts are used instead.
3368
+ */
3369
+ private readLiveWallet;
3370
+ private readWalletFunds;
3371
+ /** The agent wallet's idle base asset; null when the read fails. */
3372
+ private readIdleBalance;
3325
3373
  getFundingWallet(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<string>;
3326
3374
  hasExistingDepositFunds(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<true | undefined>;
3327
3375
  getEarnings(state: ConnectionState, chainId: number): Promise<AgentEarnings>;
package/dist/index.d.ts CHANGED
@@ -560,9 +560,11 @@ type AvailablePool = {
560
560
  /** Per-pool deep link (e.g. the Morpho vault page). null when absent. */
561
561
  link: string | null;
562
562
  /**
563
- * The pool's on-chain vault address. Set for Yieldseeker, whose pools are
564
- * identified by vault address; unset for Zyfai, whose pools are identified
565
- * by name.
563
+ * The pool's on-chain vault address. Yieldseeker identifies its pools by it.
564
+ * Zyfai identifies its pools by name and sends no address, so for Zyfai it is
565
+ * read from the pool's link where that names a vault (Morpho and Euler
566
+ * vaults) and is unset otherwise. It is how the same vault offered by two
567
+ * agents is recognised.
566
568
  */
567
569
  address?: string;
568
570
  };
@@ -649,12 +651,22 @@ type AgentFundingLedgerAccess = {
649
651
  before: Date;
650
652
  }): Promise<ProviderSnapshotSample | null>;
651
653
  };
652
- /** What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`). */
654
+ /**
655
+ * What an agent did with a confirmed-deposit notice (`IAgent.depositConfirmed`).
656
+ * `attempts` counts the provider calls made. `allocated` is set when the agent
657
+ * checked whether the deposit was put to work; `allocatesAfter` (ISO) is when
658
+ * the provider will act on it at the earliest, when it said so.
659
+ */
653
660
  type DepositNotice = {
654
661
  notified: true;
662
+ attempts?: number;
663
+ allocated?: boolean;
664
+ reason?: string;
665
+ allocatesAfter?: string;
655
666
  } | {
656
667
  notified: false;
657
668
  reason: string;
669
+ attempts?: number;
658
670
  };
659
671
  interface IAgent {
660
672
  readonly id: string;
@@ -784,8 +796,12 @@ interface IAgent {
784
796
  * instead of waiting for its next scheduled check). The client calls it once
785
797
  * per confirmed transfer, in the background: it must never prompt the wallet
786
798
  * and never throw. Agents without it rely on their provider's own discovery.
799
+ * An agent that calls its provider more than once, or checks the outcome,
800
+ * reports each call through `onNotice` and resolves with the final outcome.
787
801
  */
788
- depositConfirmed?(state: ConnectionState, chainId: number, evidence: FundingEvidence): Promise<DepositNotice>;
802
+ depositConfirmed?(state: ConnectionState, chainId: number, evidence: FundingEvidence, onNotice?: (notice: DepositNotice & {
803
+ attempt: number;
804
+ }) => void): Promise<DepositNotice>;
789
805
  /** Invalidate only the confirmed asset. This hook must not sign or submit transactions. */
790
806
  invalidateFundingRead?(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, refreshUntil?: number, txHash?: string): void;
791
807
  /** End accelerated balance reads only for the exact snapshot the caller displayed. */
@@ -2319,6 +2335,11 @@ declare class OwneySDK {
2319
2335
  * deposit's ledger operation when there is one. In the background: never
2320
2336
  * throws and never delays the deposit. A missed notice only leaves the
2321
2337
  * provider on its own schedule.
2338
+ *
2339
+ * An agent that reports its provider calls (`onNotice`) gets one
2340
+ * `provider.deposit_notified` event per call and a final
2341
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
2342
+ * Otherwise the outcome is the one `provider.deposit_notified`.
2322
2343
  */
2323
2344
  private announceDepositConfirmed;
2324
2345
  private noteFundingRefresh;
@@ -3315,13 +3336,40 @@ declare class YieldseekerAgent implements IAgent {
3315
3336
  endFundingBalanceRefresh(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, read: AssetReadMetadata): boolean;
3316
3337
  /**
3317
3338
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
3318
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
3319
- * anything moves (the funding minimum, a deployed agent, no manual
3320
- * withdrawal in the last hour). Uses the agent this session already knows
3321
- * for the asset and the saved sign-in only: never prompts, never retries,
3322
- * never throws.
3323
- */
3324
- depositConfirmed(state: ConnectionState, chainId: number, evidence: FundingEvidence): Promise<DepositNotice>;
3339
+ * it now instead of on its next 30-minute check, and confirms it did.
3340
+ * Yieldseeker decides whether anything moves (the funding minimum, a
3341
+ * deployed agent, no manual withdrawal in the last hour), and its answer
3342
+ * (`{}`) does not say, so a minute after each notice the agent reads its
3343
+ * wallet: the deposit has gone into a vault when less than its amount is
3344
+ * left idle. While it has not, Yieldseeker is told again, up to
3345
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
3346
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
3347
+ * told once, since nothing can move yet. Uses the agent this session already
3348
+ * knows for the asset and the saved sign-in only: never prompts, never
3349
+ * throws. Each call is reported through `onNotice`.
3350
+ */
3351
+ depositConfirmed(state: ConnectionState, chainId: number, evidence: FundingEvidence, onNotice?: (notice: DepositNotice & {
3352
+ attempt: number;
3353
+ }) => void): Promise<DepositNotice>;
3354
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
3355
+ private sendDepositNotice;
3356
+ /**
3357
+ * When Yieldseeker may move funds again after this agent wallet's last
3358
+ * confirmed withdrawal, if that is still ahead; null when there was none in
3359
+ * the last hour or the ledger cannot say.
3360
+ */
3361
+ private withdrawalCooldownEnd;
3362
+ /**
3363
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
3364
+ * not collected from it, read at one block for a balance read. Cached
3365
+ * briefly per agent wallet and dropped by funding and allocation
3366
+ * invalidations. Null when any read fails or is slow: the snapshot's
3367
+ * amounts are used instead.
3368
+ */
3369
+ private readLiveWallet;
3370
+ private readWalletFunds;
3371
+ /** The agent wallet's idle base asset; null when the read fails. */
3372
+ private readIdleBalance;
3325
3373
  getFundingWallet(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<string>;
3326
3374
  hasExistingDepositFunds(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<true | undefined>;
3327
3375
  getEarnings(state: ConnectionState, chainId: number): Promise<AgentEarnings>;
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.6";
1014
+ var SDK_VERSION = "0.7.32-beta.8";
1015
1015
  var SCOPE2 = "funding-ledger";
1016
1016
  var REQUEST_TIMEOUT_MS2 = 5e3;
1017
1017
  var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
@@ -3860,19 +3860,31 @@ function mapAvailablePools(raw2) {
3860
3860
  for (const [token, entry] of Object.entries(byToken ?? {})) {
3861
3861
  for (const pool of entry?.pools ?? []) {
3862
3862
  if (!pool?.name) continue;
3863
+ const link = pool.info?.url || pool.info?.link || null;
3864
+ const address = vaultAddressFromLink(link);
3863
3865
  result.push({
3864
3866
  chainId,
3865
3867
  token,
3866
3868
  name: pool.name,
3867
3869
  apy: pool.info?.combined_apy ?? null,
3868
3870
  tvlUsd: pool.info?.tvlUsd ?? null,
3869
- link: pool.info?.link ?? null
3871
+ link,
3872
+ ...address !== void 0 && { address }
3870
3873
  });
3871
3874
  }
3872
3875
  }
3873
3876
  }
3874
3877
  return result;
3875
3878
  }
3879
+ var VAULT_IN_PATH = /\/(?:vault|lend)\/(0x[0-9a-fA-F]{40})(?=\/|$)/;
3880
+ function vaultAddressFromLink(link) {
3881
+ if (!link) return void 0;
3882
+ try {
3883
+ return new URL(link).pathname.match(VAULT_IN_PATH)?.[1];
3884
+ } catch {
3885
+ return void 0;
3886
+ }
3887
+ }
3876
3888
  function assemblePoolCatalog(protocols, poolsByProtocol, asset, chains) {
3877
3889
  const wanted = asset.toUpperCase();
3878
3890
  const allowedChains = chains && chains.length > 0 ? new Set(chains) : void 0;
@@ -7427,6 +7439,27 @@ function position(value, asset, baseAssetDecimals) {
7427
7439
  liquidity: Number(option.withdrawableDepositsUsd)
7428
7440
  };
7429
7441
  }
7442
+ function userFunds(context, assetAddress) {
7443
+ const live = context.liveWallet;
7444
+ if (!live) {
7445
+ return { idle: assetAddressValue(context.snapshot.tokenBalances, assetAddress), positions: context.positions };
7446
+ }
7447
+ const idle = live.idleRaw > live.feesOwedRaw ? live.idleRaw - live.feesOwedRaw : 0n;
7448
+ const pending = /^\d+$/.test(context.snapshot.pendingFeesBase ?? "") ? BigInt(context.snapshot.pendingFeesBase) : 0n;
7449
+ let fees = (live.feesOwedRaw > live.idleRaw ? live.feesOwedRaw - live.idleRaw : 0n) + pending;
7450
+ const amounts = context.positions.map((entry) => balanceRaw(entry.assetsBase, "vault positions"));
7451
+ const order = amounts.map((_, index) => index).sort((a, b) => amounts[b] > amounts[a] ? 1 : amounts[b] < amounts[a] ? -1 : 0);
7452
+ for (const index of order) {
7453
+ if (fees === 0n) break;
7454
+ const taken = amounts[index] < fees ? amounts[index] : fees;
7455
+ amounts[index] = amounts[index] - taken;
7456
+ fees -= taken;
7457
+ }
7458
+ return {
7459
+ idle: idle.toString(),
7460
+ positions: context.positions.map((entry, index) => ({ ...entry, assetsBase: amounts[index].toString() }))
7461
+ };
7462
+ }
7430
7463
  function mapYieldseekerBalances(contexts) {
7431
7464
  const tokens = [];
7432
7465
  const assetBalances = [];
@@ -7440,18 +7473,15 @@ function mapYieldseekerBalances(contexts) {
7440
7473
  asset: context.asset,
7441
7474
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
7442
7475
  });
7443
- const idle = assetAddressValue(
7444
- context.snapshot.tokenBalances,
7445
- metadata.address
7446
- );
7476
+ const funds = userFunds(context, metadata.address);
7447
7477
  tokens.push({
7448
7478
  chain: "BASE",
7449
7479
  chainId: 8453,
7450
7480
  asset: context.asset,
7451
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
7481
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
7452
7482
  });
7453
7483
  positions.push(
7454
- ...context.positions.map(
7484
+ ...funds.positions.map(
7455
7485
  (entry) => position(
7456
7486
  entry,
7457
7487
  context.asset,
@@ -8828,6 +8858,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
8828
8858
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
8829
8859
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
8830
8860
  var YIELDSEEKER_LEDGER_GRACE_MS = 6e4;
8861
+ var DEPOSIT_NOTICE_ATTEMPTS = 3;
8862
+ var DEPOSIT_ALLOCATION_CHECK_MS = 6e4;
8863
+ var DEPOSIT_NOTICE_RETRY_MS = 15e3;
8864
+ var DEPOSIT_NOTICE_RETRY_MAX_MS = 6e4;
8865
+ var YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS = 60 * 6e4;
8866
+ var YIELDSEEKER_LIVE_IDLE_CACHE_MS = 15e3;
8867
+ var YIELDSEEKER_LIVE_IDLE_BUDGET_MS = 3e3;
8831
8868
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
8832
8869
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
8833
8870
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -8897,6 +8934,18 @@ function query(params) {
8897
8934
  const encoded = search.toString();
8898
8935
  return encoded ? `?${encoded}` : "";
8899
8936
  }
8937
+ var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8938
+ function parseRawAmount(raw2) {
8939
+ if (!raw2 || !/^\d+$/.test(raw2)) return null;
8940
+ const amount = BigInt(raw2);
8941
+ return amount > 0n ? amount : null;
8942
+ }
8943
+ function reportNotice(onNotice, notice) {
8944
+ try {
8945
+ onNotice?.(notice);
8946
+ } catch {
8947
+ }
8948
+ }
8900
8949
  var YieldseekerAgent = class {
8901
8950
  id = "yieldseeker";
8902
8951
  balanceComposition = "tokens-plus-positions";
@@ -10001,6 +10050,18 @@ var YieldseekerAgent = class {
10001
10050
  let grossUnwound = 0n;
10002
10051
  let confirmedUnwinds = 0n;
10003
10052
  let latestUnwindBlock;
10053
+ let payFromCurrentFunds = false;
10054
+ const vaultShares = async (position2) => {
10055
+ try {
10056
+ const [underlying, shares] = await this.readVaultShares([position2.vaultOption], agentWallet);
10057
+ this.assertSession(generation, chainId, asset);
10058
+ 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;
10059
+ return shares.result;
10060
+ } catch (error) {
10061
+ if (error instanceof OwneyError && error.code === "NOT_CONNECTED") throw error;
10062
+ return void 0;
10063
+ }
10064
+ };
10004
10065
  const unwind = async (position2, assetsRaw) => {
10005
10066
  this.assertSession(generation, chainId, asset);
10006
10067
  assertOperation?.();
@@ -10025,6 +10086,12 @@ var YieldseekerAgent = class {
10025
10086
  }
10026
10087
  } catch (error) {
10027
10088
  this.invalidateFundingRead(state, chainId, asset);
10089
+ if (await vaultShares(position2) === 0n) {
10090
+ payFromCurrentFunds = true;
10091
+ confirmedMovement = true;
10092
+ grossUnwound += assetsRaw;
10093
+ return;
10094
+ }
10028
10095
  throw new OwneyError(
10029
10096
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10030
10097
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10089,7 +10156,7 @@ var YieldseekerAgent = class {
10089
10156
  remaining: remaining.toString()
10090
10157
  });
10091
10158
  }
10092
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10159
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10093
10160
  const availableForOwner = ownerFunds.available;
10094
10161
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10095
10162
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -10676,7 +10743,8 @@ var YieldseekerAgent = class {
10676
10743
  if (asset !== void 0) this.assertAsset(asset);
10677
10744
  const missingAssets = /* @__PURE__ */ new Set();
10678
10745
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
10679
- const balance = mapYieldseekerBalances(contexts);
10746
+ const liveWallets = await Promise.all(contexts.map((context) => this.readLiveWallet(state, chainId, context)));
10747
+ const balance = mapYieldseekerBalances(contexts.map((context, index) => liveWallets[index] === null ? context : { ...context, liveWallet: liveWallets[index] }));
10680
10748
  for (const [index, context] of contexts.entries()) {
10681
10749
  const read2 = balance.readMetadata[index];
10682
10750
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -10783,30 +10851,173 @@ var YieldseekerAgent = class {
10783
10851
  }
10784
10852
  /**
10785
10853
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10786
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
10787
- * anything moves (the funding minimum, a deployed agent, no manual
10788
- * withdrawal in the last hour). Uses the agent this session already knows
10789
- * for the asset and the saved sign-in only: never prompts, never retries,
10790
- * never throws.
10854
+ * it now instead of on its next 30-minute check, and confirms it did.
10855
+ * Yieldseeker decides whether anything moves (the funding minimum, a
10856
+ * deployed agent, no manual withdrawal in the last hour), and its answer
10857
+ * (`{}`) does not say, so a minute after each notice the agent reads its
10858
+ * wallet: the deposit has gone into a vault when less than its amount is
10859
+ * left idle. While it has not, Yieldseeker is told again, up to
10860
+ * DEPOSIT_NOTICE_ATTEMPTS calls in all; a failed call (network, server, rate
10861
+ * limit) is sent again after a wait. Within an hour of a withdrawal it is
10862
+ * told once, since nothing can move yet. Uses the agent this session already
10863
+ * knows for the asset and the saved sign-in only: never prompts, never
10864
+ * throws. Each call is reported through `onNotice`.
10791
10865
  */
10792
- async depositConfirmed(state, chainId, evidence) {
10866
+ async depositConfirmed(state, chainId, evidence, onNotice) {
10867
+ let attempts = 0;
10793
10868
  try {
10794
10869
  const asset = String(evidence.token).toUpperCase();
10795
10870
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10796
10871
  return { notified: false, reason: "UNSUPPORTED" };
10797
- const context = this.agentContexts.get(this.slotKey(state, chainId, asset));
10872
+ const slotAsset = asset;
10873
+ const context = this.agentContexts.get(this.slotKey(state, chainId, slotAsset));
10798
10874
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10799
10875
  return { notified: false, reason: "NO_AGENT" };
10800
10876
  if (!this.auth.peekToken(state, chainId)) return { notified: false, reason: "NO_SESSION" };
10877
+ const generation = this.readGeneration;
10878
+ const amount = parseRawAmount(evidence.confirmedAmount ?? evidence.intendedAmount);
10879
+ const cooldownEnds = await this.withdrawalCooldownEnd(state, chainId, slotAsset, context);
10880
+ let notified = false;
10881
+ let reason = "NOT_ALLOCATED";
10882
+ while (attempts < DEPOSIT_NOTICE_ATTEMPTS) {
10883
+ if (this.readGeneration !== generation || !this.auth.peekToken(state, chainId))
10884
+ return notified ? { notified: true, attempts, reason: "SESSION_ENDED" } : { notified: false, attempts, reason: "SESSION_ENDED" };
10885
+ attempts += 1;
10886
+ const sent = await this.sendDepositNotice(state, chainId, context);
10887
+ reportNotice(onNotice, sent.ok ? { notified: true, attempt: attempts } : { notified: false, reason: sent.reason, attempt: attempts });
10888
+ if (!sent.ok) {
10889
+ if (!sent.retryAfterMs || attempts >= DEPOSIT_NOTICE_ATTEMPTS)
10890
+ return notified ? { notified: true, attempts, allocated: false, reason: sent.reason } : { notified: false, attempts, reason: sent.reason };
10891
+ await wait2(sent.retryAfterMs);
10892
+ continue;
10893
+ }
10894
+ notified = true;
10895
+ if (amount === null) return { notified: true, attempts };
10896
+ await wait2(DEPOSIT_ALLOCATION_CHECK_MS);
10897
+ if (this.readGeneration !== generation) return { notified: true, attempts, reason: "SESSION_ENDED" };
10898
+ const idle = await this.readIdleBalance(chainId, slotAsset, context.wallet.walletAddress);
10899
+ if (idle !== null && idle < amount) return { notified: true, attempts, allocated: true };
10900
+ if (cooldownEnds !== null)
10901
+ return {
10902
+ notified: true,
10903
+ attempts,
10904
+ allocated: false,
10905
+ reason: "RECENT_WITHDRAWAL",
10906
+ allocatesAfter: new Date(cooldownEnds).toISOString()
10907
+ };
10908
+ reason = idle === null ? "UNVERIFIED" : "NOT_ALLOCATED";
10909
+ }
10910
+ return { notified: true, attempts, allocated: false, reason };
10911
+ } catch (error) {
10912
+ return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR", ...attempts ? { attempts } : {} };
10913
+ }
10914
+ }
10915
+ /** One `deposit-made` call. A failure that may pass on its own carries the wait before the next try. */
10916
+ async sendDepositNotice(state, chainId, context) {
10917
+ try {
10801
10918
  await this.walletRequest(
10802
10919
  state,
10803
10920
  chainId,
10804
10921
  this.agentPath(context, "deposit-made"),
10805
10922
  { method: "POST", body: {}, promptless: true }
10806
10923
  );
10807
- return { notified: true };
10924
+ return { ok: true };
10808
10925
  } catch (error) {
10809
- return { notified: false, reason: error instanceof OwneyError ? error.code : "ERROR" };
10926
+ if (!(error instanceof OwneyError)) return { ok: false, reason: "ERROR" };
10927
+ const details = error.details ?? {};
10928
+ const status = typeof details.statusCode === "number" ? details.statusCode : void 0;
10929
+ const transient = error.code === "AGENT_TIMEOUT" || error.code === "AGENT_API_ERROR" && (status === void 0 || status === 0 || status === 408 || status === 429 || status >= 500);
10930
+ const reason = status ? `HTTP_${status}` : error.code === "AGENT_API_ERROR" ? "NETWORK" : error.code;
10931
+ if (!transient) return { ok: false, reason };
10932
+ const named = Number(details.fields?.headers?.["Retry-After"]) * 1e3;
10933
+ return {
10934
+ ok: false,
10935
+ reason,
10936
+ retryAfterMs: Number.isFinite(named) && named > 0 ? Math.min(named, DEPOSIT_NOTICE_RETRY_MAX_MS) : DEPOSIT_NOTICE_RETRY_MS
10937
+ };
10938
+ }
10939
+ }
10940
+ /**
10941
+ * When Yieldseeker may move funds again after this agent wallet's last
10942
+ * confirmed withdrawal, if that is still ahead; null when there was none in
10943
+ * the last hour or the ledger cannot say.
10944
+ */
10945
+ async withdrawalCooldownEnd(state, chainId, asset, context) {
10946
+ const rows = await withinBudget(this.readLedger(state, chainId, asset), this.ledgerBudgetMs, null);
10947
+ const wallet = context.wallet.walletAddress.toLowerCase();
10948
+ let latest = 0;
10949
+ for (const row of rows ?? []) {
10950
+ if (row.kind !== "withdraw" && row.kind !== "withdraw_swap") continue;
10951
+ for (const leg of row.legs) {
10952
+ if (leg.legKey !== `agent:${this.id}` || leg.status !== "confirmed" || leg.agentWallet?.toLowerCase() !== wallet) continue;
10953
+ const at = Date.parse(leg.confirmedAt ?? row.settledAt ?? "");
10954
+ if (Number.isFinite(at)) latest = Math.max(latest, at);
10955
+ }
10956
+ }
10957
+ const ends = latest + YIELDSEEKER_WITHDRAWAL_COOLDOWN_MS;
10958
+ return latest > 0 && ends > Date.now() ? ends : null;
10959
+ }
10960
+ /**
10961
+ * The agent wallet's base-asset balance and the platform fee Yieldseeker has
10962
+ * not collected from it, read at one block for a balance read. Cached
10963
+ * briefly per agent wallet and dropped by funding and allocation
10964
+ * invalidations. Null when any read fails or is slow: the snapshot's
10965
+ * amounts are used instead.
10966
+ */
10967
+ readLiveWallet(state, chainId, context) {
10968
+ const contextKey = this.contextKey(state, chainId, context);
10969
+ return this.cachedRead(`idle:${contextKey}`, YIELDSEEKER_LIVE_IDLE_CACHE_MS, () => withinBudget(
10970
+ this.readWalletFunds(chainId, context.asset, context.wallet.walletAddress),
10971
+ YIELDSEEKER_LIVE_IDLE_BUDGET_MS,
10972
+ null
10973
+ ));
10974
+ }
10975
+ async readWalletFunds(chainId, asset, walletAddress) {
10976
+ try {
10977
+ const client = this.getReceiptClient();
10978
+ const wallet = getAddress6(walletAddress);
10979
+ const read2 = (operation) => withPaidRpcDiagnostics(operation, chainId, "eth_call", this.id);
10980
+ const blockNumber = await read2(() => client.getBlockNumber());
10981
+ const feeTracker = await read2(() => client.readContract({
10982
+ address: wallet,
10983
+ abi: YIELDSEEKER_AGENT_WALLET_ABI,
10984
+ functionName: "feeTracker",
10985
+ blockNumber
10986
+ }));
10987
+ if (!isAddress4(feeTracker) || /^0x0{40}$/i.test(feeTracker)) return null;
10988
+ const [idle, owed] = await Promise.all([
10989
+ read2(() => client.readContract({
10990
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
10991
+ abi: erc20Abi5,
10992
+ functionName: "balanceOf",
10993
+ args: [wallet],
10994
+ blockNumber
10995
+ })),
10996
+ read2(() => client.readContract({
10997
+ address: getAddress6(feeTracker),
10998
+ abi: YIELDSEEKER_FEE_TRACKER_ABI,
10999
+ functionName: "getFeesOwed",
11000
+ args: [wallet],
11001
+ blockNumber
11002
+ }))
11003
+ ]);
11004
+ return typeof idle === "bigint" && idle >= 0n && typeof owed === "bigint" && owed >= 0n ? { idleRaw: idle, feesOwedRaw: owed } : null;
11005
+ } catch {
11006
+ return null;
11007
+ }
11008
+ }
11009
+ /** The agent wallet's idle base asset; null when the read fails. */
11010
+ async readIdleBalance(chainId, asset, wallet) {
11011
+ try {
11012
+ const idle = await withPaidRpcDiagnostics(() => this.getReceiptClient().readContract({
11013
+ address: YIELDSEEKER_ASSET_METADATA[asset].address,
11014
+ abi: erc20Abi5,
11015
+ functionName: "balanceOf",
11016
+ args: [getAddress6(wallet)]
11017
+ }), chainId, "eth_call", this.id);
11018
+ return typeof idle === "bigint" && idle >= 0n ? idle : null;
11019
+ } catch {
11020
+ return null;
10810
11021
  }
10811
11022
  }
10812
11023
  async getFundingWallet(state, chainId, asset) {
@@ -12138,7 +12349,7 @@ var YieldseekerAgent = class {
12138
12349
  this.portfolioVersions.set(contextKey, version);
12139
12350
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12140
12351
  this.snapshotFailures.delete(contextKey);
12141
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12352
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12142
12353
  for (const kind of kinds) {
12143
12354
  const key2 = `${kind}:${contextKey}`;
12144
12355
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -16016,6 +16227,47 @@ function withWalletConnectSwitch(provider) {
16016
16227
  });
16017
16228
  }
16018
16229
 
16230
+ // src/lib/wallet-prompts.ts
16231
+ var PROMPT_METHODS = /* @__PURE__ */ new Set([
16232
+ "personal_sign",
16233
+ "eth_sign",
16234
+ "eth_signTypedData",
16235
+ "eth_signTypedData_v1",
16236
+ "eth_signTypedData_v3",
16237
+ "eth_signTypedData_v4",
16238
+ "eth_signTransaction",
16239
+ "eth_sendTransaction",
16240
+ "wallet_sendCalls"
16241
+ ]);
16242
+ var WALLET_PROMPT_HOLD_MS = 12e4;
16243
+ var WRAPPED = /* @__PURE__ */ Symbol.for("owney.oneWalletPrompt");
16244
+ function withOneWalletPrompt(provider) {
16245
+ const target = provider;
16246
+ if (target[WRAPPED] || typeof target.request !== "function") return provider;
16247
+ let tail = Promise.resolve();
16248
+ const request2 = (args) => {
16249
+ if (!PROMPT_METHODS.has(args?.method)) return target.request(args);
16250
+ const turn = tail.then(() => target.request(args));
16251
+ tail = new Promise((release) => {
16252
+ const timer = setTimeout(release, WALLET_PROMPT_HOLD_MS);
16253
+ const done = () => {
16254
+ clearTimeout(timer);
16255
+ release();
16256
+ };
16257
+ turn.then(done, done);
16258
+ });
16259
+ return turn;
16260
+ };
16261
+ return new Proxy(target, {
16262
+ get(obj, prop) {
16263
+ if (prop === WRAPPED) return true;
16264
+ if (prop === "request") return request2;
16265
+ const value = Reflect.get(obj, prop, obj);
16266
+ return typeof value === "function" ? value.bind(obj) : value;
16267
+ }
16268
+ });
16269
+ }
16270
+
16019
16271
  // src/lib/sponsored-calls-deposit.ts
16020
16272
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
16021
16273
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -16591,7 +16843,7 @@ var OwneySDK = class {
16591
16843
  if (revision !== this.connectionRevision)
16592
16844
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
16593
16845
  this.state = {
16594
- provider: withWalletConnectSwitch(provider),
16846
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
16595
16847
  walletAddress,
16596
16848
  chainId: null
16597
16849
  };
@@ -18014,6 +18266,11 @@ var OwneySDK = class {
18014
18266
  * deposit's ledger operation when there is one. In the background: never
18015
18267
  * throws and never delays the deposit. A missed notice only leaves the
18016
18268
  * provider on its own schedule.
18269
+ *
18270
+ * An agent that reports its provider calls (`onNotice`) gets one
18271
+ * `provider.deposit_notified` event per call and a final
18272
+ * `provider.deposit_allocation` with the outcome (allocated or why not).
18273
+ * Otherwise the outcome is the one `provider.deposit_notified`.
18017
18274
  */
18018
18275
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18019
18276
  try {
@@ -18026,12 +18283,18 @@ var OwneySDK = class {
18026
18283
  this.announcedDeposits.add(key2);
18027
18284
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18028
18285
  const legKey = `agent:${evidence.agentId}`;
18029
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18286
+ const record2 = (type, notice) => {
18030
18287
  try {
18031
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18288
+ ledgerOp?.event?.(type, { legKey, ...notice });
18032
18289
  } catch {
18033
18290
  }
18034
- });
18291
+ };
18292
+ let reported = false;
18293
+ const onNotice = (notice) => {
18294
+ reported = true;
18295
+ record2("provider.deposit_notified", notice);
18296
+ };
18297
+ 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));
18035
18298
  } catch {
18036
18299
  }
18037
18300
  }
@@ -19521,6 +19784,7 @@ var OwneySDK = class {
19521
19784
  let record2;
19522
19785
  let ledgerOp;
19523
19786
  let hadDurableRecord = false;
19787
+ let nothingSent = false;
19524
19788
  const startedAt = Date.now();
19525
19789
  let confirmationDeadline = Infinity;
19526
19790
  const assertCurrent = () => {
@@ -19681,7 +19945,10 @@ var OwneySDK = class {
19681
19945
  } catch (error) {
19682
19946
  const details = error instanceof OwneyError ? error.details : void 0;
19683
19947
  const moved = [...evidence.values()].some((value) => value.transfer !== "failed" && (value.delivery === "confirmed" || value.transfer === "unknown" || value.txHash || value.userOpHash || value.callsId || value.withdrawalRequest?.attempted));
19684
- if (!moved && !details?.partialResults && !details?.pendingSubmissions) throw error;
19948
+ if (!moved && !details?.partialResults && !details?.pendingSubmissions) {
19949
+ nothingSent = details?.rejectedBeforeSubmission === true && evidence.size === 0;
19950
+ throw error;
19951
+ }
19685
19952
  throw new OwneyError(
19686
19953
  "WITHDRAW_SWAP_INCOMPLETE",
19687
19954
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -19849,7 +20116,11 @@ var OwneySDK = class {
19849
20116
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
19850
20117
  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";
19851
20118
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
19852
- saveWithdrawSwap(record2);
20119
+ if (nothingSent && record2.recovery?.phase === "withdrawing" && !record2.recovery.results) {
20120
+ record2.status = "not-swapped";
20121
+ saveWithdrawSwap(record2);
20122
+ clearWithdrawSwap(record2.orderHash);
20123
+ } else saveWithdrawSwap(record2);
19853
20124
  }
19854
20125
  this.ledgerFailed(ledgerOp, error);
19855
20126
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.32-beta.6",
3
+ "version": "0.7.32-beta.8",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",