@gearbox-protocol/sdk 14.11.3 → 14.12.0-next.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.
Files changed (180) hide show
  1. package/dist/cjs/common-utils/utils/index.js +2 -0
  2. package/dist/cjs/{history/trace-utils.js → common-utils/utils/trace.js} +62 -5
  3. package/dist/cjs/dev/index.js +3 -1
  4. package/dist/cjs/dev/verifyTestnet.js +52 -0
  5. package/dist/cjs/history/assembleOperations.js +6 -6
  6. package/dist/cjs/history/classifyMulticallOperations.js +31 -25
  7. package/dist/cjs/history/index.js +0 -2
  8. package/dist/cjs/history/parseCreditAccountTransaction.js +5 -6
  9. package/dist/cjs/history/toLegacyOperation.js +5 -1
  10. package/dist/cjs/plugins/adapters/contracts/AbstractAdapter.js +25 -37
  11. package/dist/cjs/plugins/adapters/contracts/AccountMigratorAdapterContract.js +9 -0
  12. package/dist/cjs/{history/internal-types.js → plugins/adapters/transfers.js} +2 -2
  13. package/dist/cjs/preview/index.js +28 -0
  14. package/dist/cjs/preview/package.json +1 -0
  15. package/dist/cjs/preview/parse/classifyInnerOperations.js +92 -0
  16. package/dist/cjs/preview/parse/errors.js +47 -0
  17. package/dist/cjs/preview/parse/extractExpectedBalanceChanges.js +48 -0
  18. package/dist/cjs/preview/parse/index.js +34 -0
  19. package/dist/cjs/preview/parse/parseFacadeOperationCalldata.js +115 -0
  20. package/dist/cjs/preview/parse/parseOperationCalldata.js +46 -0
  21. package/dist/cjs/preview/parse/parsePoolOperationCalldata.js +77 -0
  22. package/dist/cjs/{history/inner-operations.js → preview/parse/types-adapters.js} +2 -2
  23. package/dist/cjs/preview/parse/types-facades.js +16 -0
  24. package/dist/cjs/preview/parse/types-pools.js +16 -0
  25. package/dist/cjs/preview/parse/types.js +37 -0
  26. package/dist/cjs/preview/prerequisites/AllowancePrerequisite.js +78 -0
  27. package/dist/cjs/preview/prerequisites/BalancePrerequisite.js +77 -0
  28. package/dist/cjs/preview/prerequisites/Prerequisite.js +85 -0
  29. package/dist/cjs/preview/prerequisites/buildPrerequisites.js +187 -0
  30. package/dist/cjs/preview/prerequisites/index.js +34 -0
  31. package/dist/cjs/preview/prerequisites/prepareAction.js +48 -0
  32. package/dist/cjs/preview/prerequisites/runPrerequisites.js +71 -0
  33. package/dist/cjs/preview/prerequisites/types.js +16 -0
  34. package/dist/cjs/preview/simulate/constants.js +28 -0
  35. package/dist/cjs/preview/simulate/errors.js +98 -0
  36. package/dist/cjs/preview/simulate/extractERC20Transfers.js +47 -0
  37. package/dist/cjs/preview/simulate/holders.js +45 -0
  38. package/dist/cjs/preview/simulate/index.js +40 -0
  39. package/dist/cjs/preview/simulate/simulateFacadeOperation.js +30 -0
  40. package/dist/cjs/preview/simulate/simulateOperation.js +37 -0
  41. package/dist/cjs/preview/simulate/simulatePoolOpMulticall.js +155 -0
  42. package/dist/cjs/preview/simulate/simulatePoolOpV1.js +106 -0
  43. package/dist/cjs/preview/simulate/simulatePoolOperation.js +62 -0
  44. package/dist/cjs/preview/simulate/types.js +16 -0
  45. package/dist/cjs/{history → preview/trace}/errors.js +0 -26
  46. package/dist/cjs/preview/trace/extractAdapterCallTraces.js +58 -0
  47. package/dist/cjs/{history → preview/trace}/extractTransfers.js +9 -12
  48. package/dist/cjs/{history → preview/trace}/findFacadeCalls.js +3 -3
  49. package/dist/cjs/preview/trace/index.js +30 -0
  50. package/dist/cjs/preview/trace/types.js +16 -0
  51. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +154 -0
  52. package/dist/esm/common-utils/utils/index.js +1 -0
  53. package/dist/esm/common-utils/utils/trace.js +93 -0
  54. package/dist/esm/dev/index.js +1 -0
  55. package/dist/esm/dev/verifyTestnet.js +27 -0
  56. package/dist/esm/history/assembleOperations.js +8 -6
  57. package/dist/esm/history/classifyMulticallOperations.js +29 -23
  58. package/dist/esm/history/index.js +0 -1
  59. package/dist/esm/history/parseCreditAccountTransaction.js +3 -4
  60. package/dist/esm/history/toLegacyOperation.js +5 -1
  61. package/dist/esm/plugins/adapters/contracts/AbstractAdapter.js +28 -38
  62. package/dist/esm/plugins/adapters/contracts/AccountMigratorAdapterContract.js +9 -0
  63. package/dist/esm/preview/index.js +4 -0
  64. package/dist/esm/preview/package.json +1 -0
  65. package/dist/esm/preview/parse/classifyInnerOperations.js +68 -0
  66. package/dist/esm/preview/parse/errors.js +22 -0
  67. package/dist/esm/preview/parse/extractExpectedBalanceChanges.js +24 -0
  68. package/dist/esm/preview/parse/index.js +7 -0
  69. package/dist/esm/preview/parse/parseFacadeOperationCalldata.js +91 -0
  70. package/dist/esm/preview/parse/parseOperationCalldata.js +25 -0
  71. package/dist/esm/preview/parse/parsePoolOperationCalldata.js +53 -0
  72. package/dist/esm/preview/parse/types-facades.js +0 -0
  73. package/dist/esm/preview/parse/types-pools.js +0 -0
  74. package/dist/esm/preview/parse/types.js +9 -0
  75. package/dist/esm/preview/prerequisites/AllowancePrerequisite.js +57 -0
  76. package/dist/esm/preview/prerequisites/BalancePrerequisite.js +56 -0
  77. package/dist/esm/preview/prerequisites/Prerequisite.js +63 -0
  78. package/dist/esm/preview/prerequisites/buildPrerequisites.js +163 -0
  79. package/dist/esm/preview/prerequisites/index.js +7 -0
  80. package/dist/esm/preview/prerequisites/prepareAction.js +23 -0
  81. package/dist/esm/preview/prerequisites/runPrerequisites.js +47 -0
  82. package/dist/esm/preview/prerequisites/types.js +0 -0
  83. package/dist/esm/preview/simulate/constants.js +4 -0
  84. package/dist/esm/preview/simulate/errors.js +75 -0
  85. package/dist/esm/preview/simulate/extractERC20Transfers.js +23 -0
  86. package/dist/esm/preview/simulate/holders.js +21 -0
  87. package/dist/esm/preview/simulate/index.js +12 -0
  88. package/dist/esm/preview/simulate/simulateFacadeOperation.js +6 -0
  89. package/dist/esm/preview/simulate/simulateOperation.js +13 -0
  90. package/dist/esm/preview/simulate/simulatePoolOpMulticall.js +130 -0
  91. package/dist/esm/preview/simulate/simulatePoolOpV1.js +82 -0
  92. package/dist/esm/preview/simulate/simulatePoolOperation.js +41 -0
  93. package/dist/esm/preview/simulate/types.js +0 -0
  94. package/dist/esm/{history → preview/trace}/errors.js +0 -24
  95. package/dist/esm/preview/trace/extractAdapterCallTraces.js +40 -0
  96. package/dist/esm/{history → preview/trace}/extractTransfers.js +9 -12
  97. package/dist/esm/{history → preview/trace}/findFacadeCalls.js +4 -2
  98. package/dist/esm/preview/trace/index.js +5 -0
  99. package/dist/esm/preview/trace/types.js +0 -0
  100. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +154 -0
  101. package/dist/types/common-utils/utils/index.d.ts +1 -0
  102. package/dist/types/common-utils/utils/trace.d.ts +73 -0
  103. package/dist/types/dev/index.d.ts +1 -0
  104. package/dist/types/dev/verifyTestnet.d.ts +24 -0
  105. package/dist/types/history/assembleOperations.d.ts +11 -6
  106. package/dist/types/history/classifyMulticallOperations.d.ts +21 -9
  107. package/dist/types/history/index.d.ts +0 -1
  108. package/dist/types/history/mapOperations.d.ts +7 -9
  109. package/dist/types/history/types.d.ts +22 -71
  110. package/dist/types/plugins/adapters/contracts/AbstractAdapter.d.ts +16 -17
  111. package/dist/types/plugins/adapters/contracts/AccountMigratorAdapterContract.d.ts +10 -1
  112. package/dist/types/plugins/adapters/contracts/ConvexV1BaseRewardPoolAdapterContract.d.ts +1 -1
  113. package/dist/types/plugins/adapters/contracts/ConvexV1BoosterAdapterContract.d.ts +1 -1
  114. package/dist/types/plugins/adapters/contracts/Curve2AssetsAdapterContract.d.ts +1 -1
  115. package/dist/types/plugins/adapters/contracts/Curve3AssetsAdapterContract.d.ts +1 -1
  116. package/dist/types/plugins/adapters/contracts/Curve4AssetsAdapterContract.d.ts +1 -1
  117. package/dist/types/plugins/adapters/contracts/CurveV1AdapterDeposit.d.ts +1 -1
  118. package/dist/types/plugins/adapters/contracts/CurveV1AdapterStETHContract.d.ts +1 -1
  119. package/dist/types/plugins/adapters/contracts/CurveV1StableNGAdapterContract.d.ts +1 -1
  120. package/dist/types/plugins/adapters/contracts/DaiUsdsAdapterContract.d.ts +1 -1
  121. package/dist/types/plugins/adapters/contracts/ERC4626AdapterContract.d.ts +1 -1
  122. package/dist/types/plugins/adapters/contracts/ERC4626ReferralAdapterContract.d.ts +1 -1
  123. package/dist/types/plugins/adapters/contracts/LidoV1AdapterContract.d.ts +1 -1
  124. package/dist/types/plugins/adapters/contracts/MellowDVVAdapterContract.d.ts +1 -1
  125. package/dist/types/plugins/adapters/contracts/MellowERC4626VaultAdapterContract.d.ts +1 -1
  126. package/dist/types/plugins/adapters/contracts/UniswapV2AdapterContract.d.ts +1 -1
  127. package/dist/types/plugins/adapters/contracts/UniswapV4AdapterContract.d.ts +1 -1
  128. package/dist/types/plugins/adapters/contracts/WstETHV1AdapterContract.d.ts +1 -1
  129. package/dist/types/plugins/adapters/transferHelpers.d.ts +1 -1
  130. package/dist/types/plugins/adapters/transfers.d.ts +17 -0
  131. package/dist/types/plugins/adapters/types.d.ts +8 -46
  132. package/dist/types/preview/index.d.ts +4 -0
  133. package/dist/types/preview/parse/classifyInnerOperations.d.ts +21 -0
  134. package/dist/types/preview/parse/errors.d.ts +17 -0
  135. package/dist/types/preview/parse/extractExpectedBalanceChanges.d.ts +22 -0
  136. package/dist/types/preview/parse/index.d.ts +7 -0
  137. package/dist/types/preview/parse/parseFacadeOperationCalldata.d.ts +19 -0
  138. package/dist/types/preview/parse/parseOperationCalldata.d.ts +23 -0
  139. package/dist/types/preview/parse/parsePoolOperationCalldata.d.ts +17 -0
  140. package/dist/types/preview/parse/types-adapters.d.ts +69 -0
  141. package/dist/types/preview/parse/types-facades.d.ts +158 -0
  142. package/dist/types/preview/parse/types-pools.d.ts +55 -0
  143. package/dist/types/preview/parse/types.d.ts +44 -0
  144. package/dist/types/preview/prerequisites/AllowancePrerequisite.d.ts +24 -0
  145. package/dist/types/preview/prerequisites/BalancePrerequisite.d.ts +23 -0
  146. package/dist/types/preview/prerequisites/Prerequisite.d.ts +60 -0
  147. package/dist/types/preview/prerequisites/buildPrerequisites.d.ts +16 -0
  148. package/dist/types/preview/prerequisites/index.d.ts +7 -0
  149. package/dist/types/preview/prerequisites/prepareAction.d.ts +52 -0
  150. package/dist/types/preview/prerequisites/runPrerequisites.d.ts +12 -0
  151. package/dist/types/preview/prerequisites/types.d.ts +78 -0
  152. package/dist/types/preview/simulate/constants.d.ts +6 -0
  153. package/dist/types/preview/simulate/errors.d.ts +51 -0
  154. package/dist/types/preview/simulate/extractERC20Transfers.d.ts +11 -0
  155. package/dist/types/preview/simulate/holders.d.ts +7 -0
  156. package/dist/types/preview/simulate/index.d.ts +9 -0
  157. package/dist/types/preview/simulate/simulateFacadeOperation.d.ts +25 -0
  158. package/dist/types/preview/simulate/simulateOperation.d.ts +20 -0
  159. package/dist/types/preview/simulate/simulatePoolOpMulticall.d.ts +28 -0
  160. package/dist/types/preview/simulate/simulatePoolOpV1.d.ts +14 -0
  161. package/dist/types/preview/simulate/simulatePoolOperation.d.ts +8 -0
  162. package/dist/types/preview/simulate/types.d.ts +79 -0
  163. package/dist/types/{history → preview/trace}/errors.d.ts +0 -10
  164. package/dist/types/preview/trace/extractAdapterCallTraces.d.ts +23 -0
  165. package/dist/types/{history → preview/trace}/extractTransfers.d.ts +14 -5
  166. package/dist/types/{history → preview/trace}/findFacadeCalls.d.ts +3 -2
  167. package/dist/types/preview/trace/index.d.ts +5 -0
  168. package/dist/types/preview/trace/types.d.ts +21 -0
  169. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +21 -1
  170. package/dist/types/sdk/accounts/types.d.ts +82 -0
  171. package/package.json +6 -1
  172. package/dist/cjs/history/extractProtocolCalls.js +0 -53
  173. package/dist/esm/history/extractProtocolCalls.js +0 -32
  174. package/dist/esm/history/trace-utils.js +0 -36
  175. package/dist/types/history/extractProtocolCalls.d.ts +0 -8
  176. package/dist/types/history/inner-operations.d.ts +0 -57
  177. package/dist/types/history/internal-types.d.ts +0 -47
  178. package/dist/types/history/trace-utils.d.ts +0 -12
  179. /package/dist/esm/{history/inner-operations.js → plugins/adapters/transfers.js} +0 -0
  180. /package/dist/esm/{history/internal-types.js → preview/parse/types-adapters.js} +0 -0
