@augustdigital/sdk 9.9.0 → 9.10.1

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.
@@ -35,3 +35,17 @@
35
35
  * @internal
36
36
  */
37
37
  export declare function mapWithConcurrency<TIn, TOut>(items: readonly TIn[], limit: number, task: (item: TIn, index: number) => Promise<TOut>): Promise<TOut[]>;
38
+ /**
39
+ * Race a promise against a timeout so a hung call can't block indefinitely. The
40
+ * timer is always cleared, so a fast-resolving promise leaves nothing pending.
41
+ *
42
+ * @param promise - The call to bound. It keeps running after a timeout; only
43
+ * the wait is abandoned.
44
+ * @param ms - Timeout in milliseconds. Values below 0 are treated as 0.
45
+ * @param label - Names the call in the rejection message.
46
+ * @returns What `promise` resolves to.
47
+ * @throws `Error("<label> timed out after <ms>ms")` on timeout, or whatever
48
+ * `promise` rejects with.
49
+ * @internal
50
+ */
51
+ export declare function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T>;
@@ -10,6 +10,7 @@
10
10
  */
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.mapWithConcurrency = mapWithConcurrency;
13
+ exports.withTimeout = withTimeout;
13
14
  /**
14
15
  * Map over `items` running at most `limit` tasks at a time.
15
16
  *
@@ -55,4 +56,24 @@ async function mapWithConcurrency(items, limit, task) {
55
56
  await Promise.all(Array.from({ length: width }, worker));
56
57
  return results;
57
58
  }
59
+ /**
60
+ * Race a promise against a timeout so a hung call can't block indefinitely. The
61
+ * timer is always cleared, so a fast-resolving promise leaves nothing pending.
62
+ *
63
+ * @param promise - The call to bound. It keeps running after a timeout; only
64
+ * the wait is abandoned.
65
+ * @param ms - Timeout in milliseconds. Values below 0 are treated as 0.
66
+ * @param label - Names the call in the rejection message.
67
+ * @returns What `promise` resolves to.
68
+ * @throws `Error("<label> timed out after <ms>ms")` on timeout, or whatever
69
+ * `promise` rejects with.
70
+ * @internal
71
+ */
72
+ function withTimeout(promise, ms, label) {
73
+ let timer;
74
+ const timeout = new Promise((_resolve, reject) => {
75
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), Math.max(0, ms));
76
+ });
77
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
78
+ }
58
79
  //# sourceMappingURL=concurrency.js.map
