@owney/sdk 0.7.32-beta.7 → 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.7";
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];
@@ -8107,6 +8107,27 @@ function position(value, asset, baseAssetDecimals) {
8107
8107
  liquidity: Number(option.withdrawableDepositsUsd)
8108
8108
  };
8109
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
+ }
8110
8131
  function mapYieldseekerBalances(contexts) {
8111
8132
  const tokens = [];
8112
8133
  const assetBalances = [];
@@ -8120,18 +8141,15 @@ function mapYieldseekerBalances(contexts) {
8120
8141
  asset: context.asset,
8121
8142
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
8122
8143
  });
8123
- const idle = assetAddressValue(
8124
- context.snapshot.tokenBalances,
8125
- metadata.address
8126
- );
8144
+ const funds = userFunds(context, metadata.address);
8127
8145
  tokens.push({
8128
8146
  chain: "BASE",
8129
8147
  chainId: 8453,
8130
8148
  asset: context.asset,
8131
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
8149
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
8132
8150
  });
8133
8151
  positions.push(
8134
- ...context.positions.map(
8152
+ ...funds.positions.map(
8135
8153
  (entry) => position(
8136
8154
  entry,
8137
8155
  context.asset,
@@ -9500,6 +9518,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
9500
9518
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
9501
9519
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
9502
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;
9503
9528
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
9504
9529
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
9505
9530
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -9569,6 +9594,18 @@ function query(params) {
9569
9594
  const encoded = search.toString();
9570
9595
  return encoded ? `?${encoded}` : "";
9571
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
+ }
9572
9609
  var YieldseekerAgent = class {
9573
9610
  id = "yieldseeker";
9574
9611
  balanceComposition = "tokens-plus-positions";
@@ -10673,6 +10710,18 @@ var YieldseekerAgent = class {
10673
10710
  let grossUnwound = 0n;
10674
10711
  let confirmedUnwinds = 0n;
10675
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
+ };
10676
10725
  const unwind = async (position2, assetsRaw) => {
10677
10726
  this.assertSession(generation, chainId, asset);
10678
10727
  assertOperation?.();
@@ -10697,6 +10746,12 @@ var YieldseekerAgent = class {
10697
10746
  }
10698
10747
  } catch (error) {
10699
10748
  this.invalidateFundingRead(state, chainId, asset);
10749
+ if (await vaultShares(position2) === 0n) {
10750
+ payFromCurrentFunds = true;
10751
+ confirmedMovement = true;
10752
+ grossUnwound += assetsRaw;
10753
+ return;
10754
+ }
10700
10755
  throw new OwneyError(
10701
10756
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10702
10757
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10761,7 +10816,7 @@ var YieldseekerAgent = class {
10761
10816
  remaining: remaining.toString()
10762
10817
  });
10763
10818
  }
10764
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10819
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10765
10820
  const availableForOwner = ownerFunds.available;
10766
10821
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10767
10822
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -11348,7 +11403,8 @@ var YieldseekerAgent = class {
11348
11403
  if (asset !== void 0) this.assertAsset(asset);
11349
11404
  const missingAssets = /* @__PURE__ */ new Set();
11350
11405
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
11351
- 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] }));
11352
11408
  for (const [index, context] of contexts.entries()) {
11353
11409
  const read2 = balance.readMetadata[index];
11354
11410
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -11455,30 +11511,173 @@ var YieldseekerAgent = class {
11455
11511
  }
11456
11512
  /**
11457
11513
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
11458
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
11459
- * anything moves (the funding minimum, a deployed agent, no manual
11460
- * withdrawal in the last hour). Uses the agent this session already knows
11461
- * for the asset and the saved sign-in only: never prompts, never retries,
11462
- * never throws.
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`.
11463
11525
  */
11464
- async depositConfirmed(state, chainId, evidence) {
11526
+ async depositConfirmed(state, chainId, evidence, onNotice) {
11527
+ let attempts = 0;
11465
11528
  try {
11466
11529
  const asset = String(evidence.token).toUpperCase();
11467
11530
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
11468
11531
  return { notified: false, reason: "UNSUPPORTED" };
11469
- 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));
11470
11534
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
11471
11535
  return { notified: false, reason: "NO_AGENT" };
11472
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 {
11473
11578
  await this.walletRequest(
11474
11579
  state,
11475
11580
  chainId,
11476
11581
  this.agentPath(context, "deposit-made"),
11477
11582
  { method: "POST", body: {}, promptless: true }
11478
11583
  );
11479
- return { notified: true };
11584
+ return { ok: true };
11480
11585
  } catch (error) {
11481
- 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;
11482
11681
  }
11483
11682
  }
11484
11683
  async getFundingWallet(state, chainId, asset) {
@@ -12810,7 +13009,7 @@ var YieldseekerAgent = class {
12810
13009
  this.portfolioVersions.set(contextKey, version);
12811
13010
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12812
13011
  this.snapshotFailures.delete(contextKey);
12813
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
13012
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12814
13013
  for (const kind of kinds) {
12815
13014
  const key2 = `${kind}:${contextKey}`;
12816
13015
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -16682,6 +16881,47 @@ function withWalletConnectSwitch(provider) {
16682
16881
  });
16683
16882
  }
16684
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
+
16685
16925
  // src/lib/sponsored-calls-deposit.ts
16686
16926
  var import_viem24 = require("viem");
16687
16927
  init_errors();
@@ -17258,7 +17498,7 @@ var OwneySDK = class {
17258
17498
  if (revision !== this.connectionRevision)
17259
17499
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
17260
17500
  this.state = {
17261
- provider: withWalletConnectSwitch(provider),
17501
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
17262
17502
  walletAddress,
17263
17503
  chainId: null
17264
17504
  };
@@ -18681,6 +18921,11 @@ var OwneySDK = class {
18681
18921
  * deposit's ledger operation when there is one. In the background: never
18682
18922
  * throws and never delays the deposit. A missed notice only leaves the
18683
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`.
18684
18929
  */
18685
18930
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18686
18931
  try {
@@ -18693,12 +18938,18 @@ var OwneySDK = class {
18693
18938
  this.announcedDeposits.add(key2);
18694
18939
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18695
18940
  const legKey = `agent:${evidence.agentId}`;
18696
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18941
+ const record2 = (type, notice) => {
18697
18942
  try {
18698
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18943
+ ledgerOp?.event?.(type, { legKey, ...notice });
18699
18944
  } catch {
18700
18945
  }
18701
- });
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));
18702
18953
  } catch {
18703
18954
  }
18704
18955
  }
@@ -20188,6 +20439,7 @@ var OwneySDK = class {
20188
20439
  let record2;
20189
20440
  let ledgerOp;
20190
20441
  let hadDurableRecord = false;
20442
+ let nothingSent = false;
20191
20443
  const startedAt = Date.now();
20192
20444
  let confirmationDeadline = Infinity;
20193
20445
  const assertCurrent = () => {
@@ -20348,7 +20600,10 @@ var OwneySDK = class {
20348
20600
  } catch (error) {
20349
20601
  const details = error instanceof OwneyError ? error.details : void 0;
20350
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));
20351
- 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
+ }
20352
20607
  throw new OwneyError(
20353
20608
  "WITHDRAW_SWAP_INCOMPLETE",
20354
20609
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -20516,7 +20771,11 @@ var OwneySDK = class {
20516
20771
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
20517
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";
20518
20773
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
20519
- 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);
20520
20779
  }
20521
20780
  this.ledgerFailed(ledgerOp, error);
20522
20781
  throw error;
package/dist/index.d.cts CHANGED
@@ -651,12 +651,22 @@ type AgentFundingLedgerAccess = {
651
651
  before: Date;
652
652
  }): Promise<ProviderSnapshotSample | null>;
653
653
  };
654
- /** 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
+ */
655
660
  type DepositNotice = {
656
661
  notified: true;
662
+ attempts?: number;
663
+ allocated?: boolean;
664
+ reason?: string;
665
+ allocatesAfter?: string;
657
666
  } | {
658
667
  notified: false;
659
668
  reason: string;
669
+ attempts?: number;
660
670
  };
661
671
  interface IAgent {
662
672
  readonly id: string;
@@ -786,8 +796,12 @@ interface IAgent {
786
796
  * instead of waiting for its next scheduled check). The client calls it once
787
797
  * per confirmed transfer, in the background: it must never prompt the wallet
788
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.
789
801
  */
790
- 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>;
791
805
  /** Invalidate only the confirmed asset. This hook must not sign or submit transactions. */
792
806
  invalidateFundingRead?(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, refreshUntil?: number, txHash?: string): void;
793
807
  /** End accelerated balance reads only for the exact snapshot the caller displayed. */
@@ -2321,6 +2335,11 @@ declare class OwneySDK {
2321
2335
  * deposit's ledger operation when there is one. In the background: never
2322
2336
  * throws and never delays the deposit. A missed notice only leaves the
2323
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`.
2324
2343
  */
2325
2344
  private announceDepositConfirmed;
2326
2345
  private noteFundingRefresh;
@@ -3317,13 +3336,40 @@ declare class YieldseekerAgent implements IAgent {
3317
3336
  endFundingBalanceRefresh(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, read: AssetReadMetadata): boolean;
3318
3337
  /**
3319
3338
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
3320
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
3321
- * anything moves (the funding minimum, a deployed agent, no manual
3322
- * withdrawal in the last hour). Uses the agent this session already knows
3323
- * for the asset and the saved sign-in only: never prompts, never retries,
3324
- * never throws.
3325
- */
3326
- 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;
3327
3373
  getFundingWallet(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<string>;
3328
3374
  hasExistingDepositFunds(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<true | undefined>;
3329
3375
  getEarnings(state: ConnectionState, chainId: number): Promise<AgentEarnings>;
package/dist/index.d.ts CHANGED
@@ -651,12 +651,22 @@ type AgentFundingLedgerAccess = {
651
651
  before: Date;
652
652
  }): Promise<ProviderSnapshotSample | null>;
653
653
  };
654
- /** 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
+ */
655
660
  type DepositNotice = {
656
661
  notified: true;
662
+ attempts?: number;
663
+ allocated?: boolean;
664
+ reason?: string;
665
+ allocatesAfter?: string;
657
666
  } | {
658
667
  notified: false;
659
668
  reason: string;
669
+ attempts?: number;
660
670
  };
661
671
  interface IAgent {
662
672
  readonly id: string;
@@ -786,8 +796,12 @@ interface IAgent {
786
796
  * instead of waiting for its next scheduled check). The client calls it once
787
797
  * per confirmed transfer, in the background: it must never prompt the wallet
788
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.
789
801
  */
790
- 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>;
791
805
  /** Invalidate only the confirmed asset. This hook must not sign or submit transactions. */
792
806
  invalidateFundingRead?(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, refreshUntil?: number, txHash?: string): void;
793
807
  /** End accelerated balance reads only for the exact snapshot the caller displayed. */
@@ -2321,6 +2335,11 @@ declare class OwneySDK {
2321
2335
  * deposit's ledger operation when there is one. In the background: never
2322
2336
  * throws and never delays the deposit. A missed notice only leaves the
2323
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`.
2324
2343
  */
2325
2344
  private announceDepositConfirmed;
2326
2345
  private noteFundingRefresh;
@@ -3317,13 +3336,40 @@ declare class YieldseekerAgent implements IAgent {
3317
3336
  endFundingBalanceRefresh(state: ConnectionState, chainId: number, asset: OwneySupportedTokens, read: AssetReadMetadata): boolean;
3318
3337
  /**
3319
3338
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
3320
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
3321
- * anything moves (the funding minimum, a deployed agent, no manual
3322
- * withdrawal in the last hour). Uses the agent this session already knows
3323
- * for the asset and the saved sign-in only: never prompts, never retries,
3324
- * never throws.
3325
- */
3326
- 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;
3327
3373
  getFundingWallet(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<string>;
3328
3374
  hasExistingDepositFunds(state: ConnectionState, chainId: number, asset: OwneySupportedTokens): Promise<true | undefined>;
3329
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.7";
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];
@@ -7439,6 +7439,27 @@ function position(value, asset, baseAssetDecimals) {
7439
7439
  liquidity: Number(option.withdrawableDepositsUsd)
7440
7440
  };
7441
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
+ }
7442
7463
  function mapYieldseekerBalances(contexts) {
7443
7464
  const tokens = [];
7444
7465
  const assetBalances = [];
@@ -7452,18 +7473,15 @@ function mapYieldseekerBalances(contexts) {
7452
7473
  asset: context.asset,
7453
7474
  amount: balanceDecimal(context.snapshot.totalValueBase, context.snapshot.baseAssetDecimals, "snapshot")
7454
7475
  });
7455
- const idle = assetAddressValue(
7456
- context.snapshot.tokenBalances,
7457
- metadata.address
7458
- );
7476
+ const funds = userFunds(context, metadata.address);
7459
7477
  tokens.push({
7460
7478
  chain: "BASE",
7461
7479
  chainId: 8453,
7462
7480
  asset: context.asset,
7463
- amount: balanceDecimal(idle, metadata.decimals, "snapshot")
7481
+ amount: balanceDecimal(funds.idle, metadata.decimals, "snapshot")
7464
7482
  });
7465
7483
  positions.push(
7466
- ...context.positions.map(
7484
+ ...funds.positions.map(
7467
7485
  (entry) => position(
7468
7486
  entry,
7469
7487
  context.asset,
@@ -8840,6 +8858,13 @@ var YIELDSEEKER_SETTLEMENT_SNAPSHOT_WINDOW_MS = 10 * 6e4;
8840
8858
  var YIELDSEEKER_SETTLEMENT_ACTIVITY_CACHE_MS = 15e3;
8841
8859
  var YIELDSEEKER_LEDGER_READ_CACHE_MS = 15e3;
8842
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;
8843
8868
  var YIELDSEEKER_SERVER_BASELINE_CACHE_MS = 10 * 6e4;
8844
8869
  var YIELDSEEKER_SERVER_BASELINE_MISS_CACHE_MS = 6e4;
8845
8870
  var YIELDSEEKER_REFRESH_PLAN_RETENTION_MS = 2 * 60 * 6e4;
@@ -8909,6 +8934,18 @@ function query(params) {
8909
8934
  const encoded = search.toString();
8910
8935
  return encoded ? `?${encoded}` : "";
8911
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
+ }
8912
8949
  var YieldseekerAgent = class {
8913
8950
  id = "yieldseeker";
8914
8951
  balanceComposition = "tokens-plus-positions";
@@ -10013,6 +10050,18 @@ var YieldseekerAgent = class {
10013
10050
  let grossUnwound = 0n;
10014
10051
  let confirmedUnwinds = 0n;
10015
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
+ };
10016
10065
  const unwind = async (position2, assetsRaw) => {
10017
10066
  this.assertSession(generation, chainId, asset);
10018
10067
  assertOperation?.();
@@ -10037,6 +10086,12 @@ var YieldseekerAgent = class {
10037
10086
  }
10038
10087
  } catch (error) {
10039
10088
  this.invalidateFundingRead(state, chainId, asset);
10089
+ if (await vaultShares(position2) === 0n) {
10090
+ payFromCurrentFunds = true;
10091
+ confirmedMovement = true;
10092
+ grossUnwound += assetsRaw;
10093
+ return;
10094
+ }
10040
10095
  throw new OwneyError(
10041
10096
  error instanceof OwneyError ? error.code : "WITHDRAW_FAILED",
10042
10097
  "Could not confirm the Yieldseeker vault release. No owner transfer was submitted.",
@@ -10101,7 +10156,7 @@ var YieldseekerAgent = class {
10101
10156
  remaining: remaining.toString()
10102
10157
  });
10103
10158
  }
10104
- const ownerFunds = confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10159
+ const ownerFunds = payFromCurrentFunds ? await readOwnerFunds() : confirmedMovement ? await readOwnerFunds(latestUnwindBlock) : initialFunds;
10105
10160
  const availableForOwner = ownerFunds.available;
10106
10161
  const shortfall = availableForOwner < requested ? requested - availableForOwner : 0n;
10107
10162
  const feeRate = feeRateBps ?? (confirmedMovement && amount !== void 0 && shortfall > confirmedUnwinds ? await boundedVerification(feeRateAnswer, YIELDSEEKER_LATE_FEE_RATE_MS) : void 0) ?? 0;
@@ -10688,7 +10743,8 @@ var YieldseekerAgent = class {
10688
10743
  if (asset !== void 0) this.assertAsset(asset);
10689
10744
  const missingAssets = /* @__PURE__ */ new Set();
10690
10745
  const contexts = await this.loadPortfolio(state, chainId, { asset, allowMissingPositions: true, missingAssets });
10691
- 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] }));
10692
10748
  for (const [index, context] of contexts.entries()) {
10693
10749
  const read2 = balance.readMetadata[index];
10694
10750
  this.balanceContexts.set(read2, { context, generation: this.readGeneration });
@@ -10795,30 +10851,173 @@ var YieldseekerAgent = class {
10795
10851
  }
10796
10852
  /**
10797
10853
  * Tells Yieldseeker a deposit landed (`deposit-made`), so the agent allocates
10798
- * it now instead of on its next 30-minute check. Yieldseeker decides whether
10799
- * anything moves (the funding minimum, a deployed agent, no manual
10800
- * withdrawal in the last hour). Uses the agent this session already knows
10801
- * for the asset and the saved sign-in only: never prompts, never retries,
10802
- * never throws.
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`.
10803
10865
  */
10804
- async depositConfirmed(state, chainId, evidence) {
10866
+ async depositConfirmed(state, chainId, evidence, onNotice) {
10867
+ let attempts = 0;
10805
10868
  try {
10806
10869
  const asset = String(evidence.token).toUpperCase();
10807
10870
  if (!this.supportedChainIds.includes(chainId) || !(asset in YIELDSEEKER_ASSET_METADATA))
10808
10871
  return { notified: false, reason: "UNSUPPORTED" };
10809
- 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));
10810
10874
  if (!context || !evidence.agentWallet || context.wallet.walletAddress.toLowerCase() !== evidence.agentWallet.toLowerCase())
10811
10875
  return { notified: false, reason: "NO_AGENT" };
10812
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 {
10813
10918
  await this.walletRequest(
10814
10919
  state,
10815
10920
  chainId,
10816
10921
  this.agentPath(context, "deposit-made"),
10817
10922
  { method: "POST", body: {}, promptless: true }
10818
10923
  );
10819
- return { notified: true };
10924
+ return { ok: true };
10820
10925
  } catch (error) {
10821
- 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;
10822
11021
  }
10823
11022
  }
10824
11023
  async getFundingWallet(state, chainId, asset) {
@@ -12150,7 +12349,7 @@ var YieldseekerAgent = class {
12150
12349
  this.portfolioVersions.set(contextKey, version);
12151
12350
  if (!snapshotOnly) this.liquidityVersions.set(contextKey, version);
12152
12351
  this.snapshotFailures.delete(contextKey);
12153
- const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12352
+ const kinds = !snapshotOnly ? ["snapshot", "positions", "historic", "actions", "idle"] : keepPositions ? ["snapshot"] : ["snapshot", "positions"];
12154
12353
  for (const kind of kinds) {
12155
12354
  const key2 = `${kind}:${contextKey}`;
12156
12355
  if (snapshotOnly && kind === "positions" && this.pendingReads.has(key2)) continue;
@@ -16028,6 +16227,47 @@ function withWalletConnectSwitch(provider) {
16028
16227
  });
16029
16228
  }
16030
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
+
16031
16271
  // src/lib/sponsored-calls-deposit.ts
16032
16272
  import { encodeFunctionData as encodeFunctionData5, erc20Abi as erc20Abi6, toHex as toHex3 } from "viem";
16033
16273
  var DEFAULT_POLL_INTERVAL_MS = 1500;
@@ -16603,7 +16843,7 @@ var OwneySDK = class {
16603
16843
  if (revision !== this.connectionRevision)
16604
16844
  throw new OwneyError("NOT_CONNECTED", "Wallet connection changed while connecting.");
16605
16845
  this.state = {
16606
- provider: withWalletConnectSwitch(provider),
16846
+ provider: withOneWalletPrompt(withWalletConnectSwitch(provider)),
16607
16847
  walletAddress,
16608
16848
  chainId: null
16609
16849
  };
@@ -18026,6 +18266,11 @@ var OwneySDK = class {
18026
18266
  * deposit's ledger operation when there is one. In the background: never
18027
18267
  * throws and never delays the deposit. A missed notice only leaves the
18028
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`.
18029
18274
  */
18030
18275
  announceDepositConfirmed(state, chainId, evidence, ledgerOp) {
18031
18276
  try {
@@ -18038,12 +18283,18 @@ var OwneySDK = class {
18038
18283
  this.announcedDeposits.add(key2);
18039
18284
  if (this.announcedDeposits.size > 256) this.announcedDeposits.delete(this.announcedDeposits.values().next().value);
18040
18285
  const legKey = `agent:${evidence.agentId}`;
18041
- void Promise.resolve().then(() => agent.depositConfirmed(state, chainId, evidence)).then((notice) => notice, () => ({ notified: false, reason: "ERROR" })).then((notice) => {
18286
+ const record2 = (type, notice) => {
18042
18287
  try {
18043
- ledgerOp?.event?.("provider.deposit_notified", { legKey, ...notice });
18288
+ ledgerOp?.event?.(type, { legKey, ...notice });
18044
18289
  } catch {
18045
18290
  }
18046
- });
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));
18047
18298
  } catch {
18048
18299
  }
18049
18300
  }
@@ -19533,6 +19784,7 @@ var OwneySDK = class {
19533
19784
  let record2;
19534
19785
  let ledgerOp;
19535
19786
  let hadDurableRecord = false;
19787
+ let nothingSent = false;
19536
19788
  const startedAt = Date.now();
19537
19789
  let confirmationDeadline = Infinity;
19538
19790
  const assertCurrent = () => {
@@ -19693,7 +19945,10 @@ var OwneySDK = class {
19693
19945
  } catch (error) {
19694
19946
  const details = error instanceof OwneyError ? error.details : void 0;
19695
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));
19696
- 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
+ }
19697
19952
  throw new OwneyError(
19698
19953
  "WITHDRAW_SWAP_INCOMPLETE",
19699
19954
  "The withdrawal did not complete for swapping. No swap was submitted. Check Activity and your remaining balances.",
@@ -19861,7 +20116,11 @@ var OwneySDK = class {
19861
20116
  if (record2.recovery && outcome === "not-submitted") record2.recovery.phase = "ready";
19862
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";
19863
20118
  if (record2.recovery) record2.recovery.reason = typeof details?.reason === "string" ? details.reason : void 0;
19864
- 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);
19865
20124
  }
19866
20125
  this.ledgerFailed(ledgerOp, error);
19867
20126
  throw error;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owney/sdk",
3
- "version": "0.7.32-beta.7",
3
+ "version": "0.7.32-beta.8",
4
4
  "type": "module",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.js",