@@ -0,0 +1,24 @@
1
+ import { type Address, type ContractFunctionParameters } from "viem";
2
+ import { type MulticallCallResult, Prerequisite } from "./Prerequisite.js";
3
+ import type { PrerequisiteDetail, PrerequisiteResult } from "./types.js";
4
+ export interface AllowancePrerequisiteProps {
5
+ token: Address;
6
+ owner: Address;
7
+ spender: Address;
8
+ required: bigint;
9
+ title?: string;
10
+ id?: string;
11
+ }
12
+ /** Checks that `owner` granted `spender` an ERC-20 allowance >= `required`. */
13
+ export declare class AllowancePrerequisite extends Prerequisite<"allowance"> {
14
+ private readonly _id;
15
+ private readonly _title;
16
+ private readonly _detail;
17
+ constructor(props: AllowancePrerequisiteProps);
18
+ get id(): string;
19
+ get kind(): "allowance";
20
+ get title(): string;
21
+ get detail(): PrerequisiteDetail<"allowance">;
22
+ calls(): ContractFunctionParameters[];
23
+ resolve(slice: MulticallCallResult[]): PrerequisiteResult<"allowance">;
24
+ }
@@ -0,0 +1,23 @@
1
+ import { type Address, type ContractFunctionParameters } from "viem";
2
+ import { type MulticallCallResult, Prerequisite } from "./Prerequisite.js";
3
+ import type { PrerequisiteDetail, PrerequisiteResult } from "./types.js";
4
+ export interface BalancePrerequisiteProps {
5
+ token: Address;
6
+ owner: Address;
7
+ required: bigint;
8
+ title?: string;
9
+ id?: string;
10
+ }
11
+ /** Checks that `owner` holds an ERC-20 balance >= `required`. */
12
+ export declare class BalancePrerequisite extends Prerequisite<"balance"> {
13
+ private readonly _id;
14
+ private readonly _title;
15
+ private readonly _detail;
16
+ constructor(props: BalancePrerequisiteProps);
17
+ get id(): string;
18
+ get kind(): "balance";
19
+ get title(): string;
20
+ get detail(): PrerequisiteDetail<"balance">;
21
+ calls(): ContractFunctionParameters[];
22
+ resolve(slice: MulticallCallResult[]): PrerequisiteResult<"balance">;
23
+ }
@@ -0,0 +1,60 @@
1
+ import { type ContractFunctionParameters } from "viem";
2
+ import type { PrerequisiteContext, PrerequisiteDetail, PrerequisiteError, PrerequisiteKind, PrerequisiteResult } from "./types.js";
3
+ /**
4
+ * One entry of a viem `multicall({ allowFailure: true })` response: either a
5
+ * decoded `result` or the `error` that the call reverted with.
6
+ */
7
+ export type MulticallCallResult = {
8
+ status: "success";
9
+ result: unknown;
10
+ error?: undefined;
11
+ } | {
12
+ status: "failure";
13
+ result?: undefined;
14
+ error: Error;
15
+ };
16
+ /**
17
+ * Decodes an unknown error into a {@link PrerequisiteError} with a
18
+ * human-readable revert reason. Mirrors the SDK's `extractCallError`: walk the
19
+ * viem error chain for a {@link ContractFunctionRevertedError} and use its
20
+ * `errorName`, otherwise fall back to the error's short message / name.
21
+ */
22
+ export declare function toPrerequisiteError(cause: unknown): PrerequisiteError;
23
+ /**
24
+ * A single verifiable prerequisite for a transaction. Subclasses describe the
25
+ * on-chain reads they need ({@link calls}) and how to turn the multicall slice
26
+ * into a {@link PrerequisiteResult} ({@link resolve}).
27
+ *
28
+ * Identity (`id`, `kind`, `title`) and build-time `detail` are exposed as
29
+ * read-only accessors; subclasses back them with private fields. The shared
30
+ * {@link satisfiedResult}/{@link errorResult} helpers are `protected` so each
31
+ * subclass builds results consistently.
32
+ *
33
+ * The same instance can be verified standalone via {@link verify} or batched
34
+ * together with others by `verifyPrerequisites`.
35
+ */
36
+ export declare abstract class Prerequisite<K extends PrerequisiteKind> {
37
+ /** Stable identifier, used as a React key and for deduplication. */
38
+ abstract get id(): string;
39
+ /** Discriminant tying this check to its detail payload. */
40
+ abstract get kind(): K;
41
+ /** Human-readable label shown in the UI. */
42
+ abstract get title(): string;
43
+ /** Inputs known before reading the chain (no `actual` yet). */
44
+ abstract get detail(): PrerequisiteDetail<K>;
45
+ /** Contract reads this check needs (usually one). */
46
+ abstract calls(ctx: PrerequisiteContext): ContractFunctionParameters[];
47
+ /** Maps this check's slice of the multicall response into a result. */
48
+ abstract resolve(slice: MulticallCallResult[]): PrerequisiteResult<K>;
49
+ /**
50
+ * Verifies this prerequisite on its own using an `allowFailure` multicall.
51
+ * Prefer `verifyPrerequisites` to batch several checks into one round-trip.
52
+ */
53
+ verify(ctx: PrerequisiteContext): Promise<PrerequisiteResult<K>>;
54
+ /** Builds a successful result; `detail` carries the on-chain `actual`. */
55
+ protected satisfiedResult(satisfied: boolean, detail: PrerequisiteDetail<K>): PrerequisiteResult<K>;
56
+ /** Builds a failed result from a decoded read error. */
57
+ protected errorResult(error: PrerequisiteError): PrerequisiteResult<K>;
58
+ }
59
+ /** Any prerequisite regardless of its kind, used for heterogeneous lists. */
60
+ export type AnyPrerequisite = Prerequisite<PrerequisiteKind>;
@@ -0,0 +1,16 @@
1
+ import type { Operation } from "../parse/index.js";
2
+ import type { AnyPrerequisite } from "./Prerequisite.js";
3
+ import type { PrerequisiteContext } from "./types.js";
4
+ /**
5
+ * Derives the on-chain prerequisites for a parsed operation: the conditions
6
+ * that must hold for the call not to revert and that we can verify with the
7
+ * SDK (token approvals, wallet balances).
8
+ *
9
+ * Only *sender-actionable* prerequisites belong here: conditions the LP
10
+ * provider or borrower can fix themselves before retrying (e.g. approve a
11
+ * token, top up a balance). Non-actionable protocol/admin state (pool pause,
12
+ * available pool liquidity, health factor, liquidatability, degen NFT gating,
13
+ * bot permissions) is intentionally out of scope, since the user cannot
14
+ * resolve it. New {@link AnyPrerequisite} subclasses must follow the same rule.
15
+ */
16
+ export declare function buildPrerequisites(tx: Operation, ctx: PrerequisiteContext): AnyPrerequisite[];
@@ -0,0 +1,7 @@
1
+ export * from "./AllowancePrerequisite.js";
2
+ export * from "./BalancePrerequisite.js";
3
+ export * from "./buildPrerequisites.js";
4
+ export * from "./Prerequisite.js";
5
+ export * from "./prepareAction.js";
6
+ export * from "./runPrerequisites.js";
7
+ export * from "./types.js";
@@ -0,0 +1,52 @@
1
+ import { type Address, type Hex } from "viem";
2
+ import type { AnyPrerequisiteResult } from "./types.js";
3
+ /**
4
+ * A single transaction that satisfies a sender-actionable prerequisite.
5
+ *
6
+ * The shape is intentionally minimal (`to`/`data`/optional `value`) so it maps
7
+ * directly onto wallet send primitives (e.g. viem `sendTransaction`, wagmi
8
+ * `useSendTransaction`/`useWriteContract`). It is deliberately *not* the heavier
9
+ * {@link import("../../sdk/types/transactions.js").RawTx} used for Safe batches.
10
+ *
11
+ * The `kind` mirrors the prerequisite kind it remediates, so consumers can label
12
+ * the action (e.g. "Approve") without re-deriving it.
13
+ */
14
+ export interface PrerequisiteAction {
15
+ /** Prerequisite kind this action remediates. */
16
+ kind: "allowance";
17
+ /** Contract the transaction is sent to (the ERC-20 token for allowances). */
18
+ to: Address;
19
+ /** Encoded calldata (e.g. `approve(spender, required)`). */
20
+ data: Hex;
21
+ /** Native value to send; omitted (treated as 0) for ERC-20 approvals. */
22
+ value?: bigint;
23
+ }
24
+ /**
25
+ * Builds the transaction that resolves an unsatisfied, sender-actionable
26
+ * prerequisite, or returns `null` when the prerequisite cannot be fixed with a
27
+ * single wallet transaction.
28
+ *
29
+ * Currently only `allowance` is actionable: it returns an ERC-20
30
+ * `approve(spender, required)` for the exact required amount. `balance`
31
+ * shortfalls (the user must acquire/free up funds) and errored reads are not
32
+ * actionable and return `null`. New actionable kinds (permits, native unwrap,
33
+ * approve-reset-to-zero for non-standard tokens, ...) should be encoded here so
34
+ * consumers do not have to special-case them.
35
+ *
36
+ * Operates on the serializable {@link AnyPrerequisiteResult} produced by
37
+ * `verifyPrerequisites` (not on {@link import("./Prerequisite.js").Prerequisite}
38
+ * instances), so it works against cached/persisted results.
39
+ *
40
+ * @param result - A verified prerequisite result.
41
+ * @returns The remediation transaction, or `null` if not auto-actionable.
42
+ */
43
+ export declare function preparePrerequisiteAction(result: AnyPrerequisiteResult): PrerequisiteAction | null;
44
+ /**
45
+ * Whether a prerequisite result represents something the sender can fix with a
46
+ * single wallet transaction (i.e. {@link preparePrerequisiteAction} returns a
47
+ * transaction for it).
48
+ *
49
+ * Useful for UIs that distinguish "approve to continue" (actionable) from hard
50
+ * blocks like an insufficient balance (not actionable).
51
+ */
52
+ export declare function isActionablePrerequisite(result: AnyPrerequisiteResult): boolean;
@@ -0,0 +1,12 @@
1
+ import type { AnyPrerequisite } from "./Prerequisite.js";
2
+ import type { AnyPrerequisiteResult, PrerequisiteContext } from "./types.js";
3
+ /**
4
+ * Verifies all prerequisites in a single resilient multicall.
5
+ *
6
+ * Every prereq contributes its reads to one `multicall({ allowFailure: true })`
7
+ * batch, then resolves its own slice of the response. A read that reverts
8
+ * isolates to that prerequisite (an `error` result) without affecting the
9
+ * others; if the whole round-trip fails (RPC/network), every prerequisite
10
+ * resolves to an `error` carrying that reason.
11
+ */
12
+ export declare function verifyPrerequisites(prereqs: AnyPrerequisite[], ctx: PrerequisiteContext): Promise<AnyPrerequisiteResult[]>;
@@ -0,0 +1,78 @@
1
+ import type { Address } from "viem";
2
+ import type { OnchainSDK } from "../../sdk/index.js";
3
+ /**
4
+ * Extension point that ties each prerequisite kind to its detail payload.
5
+ *
6
+ * Adding a new prerequisite kind only requires a new entry here: the generic
7
+ * machinery below and the UI renderer registry both key off this map, so TS
8
+ * forces every consumer to handle the new kind.
9
+ *
10
+ * IMPORTANT: only add prerequisites that are *actionable by the transaction
11
+ * sender* (the LP provider or borrower). A valid prerequisite is one the user
12
+ * can resolve themselves before retrying, e.g. approve a token (`allowance`)
13
+ * or acquire/free up funds (`balance`). Do NOT add protocol- or admin-level
14
+ * state the user cannot change, such as pool pause status or available pool
15
+ * liquidity; those are not actionable and must not be listed as prerequisites.
16
+ */
17
+ export interface PrerequisiteDetailMap {
18
+ /** ERC-20 allowance from `owner` to `spender` must cover `required`. */
19
+ allowance: {
20
+ token: Address;
21
+ owner: Address;
22
+ spender: Address;
23
+ required: bigint;
24
+ /** On-chain allowance read; only present when the read succeeded. */
25
+ actual?: bigint;
26
+ };
27
+ /** ERC-20 balance of `owner` must cover `required`. */
28
+ balance: {
29
+ token: Address;
30
+ owner: Address;
31
+ required: bigint;
32
+ /** On-chain balance read; only present when the read succeeded. */
33
+ actual?: bigint;
34
+ };
35
+ }
36
+ export type PrerequisiteKind = keyof PrerequisiteDetailMap;
37
+ export type PrerequisiteDetail<K extends PrerequisiteKind = PrerequisiteKind> = PrerequisiteDetailMap[K];
38
+ /** Failure of the underlying on-chain read (revert, decode error, RPC error). */
39
+ export interface PrerequisiteError {
40
+ /** Decoded revert reason / error name, human-readable. */
41
+ reason: string;
42
+ /** Original error, kept for debugging. */
43
+ cause?: unknown;
44
+ }
45
+ export interface PrerequisiteBase<K extends PrerequisiteKind> {
46
+ id: string;
47
+ kind: K;
48
+ title: string;
49
+ detail: PrerequisiteDetail<K>;
50
+ }
51
+ /**
52
+ * Outcome of verifying a single prerequisite: either the read succeeded (a
53
+ * `satisfied` boolean) or it reverted/failed (an `error` with the revert
54
+ * reason). The two variants are mutually exclusive.
55
+ */
56
+ export type PrerequisiteResult<K extends PrerequisiteKind = PrerequisiteKind> = PrerequisiteBase<K> & ({
57
+ satisfied: boolean;
58
+ error?: undefined;
59
+ } | {
60
+ satisfied?: undefined;
61
+ error: PrerequisiteError;
62
+ });
63
+ /**
64
+ * Discriminated union over every prerequisite kind. Switching on `kind`
65
+ * narrows `detail` to the matching payload, so React components can render
66
+ * kind-specific details with full type safety.
67
+ */
68
+ export type AnyPrerequisiteResult = {
69
+ [K in PrerequisiteKind]: PrerequisiteResult<K>;
70
+ }[PrerequisiteKind];
71
+ /** Shared inputs for building and verifying prerequisites. */
72
+ export interface PrerequisiteContext {
73
+ sdk: OnchainSDK;
74
+ /** Address whose balances/allowances are checked (the tx sender). */
75
+ wallet: Address;
76
+ /** Block to read at; defaults to latest. Only set for testnet forks. */
77
+ blockNumber?: bigint;
78
+ }
@@ -0,0 +1,6 @@
1
+ import type { NetworkType } from "../../sdk/chain/index.js";
2
+ /**
3
+ * Networks where the `eth_simulateV1` JSON-RPC method is available and usable
4
+ * for pool or credit account operation simulation.
5
+ **/
6
+ export declare const ETH_SIMULATE_V1_NETWORKS: ReadonlySet<NetworkType>;
@@ -0,0 +1,51 @@
1
+ import { BaseError, type Hex } from "viem";
2
+ /** Which simulation flow produced a failure. */
3
+ export type SimulationFlowSource = "eth_simulateV1" | "multicall" | "unknown";
4
+ /** A single flow failure with its decoded revert detail. */
5
+ export interface SimulationFlowFailure {
6
+ source: SimulationFlowSource;
7
+ detail: SimulationError;
8
+ }
9
+ /**
10
+ * Error returned by the pool simulation when all attempted flows fail.
11
+ *
12
+ * On a single-flow failure it wraps that flow's decoded revert reason; when both
13
+ * the `eth_simulateV1` and multicall flows fail, it carries the details of both
14
+ * (see {@link failures}).
15
+ */
16
+ export declare class PreviewSimulationError extends BaseError {
17
+ name: string;
18
+ /** Per-flow decoded failures behind this error. */
19
+ readonly failures: SimulationFlowFailure[];
20
+ constructor(failures: SimulationFlowFailure[]);
21
+ }
22
+ /**
23
+ * Normalises an unknown rejection reason into a {@link PreviewSimulationError}.
24
+ * Pass-through when it already is one; otherwise decodes it under `source`.
25
+ */
26
+ export declare function asPreviewSimulationError(reason: unknown, source: SimulationFlowSource): PreviewSimulationError;
27
+ /** Merges several {@link PreviewSimulationError}s into one carrying all failures. */
28
+ export declare function combinePreviewSimulationErrors(...errors: (PreviewSimulationError | undefined)[]): PreviewSimulationError;
29
+ /** Decoded revert of the simulated transaction. */
30
+ export interface SimulationError {
31
+ /** Human-readable revert reason / error name. */
32
+ reason: string;
33
+ /** Original error, kept for debugging. */
34
+ cause?: unknown;
35
+ }
36
+ /** Per-call slice of a `simulateCalls` failure we need to decode. */
37
+ export interface SimulationRevert {
38
+ error?: Error;
39
+ /** Raw revert return data, when present. */
40
+ data?: Hex;
41
+ }
42
+ /**
43
+ * Decodes a simulated transaction revert into a {@link SimulationError}.
44
+ *
45
+ * The simulated call is raw calldata (no ABI), so viem cannot decode the revert
46
+ * itself. We first try to decode the raw return bytes against the SDK's
47
+ * {@link errorAbis} (Gearbox protocol exceptions plus standard ERC-20 custom
48
+ * errors); failing that, we walk viem's error chain for a
49
+ * {@link ContractFunctionRevertedError} (covers `Error(string)` / `Panic`).
50
+ */
51
+ export declare function decodeSimulationError(revert: SimulationRevert): SimulationError;
@@ -0,0 +1,11 @@
1
+ import { type Address, type Log } from "viem";
2
+ import type { TokenTransfer } from "../parse/index.js";
3
+ /**
4
+ * Parses ERC-20 `Transfer` logs and keeps only those involving one of the
5
+ * watched addresses (as sender or receiver). A log that touches several watched
6
+ * addresses is still emitted once.
7
+ *
8
+ * @param logs - raw logs from the simulated call
9
+ * @param watch - addresses whose transfers we care about (e.g. wallet + recipient)
10
+ */
11
+ export declare function extractERC20Transfers(logs: Log[], watch: Address[]): TokenTransfer[];
@@ -0,0 +1,7 @@
1
+ import type { Address } from "viem";
2
+ import type { PoolOperation } from "../parse/index.js";
3
+ /**
4
+ * Distinct addresses whose balances change during the operation: the funds
5
+ * source (payer or share owner) and the receiver.
6
+ */
7
+ export declare function watchedHolders(operation: PoolOperation, wallet: Address): Address[];
@@ -0,0 +1,9 @@
1
+ export { ETH_SIMULATE_V1_NETWORKS } from "./constants.js";
2
+ export type { SimulationError, SimulationFlowFailure, SimulationFlowSource, } from "./errors.js";
3
+ export { PreviewSimulationError } from "./errors.js";
4
+ export type { SimulateFacadeOperationInput } from "./simulateFacadeOperation.js";
5
+ export { simulateFacadeOperation } from "./simulateFacadeOperation.js";
6
+ export type { SimulateOperationInput } from "./simulateOperation.js";
7
+ export { simulateOperation } from "./simulateOperation.js";
8
+ export { simulatePoolOperation } from "./simulatePoolOperation.js";
9
+ export type { AddressBalanceChanges, OperationSimulationOptions, PoolOperationSimulation, PoolOperationSimulationInput, PoolOperationSimulationResult, TokenBalanceChange, } from "./types.js";
@@ -0,0 +1,25 @@
1
+ import type { Address, Hex } from "viem";
2
+ import type { OnchainSDK } from "../../sdk/index.js";
3
+ import type { OuterFacadeOperation } from "../parse/index.js";
4
+ import type { OperationSimulationOptions, PoolOperationSimulation } from "./types.js";
5
+ export interface SimulateFacadeOperationInput {
6
+ /** Only `client`/`networkType` are used, so any OnchainSDK works. */
7
+ sdk: OnchainSDK;
8
+ /** Parsed credit-facade operation to simulate. */
9
+ operation: OuterFacadeOperation;
10
+ /** Target contract the calldata is sent to (the credit facade). */
11
+ to: Address;
12
+ /** Raw credit-facade calldata to simulate. */
13
+ calldata: Hex;
14
+ /** Wallet whose balance changes and transfers we track. */
15
+ wallet: Address;
16
+ }
17
+ /**
18
+ * Simulates a credit-facade operation.
19
+ *
20
+ * Not yet implemented: credit-facade simulation requires multicall-aware
21
+ * balance/transfer accounting that the pool simulation does not cover. The
22
+ * signature mirrors {@link simulatePoolOperation} so the
23
+ * {@link simulateOperation} wrapper can delegate uniformly once implemented.
24
+ */
25
+ export declare function simulateFacadeOperation(_input: SimulateFacadeOperationInput, _options?: OperationSimulationOptions): Promise<PoolOperationSimulation>;
@@ -0,0 +1,20 @@
1
+ import type { Address, Hex } from "viem";
2
+ import type { OnchainSDK } from "../../sdk/index.js";
3
+ import { type Operation } from "../parse/index.js";
4
+ import type { OperationSimulationOptions, PoolOperationSimulation } from "./types.js";
5
+ export interface SimulateOperationInput {
6
+ /** Gearbox SDK instance. */
7
+ sdk: OnchainSDK;
8
+ /** Parsed pool or credit account operation */
9
+ operation: Operation;
10
+ /** Target contract the calldata is sent to. */
11
+ to: Address;
12
+ /** Raw operation calldata to simulate. */
13
+ calldata: Hex;
14
+ /** Wallet whose balance changes and transfers we track. */
15
+ wallet: Address;
16
+ }
17
+ /**
18
+ * Simulates a parsed pool or credit account operation {@link Operation}
19
+ */
20
+ export declare function simulateOperation(input: SimulateOperationInput, options?: OperationSimulationOptions): Promise<PoolOperationSimulation>;
@@ -0,0 +1,28 @@
1
+ import type { Address } from "viem";
2
+ import type { PoolOperation } from "../parse/index.js";
3
+ import type { AddressBalanceChanges, OperationSimulationOptions, PoolOperationSimulationInput, PoolOperationSimulationResult } from "./types.js";
4
+ /** Reads a watched holder's "before" balance of a token. */
5
+ export type BalanceLookup = (token: Address, holder: Address) => bigint;
6
+ /**
7
+ * Multicall pool-operation flow, used where `eth_simulateV1` is unavailable or
8
+ * as a fallback alongside it.
9
+ *
10
+ * Reads the watched holders' "before" balances together with the matching
11
+ * ERC4626 preview (`previewDeposit`/`previewMint`/`previewWithdraw`/
12
+ * `previewRedeem`) in a single multicall, then computes the theoretical balance
13
+ * changes via {@link computePoolOpBalanceChanges}.
14
+ *
15
+ * Unlike the `eth_simulateV1` flow it does not execute the calldata, so it
16
+ * cannot recover ERC-20 transfers (`transfers` is always `undefined`) and it
17
+ * ignores balance/allowance prerequisites (preview reads succeed regardless).
18
+ *
19
+ * @throws {@link PreviewSimulationError} when the multicall round-trip throws or
20
+ * any call (a balance read or the preview read) reverts.
21
+ */
22
+ export declare function simulatePoolOpMulticall(input: PoolOperationSimulationInput, options?: OperationSimulationOptions): Promise<PoolOperationSimulationResult>;
23
+ /**
24
+ * Pure computation of {@link AddressBalanceChanges} for a pool operation from
25
+ * its ERC4626 preview result and the watched holders' "before" balances. Legs
26
+ * sharing the same address are grouped together.
27
+ */
28
+ export declare function computePoolOpBalanceChanges(operation: PoolOperation, wallet: Address, previewAmount: bigint, before: BalanceLookup): AddressBalanceChanges[];
@@ -0,0 +1,14 @@
1
+ import type { OperationSimulationOptions, PoolOperationSimulationInput, PoolOperationSimulationResult } from "./types.js";
2
+ /**
3
+ * `eth_simulateV1` pool-operation flow.
4
+ *
5
+ * Sandwiches the raw calldata between `balanceOf` reads of the underlying and
6
+ * pool (share) tokens for every watched holder, then derives the balance changes
7
+ * from the before/after diff and the wallet-relevant ERC-20 transfers from the
8
+ * emitted logs. Simulation runs against real chain state (no overrides), so an
9
+ * unmet prerequisite surfaces here as a revert.
10
+ *
11
+ * @throws {@link PreviewSimulationError} when the round-trip throws or the
12
+ * simulated transaction reverts.
13
+ */
14
+ export declare function simulatePoolOpV1(input: PoolOperationSimulationInput, options?: OperationSimulationOptions): Promise<PoolOperationSimulationResult>;
@@ -0,0 +1,8 @@
1
+ import type { OperationSimulationOptions, PoolOperationSimulation, PoolOperationSimulationInput } from "./types.js";
2
+ /**
3
+ * Simulates a pool deposit/mint/withdraw/redeem and returns the resulting
4
+ * balance changes (and, when available, ERC-20 transfers), or a decoded failure.
5
+ *
6
+ * @throws {@link PreviewSimulationError} when the simulation fails.
7
+ */
8
+ export declare function simulatePoolOperation(input: PoolOperationSimulationInput, options?: OperationSimulationOptions): Promise<PoolOperationSimulation>;
@@ -0,0 +1,79 @@
1
+ import type { Address, Hex } from "viem";
2
+ import type { OnchainSDK } from "../../sdk/index.js";
3
+ import type { ILogger } from "../../sdk/types/logger.js";
4
+ import type { PoolOperation, TokenTransfer } from "../parse/index.js";
5
+ import type { PreviewSimulationError } from "./errors.js";
6
+ /**
7
+ * Change in an address's balance of a single token over the simulated call.
8
+ * `delta` is `after - before` (negative when the address spent the token).
9
+ */
10
+ export interface TokenBalanceChange {
11
+ token: Address;
12
+ before: bigint;
13
+ after: bigint;
14
+ delta: bigint;
15
+ }
16
+ /**
17
+ * Balance changes for a single watched address (e.g. the wallet or the
18
+ * operation recipient). Keyed purely by address; UI labeling is resolved
19
+ * separately by the presentation layer.
20
+ */
21
+ export interface AddressBalanceChanges {
22
+ address: Address;
23
+ changes: TokenBalanceChange[];
24
+ }
25
+ export interface PoolOperationSimulationInput {
26
+ /** Only `client`/`networkType` are used, so any OnchainSDK works. */
27
+ sdk: OnchainSDK;
28
+ /** Parsed operation, used to resolve the underlying and pool tokens. */
29
+ operation: PoolOperation;
30
+ /** Target contract the calldata is sent to (the pool). */
31
+ to: Address;
32
+ /** Raw deposit/mint/withdraw/redeem calldata to simulate. */
33
+ calldata: Hex;
34
+ /** Wallet whose balance changes and transfers we track. */
35
+ wallet: Address;
36
+ }
37
+ export interface OperationSimulationOptions {
38
+ /** Block to simulate at; defaults to latest. */
39
+ blockNumber?: bigint;
40
+ /**
41
+ * Whether to run the `eth_simulateV1` flow (preferred, recovers transfers).
42
+ * When `undefined`, defaults to whether the SDK's network is in
43
+ * {@link ETH_SIMULATE_V1_NETWORKS}.
44
+ */
45
+ useSimulateV1?: boolean;
46
+ /**
47
+ * Optional logger.
48
+ **/
49
+ logger?: ILogger;
50
+ }
51
+ /**
52
+ * Successful simulation of a pool operation: the balance changes grouped by
53
+ * watched address and, when available, the wallet-filtered ERC-20 transfers.
54
+ * This is the success payload of {@link PoolOperationSimulation} without the
55
+ * `status` discriminant.
56
+ */
57
+ export interface PoolOperationSimulationResult {
58
+ /**
59
+ * Balance changes grouped by watched address (wallet, recipient, owner).
60
+ **/
61
+ balanceChanges: AddressBalanceChanges[];
62
+ /**
63
+ * ERC-20 transfers involving the watched addresses.
64
+ *
65
+ * NOTE: transfers are **not guaranteed** to be returned.
66
+ */
67
+ transfers?: TokenTransfer[];
68
+ }
69
+ /**
70
+ * Outcome of simulating a pool operation. On success it carries a
71
+ * {@link PoolOperationSimulationResult}; on failure it carries a
72
+ * {@link PreviewSimulationError}.
73
+ */
74
+ export type PoolOperationSimulation = ({
75
+ status: "success";
76
+ } & PoolOperationSimulationResult) | {
77
+ status: "failure";
78
+ error: PreviewSimulationError;
79
+ };
@@ -9,16 +9,6 @@ export declare class TransferAlignmentError extends Error {
9
9
  export declare class WithdrawCollateralAlignmentError extends Error {
10
10
  constructor(expected: number, actual: number);
11
11
  }
12
- export declare class ProtocolCallNotFoundError extends Error {
13
- readonly targetContract: Address;
14
- readonly executeIndex: number;
15
- constructor(targetContract: Address, executeIndex: number);
16
- }
17
- export declare class AdapterTraceAlignmentError extends Error {
18
- readonly expected: number;
19
- readonly actual: number;
20
- constructor(expected: number, actual: number);
21
- }
22
12
  export declare class UnexpectedFacadeEventOrderError extends Error {
23
13
  constructor(e: {
24
14
  eventName: string;
@@ -0,0 +1,23 @@
1
+ import { type CallTrace } from "../../common-utils/utils/trace.js";
2
+ /**
3
+ * Extracts the user multicall's adapter-level call traces from a single facade
4
+ * call trace.
5
+ *
6
+ * Returns the direct children of the facade trace that perform an external
7
+ * protocol call (their subtree resolves to a `CreditManager.execute(bytes)`
8
+ * that reaches a leaf CALL to a target contract), in trace order.
9
+ *
10
+ * Scoping to direct children of the facade trace (rather than flattening the
11
+ * whole subtree) avoids over-counting in nested credit-manager scenarios such
12
+ * as account migration, where a single migrate-adapter subtree nests another
13
+ * account's `execute(bytes)` calls.
14
+ *
15
+ * Facade-synthesized phantom-token withdrawals are excluded: while processing
16
+ * `withdrawCollateral` on a phantom token the facade issues its own
17
+ * `withdrawPhantomToken` adapter call, which also reaches an external target
18
+ * but does not correspond to a user multicall inner call. These are detected
19
+ * via the preceding `getPhantomTokenInfo()` probe (see
20
+ * {@link isSynthesizedPhantomWithdrawal}), so the returned traces line up 1:1,
21
+ * in order, with the multicall's adapter inner calls.
22
+ */
23
+ export declare function extractAdapterCallTraces(facadeTrace: CallTrace): CallTrace[];
@@ -1,7 +1,6 @@
1
1
  import { type Address, type Log } from "viem";
2
- import { AddressMap } from "../sdk/index.js";
3
- import type { ExecuteResult } from "./internal-types.js";
4
- import type { DirectTransferInfo } from "./types.js";
2
+ import { AddressMap } from "../../sdk/index.js";
3
+ import type { TokenTransfer } from "../parse/index.js";
5
4
  type RawLog = Log<bigint | number, number, false>;
6
5
  /**
7
6
  * Effective `withdrawCollateral` outcome decoded from the facade's
@@ -26,8 +25,18 @@ export interface WithdrawCollateralEventInfo {
26
25
  * @param creditAccount - the credit account address to track
27
26
  */
28
27
  export interface ExtractTransfersResult {
29
- executeResults: ExecuteResult[];
30
- directTransfers: DirectTransferInfo[];
28
+ /**
29
+ * ERC-20 transfers grouped per facade `Execute` event, one inner array per
30
+ * Execute event across the whole transaction, in emission order. Each inner
31
+ * array holds the transfers to/from the credit account that occurred between
32
+ * that Execute boundary and the previous one.
33
+ */
34
+ executeTransfers: TokenTransfer[][];
35
+ /**
36
+ * ERC-20 transfers that are not part of a facade `Execute` event and are
37
+ * direct incoming transfers to the credit account.
38
+ */
39
+ directTransfers: TokenTransfer[];
31
40
  liquidationRemainingFunds?: bigint;
32
41
  /** Maps phantom token address to its deposited (underlying) token address. */
33
42
  phantomTokens: AddressMap<Address>;
@@ -1,6 +1,7 @@
1
1
  import { type Address } from "viem";
2
- import type { ChainContractsRegister } from "../sdk/index.js";
3
- import type { CallTrace, FacadeParsedCall } from "./internal-types.js";
2
+ import { type CallTrace } from "../../common-utils/utils/trace.js";
3
+ import type { ChainContractsRegister } from "../../sdk/index.js";
4
+ import type { FacadeParsedCall } from "./types.js";
4
5
  /**
5
6
  * Walks a `debug_traceTransaction` callTracer tree, finds all non-reverted
6
7
  * calls to the credit facade, parses them via the register, and returns
@@ -0,0 +1,5 @@
1
+ export * from "./errors.js";
2
+ export * from "./extractAdapterCallTraces.js";
3
+ export * from "./extractTransfers.js";
4
+ export * from "./findFacadeCalls.js";
5
+ export * from "./types.js";