@@ -311,6 +311,16 @@ export interface PnlHistoryConsistencyParams {
311
311
  * (subgraph deposits or LayerZero cross-chain deposits).
312
312
  */
313
313
  hasDeposits: boolean;
314
+ /**
315
+ * Whether the indexed deposits explain every share mint to the wallet (see
316
+ * {@link historyCoversMints}). Defaults to `true`.
317
+ */
318
+ mintsMatchHistory?: boolean;
319
+ /**
320
+ * Shares received by peer transfer, priced in raw base units (asset
321
+ * decimals) by {@link transferCostBasis}. Defaults to zero.
322
+ */
323
+ receivedByTransferRaw?: bigint;
314
324
  /** Total withdrawn, in raw base units (asset decimals). */
315
325
  totalWithdrawnRaw: bigint;
316
326
  /** Current on-chain position value, in raw base units (asset decimals). */
@@ -326,9 +336,14 @@ export interface PnlHistoryConsistencyParams {
326
336
  * position as pure profit — a plausible-looking but wrong number.
327
337
  *
328
338
  * This guard rejects exactly that state: a non-zero position with no recorded
329
- * deposits *and* no recorded withdrawals. Any of the following is treated as
330
- * consistent and passes:
339
+ * deposits, no shares received by transfer *and* no recorded withdrawals. It
340
+ * also rejects a non-zero position with no recorded deposits when a share mint
341
+ * to the wallet has no matching deposit (`mintsMatchHistory: false`): the mint
342
+ * proves a deposit the history failed to return, so neither a peer transfer
343
+ * nor a withdrawal makes the cost basis complete. Otherwise, any of the
344
+ * following is treated as consistent and passes:
331
345
  * - deposits are present (the normal, computable case);
346
+ * - shares were received by transfer and priced (see {@link transferCostBasis});
332
347
  * - withdrawals are present (a fully-exited-then-re-entered position is still
333
348
  * computable — the withdrawal records prove history loaded);
334
349
  * - the current position is zero (the wallet never interacted or fully exited,
@@ -338,15 +353,17 @@ export interface PnlHistoryConsistencyParams {
338
353
  * path with no added latency.
339
354
  *
340
355
  * Shares received by a direct token transfer (never deposited, never withdrew)
341
- * reach this guard as deposits: {@link getVaultUserLifetimePnl} prices them
342
- * with {@link transferCostBasis} first. The guard still throws for such a
343
- * wallet when its transfers cannot be read or priced.
356
+ * reach this guard as `receivedByTransferRaw`: {@link getVaultUserLifetimePnl}
357
+ * prices them with {@link transferCostBasis} first. The guard still throws for
358
+ * such a wallet when its transfers cannot be read or priced, or when a share
359
+ * mint to it has no indexed deposit.
344
360
  *
345
361
  * @param params - See {@link PnlHistoryConsistencyParams}.
346
362
  * @returns `void` when the history is consistent.
347
363
  * @throws {@link AugustHistoryUnavailableError} with code `HISTORY_UNAVAILABLE`
348
- * and `context: { vault, wallet }` when a non-zero position has neither
349
- * deposits nor withdrawals recorded. The message carries the
364
+ * and `context: { vault, wallet }` when a non-zero position has no deposits
365
+ * recorded and either a share mint without a matching deposit or neither
366
+ * received shares nor withdrawals. The message carries the
350
367
  * `#getVaultUserLifetimePnl::<vault>::<wallet>` prefix so it groups with the
351
368
  * other errors leaving the getter.
352
369
  * @example
@@ -355,12 +372,14 @@ export interface PnlHistoryConsistencyParams {
355
372
  * vault,
356
373
  * wallet,
357
374
  * hasDeposits: depositsByAsset.size > 0,
375
+ * mintsMatchHistory,
376
+ * receivedByTransferRaw: costBasis.receivedByTransferRaw,
358
377
  * totalWithdrawnRaw,
359
378
  * currentPositionRaw: currentPositionValue.raw,
360
379
  * });
361
380
  * ```
362
381
  */
363
- export declare function assertPnlHistoryConsistent({ vault, wallet, hasDeposits, totalWithdrawnRaw, currentPositionRaw, }: PnlHistoryConsistencyParams): void;
382
+ export declare function assertPnlHistoryConsistent({ vault, wallet, hasDeposits, mintsMatchHistory, receivedByTransferRaw, totalWithdrawnRaw, currentPositionRaw, }: PnlHistoryConsistencyParams): void;
364
383
  /** Inputs the lifetime-PnL price guard inspects. */
365
384
  export interface PnlTokenPriceParams {
366
385
  /** Vault contract address, used for the error message and context. */
@@ -728,7 +747,9 @@ export interface PnlCostBasis {
728
747
  *
729
748
  * A depositor whose history misses a mint ({@link historyCoversMints}) is the
730
749
  * exception: its transfers do not count, so the result matches what the getter
731
- * returned before transfers counted for depositors. On a LayerZero OVault the
750
+ * returned before transfers counted for depositors. A wallet with no deposit
751
+ * still gets a basis here when its history misses a mint, but
752
+ * {@link assertPnlHistoryConsistent} rejects it. On a LayerZero OVault the
732
753
  * caller leaves the hub composer and share OFT out of the transfers (see
733
754
  * {@link selectPeerTransfers}): the composer's deliveries are already counted
734
755
  * as LayerZero deposits, and shares bridged to a spoke chain still count in the
@@ -789,16 +810,18 @@ export declare function pnlCostBasis({ depositedRaw, withdrawnAssetsRaw, hasDepo
789
810
  * shares add to `totalDeposited` (and are reported again as
790
811
  * `receivedByTransfer`), sent shares add to `totalWithdrawn`. This holds
791
812
  * alongside indexed deposits, so a wallet that received shares and also
792
- * deposited is not credited with the received shares as profit. LayerZero
793
- * OVaults count transfers only when history holds no deposit, because their
794
- * composer delivers cross-chain deposits by transfer.
813
+ * deposited is not credited with the received shares as profit. On LayerZero
814
+ * OVaults, transfers from or to the hub composer and share OFT do not count,
815
+ * because the composer delivers cross-chain deposits by transfer and those
816
+ * are already counted as LayerZero deposits.
795
817
  *
796
818
  * Gaps in the indexed history: a share mint with no `Deposit` event counts as
797
819
  * a deposit of the assets in its `ReserveDeposit` event
798
820
  * ({@link selectReserveDeposits}; High Growth ETH emits it for Kelp gain-adapter
799
821
  * deposits), and a withdrawal request the vault logged twice counts once
800
822
  * ({@link countWithdrawalRequestsOnce}). Transfers fold in for a depositor only
801
- * once every mint is explained.
823
+ * once every mint is explained. A wallet with no indexed deposit and a mint
824
+ * that no deposit explains throws `HISTORY_UNAVAILABLE`.
802
825
  *
803
826
  * Tokenized Vault V2 redemptions carry only shares, so a settled one counts at
804
827
  * the assets the vault paid, or at the share ratio on its claim date when the
@@ -813,9 +836,8 @@ export declare function pnlCostBasis({ depositedRaw, withdrawnAssetsRaw, hasDepo
813
836
  * for a Tokenized Vault V2 wallet with redemption requests, a `lagDuration()`
814
837
  * read plus one backend timeseries request. A timeseries window with no usable
815
838
  * ratio (a closed vault whose history stopped earlier) is read again in full,
816
- * so the latest earlier day still prices it. For
817
- * non-LayerZero vaults the transfer query runs in parallel with the history
818
- * read; for LayerZero vaults it runs only when history holds no deposit.
839
+ * so the latest earlier day still prices it. The transfer query runs for
840
+ * every vault, in parallel with the history read.
819
841
  *
820
842
  * @param vault - Vault contract address
821
843
  * @param wallet - User wallet address
@@ -823,7 +845,8 @@ export declare function pnlCostBasis({ depositedRaw, withdrawnAssetsRaw, hasDepo
823
845
  * @returns Lifetime PnL data in both native token and USD
824
846
  * @throws {@link AugustHistoryUnavailableError} (`HISTORY_UNAVAILABLE`) when a
825
847
  * live position has no indexed deposits, withdrawals or priceable share
826
- * transfers.
848
+ * transfers, or has no indexed deposit while a share mint to the wallet has
849
+ * no matching deposit.
827
850
  * @throws {@link AugustPriceUnavailableError} (`PRICE_UNAVAILABLE`) when the
828
851
  * underlying asset has no USD price, or `asset()` cannot be read.
829
852
  */
@@ -641,11 +641,14 @@ async function getVaultAllocations(vault, options, tokenizedVault) {
641
641
  // afterwards, and a borrower on a chain with portfolio coverage would otherwise
642
642
  // have its rows silently dropped rather than double-counted.
643
643
  let untangledTokenCount = 0;
644
+ let vaultOctav;
644
645
  const borrowerPortfolioFetchers = {
645
646
  solana: async (borrower) => {
646
- const portfolios = await (0, octavfi_1.fetchOctavfiPortfolios)([borrower]);
647
- return portfolios.length > 0
648
- ? (0, octavfi_1.transformOctavfiToDebank)(portfolios[0])
647
+ vaultOctav ??= (0, octavfi_1.fetchVaultOctavResponse)(vault, options?.headers);
648
+ const response = await vaultOctav;
649
+ const portfolio = response ? response[borrower] : undefined;
650
+ return portfolio && !('error' in portfolio)
651
+ ? (0, octavfi_1.transformOctavfiToDebank)(portfolio)
649
652
  : null;
650
653
  },
651
654
  };
@@ -2270,9 +2273,14 @@ async function getYieldLastRealizedOn({ vault, options, }) {
2270
2273
  * position as pure profit — a plausible-looking but wrong number.
2271
2274
  *
2272
2275
  * This guard rejects exactly that state: a non-zero position with no recorded
2273
- * deposits *and* no recorded withdrawals. Any of the following is treated as
2274
- * consistent and passes:
2276
+ * deposits, no shares received by transfer *and* no recorded withdrawals. It
2277
+ * also rejects a non-zero position with no recorded deposits when a share mint
2278
+ * to the wallet has no matching deposit (`mintsMatchHistory: false`): the mint
2279
+ * proves a deposit the history failed to return, so neither a peer transfer
2280
+ * nor a withdrawal makes the cost basis complete. Otherwise, any of the
2281
+ * following is treated as consistent and passes:
2275
2282
  * - deposits are present (the normal, computable case);
2283
+ * - shares were received by transfer and priced (see {@link transferCostBasis});
2276
2284
  * - withdrawals are present (a fully-exited-then-re-entered position is still
2277
2285
  * computable — the withdrawal records prove history loaded);
2278
2286
  * - the current position is zero (the wallet never interacted or fully exited,
@@ -2282,15 +2290,17 @@ async function getYieldLastRealizedOn({ vault, options, }) {
2282
2290
  * path with no added latency.
2283
2291
  *
2284
2292
  * Shares received by a direct token transfer (never deposited, never withdrew)
2285
- * reach this guard as deposits: {@link getVaultUserLifetimePnl} prices them
2286
- * with {@link transferCostBasis} first. The guard still throws for such a
2287
- * wallet when its transfers cannot be read or priced.
2293
+ * reach this guard as `receivedByTransferRaw`: {@link getVaultUserLifetimePnl}
2294
+ * prices them with {@link transferCostBasis} first. The guard still throws for
2295
+ * such a wallet when its transfers cannot be read or priced, or when a share
2296
+ * mint to it has no indexed deposit.
2288
2297
  *
2289
2298
  * @param params - See {@link PnlHistoryConsistencyParams}.
2290
2299
  * @returns `void` when the history is consistent.
2291
2300
  * @throws {@link AugustHistoryUnavailableError} with code `HISTORY_UNAVAILABLE`
2292
- * and `context: { vault, wallet }` when a non-zero position has neither
2293
- * deposits nor withdrawals recorded. The message carries the
2301
+ * and `context: { vault, wallet }` when a non-zero position has no deposits
2302
+ * recorded and either a share mint without a matching deposit or neither
2303
+ * received shares nor withdrawals. The message carries the
2294
2304
  * `#getVaultUserLifetimePnl::<vault>::<wallet>` prefix so it groups with the
2295
2305
  * other errors leaving the getter.
2296
2306
  * @example
@@ -2299,16 +2309,23 @@ async function getYieldLastRealizedOn({ vault, options, }) {
2299
2309
  * vault,
2300
2310
  * wallet,
2301
2311
  * hasDeposits: depositsByAsset.size > 0,
2312
+ * mintsMatchHistory,
2313
+ * receivedByTransferRaw: costBasis.receivedByTransferRaw,
2302
2314
  * totalWithdrawnRaw,
2303
2315
  * currentPositionRaw: currentPositionValue.raw,
2304
2316
  * });
2305
2317
  * ```
2306
2318
  */
2307
- function assertPnlHistoryConsistent({ vault, wallet, hasDeposits, totalWithdrawnRaw, currentPositionRaw, }) {
2308
- const positionExists = currentPositionRaw > BigInt(0);
2309
- const noHistory = !hasDeposits && totalWithdrawnRaw === BigInt(0);
2310
- if (positionExists && noHistory) {
2311
- throw new errors_1.AugustHistoryUnavailableError(`#getVaultUserLifetimePnl::${vault}::${wallet}:transaction history unavailable — a live position exists but no deposits or withdrawals were indexed, so lifetime PnL cannot be computed without over-reporting the entire position as profit`, { context: { vault, wallet } });
2319
+ function assertPnlHistoryConsistent({ vault, wallet, hasDeposits, mintsMatchHistory = true, receivedByTransferRaw = BigInt(0), totalWithdrawnRaw, currentPositionRaw, }) {
2320
+ if (currentPositionRaw <= BigInt(0) || hasDeposits)
2321
+ return;
2322
+ const missingDeposit = !mintsMatchHistory;
2323
+ const noHistory = receivedByTransferRaw === BigInt(0) && totalWithdrawnRaw === BigInt(0);
2324
+ if (missingDeposit || noHistory) {
2325
+ const reason = missingDeposit
2326
+ ? 'a share mint has no indexed deposit'
2327
+ : 'no deposits or withdrawals were indexed';
2328
+ throw new errors_1.AugustHistoryUnavailableError(`#getVaultUserLifetimePnl::${vault}::${wallet}:transaction history unavailable — a live position exists but ${reason}, so lifetime PnL cannot be computed without over-reporting the entire position as profit`, { context: { vault, wallet } });
2312
2329
  }
2313
2330
  }
2314
2331
  /**
@@ -2710,7 +2727,9 @@ function settleV2Redemptions({ history, lagDuration, ratios, now, }) {
2710
2727
  *
2711
2728
  * A depositor whose history misses a mint ({@link historyCoversMints}) is the
2712
2729
  * exception: its transfers do not count, so the result matches what the getter
2713
- * returned before transfers counted for depositors. On a LayerZero OVault the
2730
+ * returned before transfers counted for depositors. A wallet with no deposit
2731
+ * still gets a basis here when its history misses a mint, but
2732
+ * {@link assertPnlHistoryConsistent} rejects it. On a LayerZero OVault the
2714
2733
  * caller leaves the hub composer and share OFT out of the transfers (see
2715
2734
  * {@link selectPeerTransfers}): the composer's deliveries are already counted
2716
2735
  * as LayerZero deposits, and shares bridged to a spoke chain still count in the
@@ -2852,16 +2871,18 @@ async function readV2Redemptions(provider, vault, history, headers) {
2852
2871
  * shares add to `totalDeposited` (and are reported again as
2853
2872
  * `receivedByTransfer`), sent shares add to `totalWithdrawn`. This holds
2854
2873
  * alongside indexed deposits, so a wallet that received shares and also
2855
- * deposited is not credited with the received shares as profit. LayerZero
2856
- * OVaults count transfers only when history holds no deposit, because their
2857
- * composer delivers cross-chain deposits by transfer.
2874
+ * deposited is not credited with the received shares as profit. On LayerZero
2875
+ * OVaults, transfers from or to the hub composer and share OFT do not count,
2876
+ * because the composer delivers cross-chain deposits by transfer and those
2877
+ * are already counted as LayerZero deposits.
2858
2878
  *
2859
2879
  * Gaps in the indexed history: a share mint with no `Deposit` event counts as
2860
2880
  * a deposit of the assets in its `ReserveDeposit` event
2861
2881
  * ({@link selectReserveDeposits}; High Growth ETH emits it for Kelp gain-adapter
2862
2882
  * deposits), and a withdrawal request the vault logged twice counts once
2863
2883
  * ({@link countWithdrawalRequestsOnce}). Transfers fold in for a depositor only
2864
- * once every mint is explained.
2884
+ * once every mint is explained. A wallet with no indexed deposit and a mint
2885
+ * that no deposit explains throws `HISTORY_UNAVAILABLE`.
2865
2886
  *
2866
2887
  * Tokenized Vault V2 redemptions carry only shares, so a settled one counts at
2867
2888
  * the assets the vault paid, or at the share ratio on its claim date when the
@@ -2876,9 +2897,8 @@ async function readV2Redemptions(provider, vault, history, headers) {
2876
2897
  * for a Tokenized Vault V2 wallet with redemption requests, a `lagDuration()`
2877
2898
  * read plus one backend timeseries request. A timeseries window with no usable
2878
2899
  * ratio (a closed vault whose history stopped earlier) is read again in full,
2879
- * so the latest earlier day still prices it. For
2880
- * non-LayerZero vaults the transfer query runs in parallel with the history
2881
- * read; for LayerZero vaults it runs only when history holds no deposit.
2900
+ * so the latest earlier day still prices it. The transfer query runs for
2901
+ * every vault, in parallel with the history read.
2882
2902
  *
2883
2903
  * @param vault - Vault contract address
2884
2904
  * @param wallet - User wallet address
@@ -2886,7 +2906,8 @@ async function readV2Redemptions(provider, vault, history, headers) {
2886
2906
  * @returns Lifetime PnL data in both native token and USD
2887
2907
  * @throws {@link AugustHistoryUnavailableError} (`HISTORY_UNAVAILABLE`) when a
2888
2908
  * live position has no indexed deposits, withdrawals or priceable share
2889
- * transfers.
2909
+ * transfers, or has no indexed deposit while a share mint to the wallet has
2910
+ * no matching deposit.
2890
2911
  * @throws {@link AugustPriceUnavailableError} (`PRICE_UNAVAILABLE`) when the
2891
2912
  * underlying asset has no USD price, or `asset()` cannot be read.
2892
2913
  */
@@ -3256,7 +3277,9 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
3256
3277
  assertPnlHistoryConsistent({
3257
3278
  vault,
3258
3279
  wallet,
3259
- hasDeposits: hasDeposits || costBasis.receivedByTransferRaw > BigInt(0),
3280
+ hasDeposits,
3281
+ mintsMatchHistory,
3282
+ receivedByTransferRaw: costBasis.receivedByTransferRaw,
3260
3283
  totalWithdrawnRaw: costBasis.withdrawnAssetsRaw,
3261
3284
  currentPositionRaw: BigInt(currentPositionValue.raw),
3262
3285
  });