@gearbox-protocol/sdk 14.11.0-next.8 → 14.11.0

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 (186) hide show
  1. package/dist/cjs/common-utils/utils/index.js +0 -2
  2. package/dist/cjs/dev/index.js +1 -3
  3. package/dist/cjs/dev/isOutOfSyncError.js +3 -1
  4. package/dist/cjs/history/assembleOperations.js +6 -6
  5. package/dist/cjs/history/classifyMulticallOperations.js +25 -31
  6. package/dist/cjs/{preview/trace → history}/errors.js +26 -0
  7. package/dist/cjs/history/extractProtocolCalls.js +53 -0
  8. package/dist/cjs/{preview/trace → history}/extractTransfers.js +23 -11
  9. package/dist/cjs/{preview/trace → history}/findFacadeCalls.js +3 -3
  10. package/dist/cjs/history/index.js +2 -0
  11. package/dist/cjs/{preview/parse/types-facades.js → history/inner-operations.js} +2 -2
  12. package/dist/cjs/{preview/parse/types-adapters.js → history/internal-types.js} +2 -2
  13. package/dist/cjs/history/parseCreditAccountTransaction.js +6 -5
  14. package/dist/cjs/history/toLegacyOperation.js +2 -6
  15. package/dist/cjs/{common-utils/utils/trace.js → history/trace-utils.js} +5 -62
  16. package/dist/cjs/permissionless/bindings/pricefeeds/curve-twap.js +2 -2
  17. package/dist/cjs/plugins/adapters/contracts/AbstractAdapter.js +37 -25
  18. package/dist/cjs/plugins/adapters/contracts/AccountMigratorAdapterContract.js +0 -9
  19. package/dist/cjs/rewards/rewards/api.js +4 -2
  20. package/dist/cjs/rewards/rewards/merkl-api.js +9 -3
  21. package/dist/esm/common-utils/utils/index.js +0 -1
  22. package/dist/esm/dev/index.js +0 -1
  23. package/dist/esm/dev/isOutOfSyncError.js +3 -1
  24. package/dist/esm/history/assembleOperations.js +6 -8
  25. package/dist/esm/history/classifyMulticallOperations.js +23 -29
  26. package/dist/esm/{preview/trace → history}/errors.js +24 -0
  27. package/dist/esm/history/extractProtocolCalls.js +32 -0
  28. package/dist/esm/{preview/trace → history}/extractTransfers.js +23 -11
  29. package/dist/esm/{preview/trace → history}/findFacadeCalls.js +2 -4
  30. package/dist/esm/history/index.js +1 -0
  31. package/dist/esm/history/parseCreditAccountTransaction.js +4 -3
  32. package/dist/esm/history/toLegacyOperation.js +2 -6
  33. package/dist/esm/history/trace-utils.js +36 -0
  34. package/dist/esm/permissionless/bindings/pricefeeds/curve-twap.js +2 -2
  35. package/dist/esm/plugins/adapters/contracts/AbstractAdapter.js +38 -28
  36. package/dist/esm/plugins/adapters/contracts/AccountMigratorAdapterContract.js +0 -9
  37. package/dist/esm/rewards/rewards/api.js +4 -2
  38. package/dist/esm/rewards/rewards/merkl-api.js +9 -3
  39. package/dist/types/common-utils/utils/index.d.ts +0 -1
  40. package/dist/types/dev/index.d.ts +0 -1
  41. package/dist/types/history/assembleOperations.d.ts +6 -11
  42. package/dist/types/history/classifyMulticallOperations.d.ts +9 -21
  43. package/dist/types/{preview/trace → history}/errors.d.ts +10 -0
  44. package/dist/types/history/extractProtocolCalls.d.ts +8 -0
  45. package/dist/types/{preview/trace → history}/extractTransfers.d.ts +7 -15
  46. package/dist/types/{preview/trace → history}/findFacadeCalls.d.ts +2 -3
  47. package/dist/types/history/index.d.ts +1 -0
  48. package/dist/types/history/inner-operations.d.ts +57 -0
  49. package/dist/types/history/internal-types.d.ts +47 -0
  50. package/dist/types/history/mapOperations.d.ts +9 -7
  51. package/dist/types/history/trace-utils.d.ts +12 -0
  52. package/dist/types/history/types.d.ts +71 -22
  53. package/dist/types/plugins/adapters/contracts/AbstractAdapter.d.ts +17 -16
  54. package/dist/types/plugins/adapters/contracts/AccountMigratorAdapterContract.d.ts +1 -10
  55. package/dist/types/plugins/adapters/contracts/ConvexV1BaseRewardPoolAdapterContract.d.ts +1 -1
  56. package/dist/types/plugins/adapters/contracts/ConvexV1BoosterAdapterContract.d.ts +1 -1
  57. package/dist/types/plugins/adapters/contracts/Curve2AssetsAdapterContract.d.ts +1 -1
  58. package/dist/types/plugins/adapters/contracts/Curve3AssetsAdapterContract.d.ts +1 -1
  59. package/dist/types/plugins/adapters/contracts/Curve4AssetsAdapterContract.d.ts +1 -1
  60. package/dist/types/plugins/adapters/contracts/CurveV1AdapterDeposit.d.ts +1 -1
  61. package/dist/types/plugins/adapters/contracts/CurveV1AdapterStETHContract.d.ts +1 -1
  62. package/dist/types/plugins/adapters/contracts/CurveV1StableNGAdapterContract.d.ts +1 -1
  63. package/dist/types/plugins/adapters/contracts/DaiUsdsAdapterContract.d.ts +1 -1
  64. package/dist/types/plugins/adapters/contracts/ERC4626AdapterContract.d.ts +1 -1
  65. package/dist/types/plugins/adapters/contracts/ERC4626ReferralAdapterContract.d.ts +1 -1
  66. package/dist/types/plugins/adapters/contracts/LidoV1AdapterContract.d.ts +1 -1
  67. package/dist/types/plugins/adapters/contracts/MellowDVVAdapterContract.d.ts +1 -1
  68. package/dist/types/plugins/adapters/contracts/MellowERC4626VaultAdapterContract.d.ts +1 -1
  69. package/dist/types/plugins/adapters/contracts/UniswapV2AdapterContract.d.ts +1 -1
  70. package/dist/types/plugins/adapters/contracts/UniswapV4AdapterContract.d.ts +1 -1
  71. package/dist/types/plugins/adapters/contracts/WstETHV1AdapterContract.d.ts +1 -1
  72. package/dist/types/plugins/adapters/transferHelpers.d.ts +1 -1
  73. package/dist/types/plugins/adapters/types.d.ts +46 -8
  74. package/dist/types/rewards/rewards/api.d.ts +2 -1
  75. package/dist/types/rewards/rewards/merkl-api.d.ts +2 -1
  76. package/package.json +1 -6
  77. package/dist/cjs/dev/verifyTestnet.js +0 -124
  78. package/dist/cjs/plugins/adapters/transfers.js +0 -16
  79. package/dist/cjs/preview/index.js +0 -28
  80. package/dist/cjs/preview/package.json +0 -1
  81. package/dist/cjs/preview/parse/classifyInnerOperations.js +0 -92
  82. package/dist/cjs/preview/parse/errors.js +0 -47
  83. package/dist/cjs/preview/parse/extractExpectedBalanceChanges.js +0 -48
  84. package/dist/cjs/preview/parse/index.js +0 -34
  85. package/dist/cjs/preview/parse/parseFacadeOperationCalldata.js +0 -115
  86. package/dist/cjs/preview/parse/parseOperationCalldata.js +0 -46
  87. package/dist/cjs/preview/parse/parsePoolOperationCalldata.js +0 -77
  88. package/dist/cjs/preview/parse/types-pools.js +0 -16
  89. package/dist/cjs/preview/parse/types.js +0 -37
  90. package/dist/cjs/preview/prerequisites/AllowancePrerequisite.js +0 -78
  91. package/dist/cjs/preview/prerequisites/BalancePrerequisite.js +0 -77
  92. package/dist/cjs/preview/prerequisites/Prerequisite.js +0 -85
  93. package/dist/cjs/preview/prerequisites/buildPrerequisites.js +0 -187
  94. package/dist/cjs/preview/prerequisites/index.js +0 -34
  95. package/dist/cjs/preview/prerequisites/prepareAction.js +0 -48
  96. package/dist/cjs/preview/prerequisites/runPrerequisites.js +0 -71
  97. package/dist/cjs/preview/prerequisites/types.js +0 -16
  98. package/dist/cjs/preview/simulate/constants.js +0 -28
  99. package/dist/cjs/preview/simulate/errors.js +0 -98
  100. package/dist/cjs/preview/simulate/extractERC20Transfers.js +0 -47
  101. package/dist/cjs/preview/simulate/holders.js +0 -45
  102. package/dist/cjs/preview/simulate/index.js +0 -40
  103. package/dist/cjs/preview/simulate/simulateFacadeOperation.js +0 -30
  104. package/dist/cjs/preview/simulate/simulateOperation.js +0 -37
  105. package/dist/cjs/preview/simulate/simulatePoolOpMulticall.js +0 -155
  106. package/dist/cjs/preview/simulate/simulatePoolOpV1.js +0 -106
  107. package/dist/cjs/preview/simulate/simulatePoolOperation.js +0 -62
  108. package/dist/cjs/preview/simulate/types.js +0 -16
  109. package/dist/cjs/preview/trace/extractAdapterCallTraces.js +0 -58
  110. package/dist/cjs/preview/trace/index.js +0 -30
  111. package/dist/cjs/preview/trace/types.js +0 -16
  112. package/dist/esm/common-utils/utils/trace.js +0 -93
  113. package/dist/esm/dev/verifyTestnet.js +0 -98
  114. package/dist/esm/preview/index.js +0 -4
  115. package/dist/esm/preview/package.json +0 -1
  116. package/dist/esm/preview/parse/classifyInnerOperations.js +0 -68
  117. package/dist/esm/preview/parse/errors.js +0 -22
  118. package/dist/esm/preview/parse/extractExpectedBalanceChanges.js +0 -24
  119. package/dist/esm/preview/parse/index.js +0 -7
  120. package/dist/esm/preview/parse/parseFacadeOperationCalldata.js +0 -91
  121. package/dist/esm/preview/parse/parseOperationCalldata.js +0 -25
  122. package/dist/esm/preview/parse/parsePoolOperationCalldata.js +0 -53
  123. package/dist/esm/preview/parse/types-facades.js +0 -0
  124. package/dist/esm/preview/parse/types-pools.js +0 -0
  125. package/dist/esm/preview/parse/types.js +0 -9
  126. package/dist/esm/preview/prerequisites/AllowancePrerequisite.js +0 -57
  127. package/dist/esm/preview/prerequisites/BalancePrerequisite.js +0 -56
  128. package/dist/esm/preview/prerequisites/Prerequisite.js +0 -63
  129. package/dist/esm/preview/prerequisites/buildPrerequisites.js +0 -163
  130. package/dist/esm/preview/prerequisites/index.js +0 -7
  131. package/dist/esm/preview/prerequisites/prepareAction.js +0 -23
  132. package/dist/esm/preview/prerequisites/runPrerequisites.js +0 -47
  133. package/dist/esm/preview/prerequisites/types.js +0 -0
  134. package/dist/esm/preview/simulate/constants.js +0 -4
  135. package/dist/esm/preview/simulate/errors.js +0 -75
  136. package/dist/esm/preview/simulate/extractERC20Transfers.js +0 -23
  137. package/dist/esm/preview/simulate/holders.js +0 -21
  138. package/dist/esm/preview/simulate/index.js +0 -12
  139. package/dist/esm/preview/simulate/simulateFacadeOperation.js +0 -6
  140. package/dist/esm/preview/simulate/simulateOperation.js +0 -13
  141. package/dist/esm/preview/simulate/simulatePoolOpMulticall.js +0 -130
  142. package/dist/esm/preview/simulate/simulatePoolOpV1.js +0 -82
  143. package/dist/esm/preview/simulate/simulatePoolOperation.js +0 -41
  144. package/dist/esm/preview/simulate/types.js +0 -0
  145. package/dist/esm/preview/trace/extractAdapterCallTraces.js +0 -40
  146. package/dist/esm/preview/trace/index.js +0 -5
  147. package/dist/esm/preview/trace/types.js +0 -0
  148. package/dist/types/common-utils/utils/trace.d.ts +0 -73
  149. package/dist/types/dev/verifyTestnet.d.ts +0 -82
  150. package/dist/types/plugins/adapters/transfers.d.ts +0 -17
  151. package/dist/types/preview/index.d.ts +0 -4
  152. package/dist/types/preview/parse/classifyInnerOperations.d.ts +0 -21
  153. package/dist/types/preview/parse/errors.d.ts +0 -17
  154. package/dist/types/preview/parse/extractExpectedBalanceChanges.d.ts +0 -22
  155. package/dist/types/preview/parse/index.d.ts +0 -7
  156. package/dist/types/preview/parse/parseFacadeOperationCalldata.d.ts +0 -19
  157. package/dist/types/preview/parse/parseOperationCalldata.d.ts +0 -23
  158. package/dist/types/preview/parse/parsePoolOperationCalldata.d.ts +0 -17
  159. package/dist/types/preview/parse/types-adapters.d.ts +0 -69
  160. package/dist/types/preview/parse/types-facades.d.ts +0 -157
  161. package/dist/types/preview/parse/types-pools.d.ts +0 -55
  162. package/dist/types/preview/parse/types.d.ts +0 -44
  163. package/dist/types/preview/prerequisites/AllowancePrerequisite.d.ts +0 -24
  164. package/dist/types/preview/prerequisites/BalancePrerequisite.d.ts +0 -23
  165. package/dist/types/preview/prerequisites/Prerequisite.d.ts +0 -60
  166. package/dist/types/preview/prerequisites/buildPrerequisites.d.ts +0 -16
  167. package/dist/types/preview/prerequisites/index.d.ts +0 -7
  168. package/dist/types/preview/prerequisites/prepareAction.d.ts +0 -52
  169. package/dist/types/preview/prerequisites/runPrerequisites.d.ts +0 -12
  170. package/dist/types/preview/prerequisites/types.d.ts +0 -78
  171. package/dist/types/preview/simulate/constants.d.ts +0 -6
  172. package/dist/types/preview/simulate/errors.d.ts +0 -51
  173. package/dist/types/preview/simulate/extractERC20Transfers.d.ts +0 -11
  174. package/dist/types/preview/simulate/holders.d.ts +0 -7
  175. package/dist/types/preview/simulate/index.d.ts +0 -9
  176. package/dist/types/preview/simulate/simulateFacadeOperation.d.ts +0 -25
  177. package/dist/types/preview/simulate/simulateOperation.d.ts +0 -20
  178. package/dist/types/preview/simulate/simulatePoolOpMulticall.d.ts +0 -28
  179. package/dist/types/preview/simulate/simulatePoolOpV1.d.ts +0 -14
  180. package/dist/types/preview/simulate/simulatePoolOperation.d.ts +0 -8
  181. package/dist/types/preview/simulate/types.d.ts +0 -79
  182. package/dist/types/preview/trace/extractAdapterCallTraces.d.ts +0 -23
  183. package/dist/types/preview/trace/index.d.ts +0 -5
  184. package/dist/types/preview/trace/types.d.ts +0 -21
  185. /package/dist/esm/{plugins/adapters/transfers.js → history/inner-operations.js} +0 -0
  186. /package/dist/esm/{preview/parse/types-adapters.js → history/internal-types.js} +0 -0
@@ -1,47 +0,0 @@
1
- async function verifyPrerequisites(prereqs, ctx) {
2
- if (prereqs.length === 0) {
3
- return [];
4
- }
5
- const ranges = [];
6
- const calls = [];
7
- for (const prereq of prereqs) {
8
- const start = calls.length;
9
- calls.push(...prereq.calls(ctx));
10
- ranges.push({ start, end: calls.length });
11
- }
12
- let results;
13
- try {
14
- results = await ctx.sdk.client.multicall({
15
- allowFailure: true,
16
- contracts: calls,
17
- // `undefined` lets viem read at `latest`; `blockNumber` is only set for
18
- // testnet forks pinned to a specific block.
19
- blockNumber: ctx.blockNumber
20
- });
21
- } catch (cause) {
22
- const error = cause instanceof Error ? cause : new Error(String(cause));
23
- return prereqs.map(
24
- (prereq, i) => (
25
- // Each prereq pairs its own kind with its detail, so the widened
26
- // `resolve` return is safe to narrow back to the discriminated union.
27
- prereq.resolve(
28
- failureSlice(ranges[i].end - ranges[i].start, error)
29
- )
30
- )
31
- );
32
- }
33
- return prereqs.map(
34
- (prereq, i) => prereq.resolve(
35
- results.slice(ranges[i].start, ranges[i].end)
36
- )
37
- );
38
- }
39
- function failureSlice(n, error) {
40
- return Array.from({ length: n }, () => ({
41
- status: "failure",
42
- error
43
- }));
44
- }
45
- export {
46
- verifyPrerequisites
47
- };
File without changes
@@ -1,4 +0,0 @@
1
- const ETH_SIMULATE_V1_NETWORKS = /* @__PURE__ */ new Set(["Mainnet", "Plasma", "Somnia"]);
2
- export {
3
- ETH_SIMULATE_V1_NETWORKS
4
- };
@@ -1,75 +0,0 @@
1
- import {
2
- BaseError,
3
- ContractFunctionRevertedError,
4
- decodeErrorResult
5
- } from "viem";
6
- import { errorAbis } from "../../abi/errors.js";
7
- class PreviewSimulationError extends BaseError {
8
- name = "PreviewSimulationError";
9
- /** Per-flow decoded failures behind this error. */
10
- failures;
11
- constructor(failures) {
12
- const shortMessage = failures.length <= 1 ? failures[0]?.detail.reason ?? "simulation failed" : "all simulation flows failed";
13
- const cause = failures.find((f) => f.detail.cause instanceof Error)?.detail.cause;
14
- super(shortMessage, {
15
- metaMessages: failures.map((f) => `[${f.source}] ${f.detail.reason}`),
16
- cause
17
- });
18
- this.failures = failures;
19
- }
20
- }
21
- function asPreviewSimulationError(reason, source) {
22
- if (reason instanceof PreviewSimulationError) {
23
- return reason;
24
- }
25
- const error = reason instanceof Error ? reason : new Error(String(reason));
26
- return new PreviewSimulationError([
27
- { source, detail: decodeSimulationError({ error }) }
28
- ]);
29
- }
30
- function combinePreviewSimulationErrors(...errors) {
31
- return new PreviewSimulationError(
32
- errors.filter((e) => e).flatMap((e) => e?.failures ?? [])
33
- );
34
- }
35
- function decodeSimulationError(revert) {
36
- const { error, data } = revert;
37
- if (data && data !== "0x") {
38
- try {
39
- const decoded = decodeErrorResult({ abi: errorAbis, data });
40
- return {
41
- reason: formatDecodedError(decoded.errorName, decoded.args),
42
- cause: error
43
- };
44
- } catch {
45
- }
46
- }
47
- if (error instanceof BaseError) {
48
- const reverted = error.walk(
49
- (e) => e instanceof ContractFunctionRevertedError
50
- );
51
- if (reverted instanceof ContractFunctionRevertedError) {
52
- return {
53
- reason: reverted.data?.errorName ?? reverted.reason ?? reverted.shortMessage ?? "reverted",
54
- cause: error
55
- };
56
- }
57
- return { reason: error.shortMessage ?? error.name, cause: error };
58
- }
59
- if (error instanceof Error) {
60
- return { reason: error.message, cause: error };
61
- }
62
- return { reason: "reverted", cause: error };
63
- }
64
- function formatDecodedError(errorName, args) {
65
- if (!args || args.length === 0) {
66
- return errorName;
67
- }
68
- return `${errorName}(${args.map((arg) => String(arg)).join(", ")})`;
69
- }
70
- export {
71
- PreviewSimulationError,
72
- asPreviewSimulationError,
73
- combinePreviewSimulationErrors,
74
- decodeSimulationError
75
- };
@@ -1,23 +0,0 @@
1
- import { isAddressEqual, parseEventLogs } from "viem";
2
- import { ierc20Abi } from "../../abi/iERC20.js";
3
- function extractERC20Transfers(logs, watch) {
4
- const parsed = parseEventLogs({
5
- abi: ierc20Abi,
6
- eventName: "Transfer",
7
- logs
8
- });
9
- const transfers = [];
10
- for (const log of parsed) {
11
- const { from, to, value } = log.args;
12
- const involved = watch.some(
13
- (address) => isAddressEqual(from, address) || isAddressEqual(to, address)
14
- );
15
- if (involved) {
16
- transfers.push({ token: log.address, amount: value, from, to });
17
- }
18
- }
19
- return transfers;
20
- }
21
- export {
22
- extractERC20Transfers
23
- };
@@ -1,21 +0,0 @@
1
- import { AddressSet } from "../../sdk/index.js";
2
- function sourceHolder(operation, wallet) {
3
- switch (operation.operation) {
4
- case "Deposit":
5
- case "Mint":
6
- return wallet;
7
- case "Withdraw":
8
- case "Redeem":
9
- return operation.owner;
10
- }
11
- }
12
- function watchedHolders(operation, wallet) {
13
- const holders = new AddressSet([
14
- sourceHolder(operation, wallet),
15
- operation.receiver
16
- ]);
17
- return holders.asArray();
18
- }
19
- export {
20
- watchedHolders
21
- };
@@ -1,12 +0,0 @@
1
- import { ETH_SIMULATE_V1_NETWORKS } from "./constants.js";
2
- import { PreviewSimulationError } from "./errors.js";
3
- import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
4
- import { simulateOperation } from "./simulateOperation.js";
5
- import { simulatePoolOperation } from "./simulatePoolOperation.js";
6
- export {
7
- ETH_SIMULATE_V1_NETWORKS,
8
- PreviewSimulationError,
9
- simulateFacadeOperation,
10
- simulateOperation,
11
- simulatePoolOperation
12
- };
@@ -1,6 +0,0 @@
1
- async function simulateFacadeOperation(_input, _options) {
2
- throw new Error("not yet implemented");
3
- }
4
- export {
5
- simulateFacadeOperation
6
- };
@@ -1,13 +0,0 @@
1
- import { isPoolOperation } from "../parse/index.js";
2
- import { simulateFacadeOperation } from "./simulateFacadeOperation.js";
3
- import { simulatePoolOperation } from "./simulatePoolOperation.js";
4
- async function simulateOperation(input, options) {
5
- const { operation } = input;
6
- if (isPoolOperation(operation)) {
7
- return simulatePoolOperation({ ...input, operation }, options);
8
- }
9
- return simulateFacadeOperation({ ...input, operation }, options);
10
- }
11
- export {
12
- simulateOperation
13
- };
@@ -1,130 +0,0 @@
1
- import { iPoolV310Abi } from "../../abi/310/generated.js";
2
- import { ierc20Abi } from "../../abi/iERC20.js";
3
- import { AddressMap } from "../../sdk/index.js";
4
- import { decodeSimulationError, PreviewSimulationError } from "./errors.js";
5
- import { watchedHolders } from "./holders.js";
6
- function previewRead(operation) {
7
- switch (operation.operation) {
8
- case "Deposit":
9
- return { functionName: "previewDeposit", amount: operation.assets };
10
- case "Mint":
11
- return { functionName: "previewMint", amount: operation.shares };
12
- case "Withdraw":
13
- return { functionName: "previewWithdraw", amount: operation.assets };
14
- case "Redeem":
15
- return { functionName: "previewRedeem", amount: operation.shares };
16
- }
17
- }
18
- async function simulatePoolOpMulticall(input, options = {}) {
19
- const { sdk, operation, wallet } = input;
20
- const { blockNumber } = options;
21
- const { underlying, pool } = operation;
22
- const holders = watchedHolders(operation, wallet);
23
- const tokens = [underlying, pool];
24
- const balanceCalls = holders.flatMap(
25
- (holder) => tokens.map((token) => ({ holder, token }))
26
- );
27
- const balanceContracts = balanceCalls.map(
28
- ({ holder, token }) => ({
29
- address: token,
30
- abi: ierc20Abi,
31
- functionName: "balanceOf",
32
- args: [holder]
33
- })
34
- );
35
- const { functionName, amount } = previewRead(operation);
36
- const previewContract = {
37
- address: pool,
38
- abi: iPoolV310Abi,
39
- functionName,
40
- args: [amount]
41
- };
42
- let results;
43
- try {
44
- results = await sdk.client.multicall({
45
- allowFailure: false,
46
- // `undefined` lets viem read at `latest`; `blockNumber` is only set for
47
- // testnet forks pinned to a specific block.
48
- blockNumber,
49
- contracts: [...balanceContracts, previewContract]
50
- });
51
- } catch (cause) {
52
- throw new PreviewSimulationError([
53
- {
54
- source: "multicall",
55
- detail: decodeSimulationError({
56
- error: cause instanceof Error ? cause : new Error(String(cause))
57
- })
58
- }
59
- ]);
60
- }
61
- const previewAmount = results[balanceContracts.length];
62
- const balances = new AddressMap();
63
- for (const [i, { holder, token }] of balanceCalls.entries()) {
64
- const tokenBalances = balances.get(holder) ?? new AddressMap();
65
- tokenBalances.upsert(token, results[i]);
66
- balances.upsert(holder, tokenBalances);
67
- }
68
- const before = (token, holder) => balances.get(holder)?.get(token) ?? 0n;
69
- return {
70
- balanceChanges: computePoolOpBalanceChanges(
71
- operation,
72
- wallet,
73
- previewAmount,
74
- before
75
- ),
76
- transfers: void 0
77
- };
78
- }
79
- function balanceLegs(operation, wallet, previewAmount) {
80
- const { underlying, pool, receiver } = operation;
81
- switch (operation.operation) {
82
- case "Deposit":
83
- return [
84
- { address: wallet, token: underlying, delta: -operation.assets },
85
- { address: receiver, token: pool, delta: previewAmount }
86
- ];
87
- case "Mint":
88
- return [
89
- { address: wallet, token: underlying, delta: -previewAmount },
90
- { address: receiver, token: pool, delta: operation.shares }
91
- ];
92
- case "Withdraw":
93
- return [
94
- { address: operation.owner, token: pool, delta: -previewAmount },
95
- { address: receiver, token: underlying, delta: operation.assets }
96
- ];
97
- case "Redeem":
98
- return [
99
- { address: operation.owner, token: pool, delta: -operation.shares },
100
- { address: receiver, token: underlying, delta: previewAmount }
101
- ];
102
- }
103
- }
104
- function computePoolOpBalanceChanges(operation, wallet, previewAmount, before) {
105
- const byAddress = new AddressMap();
106
- for (const { address, token, delta } of balanceLegs(
107
- operation,
108
- wallet,
109
- previewAmount
110
- )) {
111
- const beforeBalance = before(token, address);
112
- const change = {
113
- token,
114
- before: beforeBalance,
115
- after: beforeBalance + delta,
116
- delta
117
- };
118
- const existing = byAddress.get(address);
119
- if (existing) {
120
- existing.changes.push(change);
121
- } else {
122
- byAddress.upsert(address, { address, changes: [change] });
123
- }
124
- }
125
- return byAddress.values();
126
- }
127
- export {
128
- computePoolOpBalanceChanges,
129
- simulatePoolOpMulticall
130
- };
@@ -1,82 +0,0 @@
1
- import { simulateCalls } from "viem/actions";
2
- import { ierc20Abi } from "../../abi/iERC20.js";
3
- import { decodeSimulationError, PreviewSimulationError } from "./errors.js";
4
- import { extractERC20Transfers } from "./extractERC20Transfers.js";
5
- import { watchedHolders } from "./holders.js";
6
- async function simulatePoolOpV1(input, options = {}) {
7
- const { sdk, operation, to, calldata, wallet } = input;
8
- const { blockNumber } = options;
9
- const { underlying, pool } = operation;
10
- const holders = watchedHolders(operation, wallet);
11
- const tokens = [underlying, pool];
12
- const balanceOf = (token, holder) => ({
13
- to: token,
14
- abi: ierc20Abi,
15
- functionName: "balanceOf",
16
- args: [holder]
17
- });
18
- const balanceCalls = holders.flatMap(
19
- (holder) => tokens.map((token) => balanceOf(token, holder))
20
- );
21
- let results;
22
- try {
23
- ({ results } = await simulateCalls(sdk.client, {
24
- account: wallet,
25
- // `undefined` lets viem simulate at `latest`; `blockNumber` is only set
26
- // for testnet forks pinned to a specific block.
27
- blockNumber,
28
- calls: [...balanceCalls, { to, data: calldata }, ...balanceCalls]
29
- }));
30
- } catch (cause) {
31
- throw new PreviewSimulationError([
32
- {
33
- source: "eth_simulateV1",
34
- detail: decodeSimulationError({
35
- error: cause instanceof Error ? cause : new Error(String(cause))
36
- })
37
- }
38
- ]);
39
- }
40
- const sim = results;
41
- const txIndex = balanceCalls.length;
42
- const afterOffset = txIndex + 1;
43
- const txResult = sim[txIndex];
44
- if (!txResult || txResult.status === "failure") {
45
- throw new PreviewSimulationError([
46
- {
47
- source: "eth_simulateV1",
48
- detail: decodeSimulationError({
49
- error: txResult?.error,
50
- data: txResult?.data
51
- })
52
- }
53
- ]);
54
- }
55
- const balanceChanges = [];
56
- for (const [holderIndex, address] of holders.entries()) {
57
- const changes = [];
58
- for (const [tokenIndex, token] of tokens.entries()) {
59
- const slot = holderIndex * tokens.length + tokenIndex;
60
- const before = readBalance(sim[slot]);
61
- const after = readBalance(sim[afterOffset + slot]);
62
- const delta = after - before;
63
- const magnitude = delta >= 0n ? delta : -delta;
64
- if (magnitude > 1n) {
65
- changes.push({ token, before, after, delta });
66
- }
67
- }
68
- if (changes.length > 0) {
69
- balanceChanges.push({ address, changes });
70
- }
71
- }
72
- return {
73
- transfers: extractERC20Transfers(txResult.logs ?? [], holders),
74
- balanceChanges
75
- };
76
- }
77
- function readBalance(result) {
78
- return result?.status === "success" ? result.result : 0n;
79
- }
80
- export {
81
- simulatePoolOpV1
82
- };
@@ -1,41 +0,0 @@
1
- import { ETH_SIMULATE_V1_NETWORKS } from "./constants.js";
2
- import {
3
- asPreviewSimulationError,
4
- combinePreviewSimulationErrors
5
- } from "./errors.js";
6
- import { simulatePoolOpMulticall } from "./simulatePoolOpMulticall.js";
7
- import { simulatePoolOpV1 } from "./simulatePoolOpV1.js";
8
- async function simulatePoolOperation(input, options = {}) {
9
- const { sdk } = input;
10
- const { logger } = options;
11
- const useSimulateV1 = options.useSimulateV1 ?? ETH_SIMULATE_V1_NETWORKS.has(sdk.networkType);
12
- logger?.debug(
13
- { wallet: input.wallet, to: input.to },
14
- "simulating pool operation"
15
- );
16
- const [v1, multicall] = await Promise.allSettled([
17
- useSimulateV1 ? simulatePoolOpV1(input, options) : void 0,
18
- simulatePoolOpMulticall(input, options)
19
- ]);
20
- if (v1.status === "fulfilled" && v1.value) {
21
- return { status: "success", ...v1.value };
22
- }
23
- if (multicall.status === "fulfilled") {
24
- if (v1.status === "rejected") {
25
- logger?.debug(
26
- asPreviewSimulationError(v1.reason, "eth_simulateV1"),
27
- "eth_simulateV1 flow failed; falling back to multicall result"
28
- );
29
- }
30
- return { status: "success", ...multicall.value };
31
- }
32
- const error = combinePreviewSimulationErrors(
33
- v1.status === "rejected" ? asPreviewSimulationError(v1.reason, "eth_simulateV1") : void 0,
34
- asPreviewSimulationError(multicall.reason, "multicall")
35
- );
36
- logger?.error(error, "pool operation simulation failed");
37
- return { status: "failure", error };
38
- }
39
- export {
40
- simulatePoolOperation
41
- };
File without changes
@@ -1,40 +0,0 @@
1
- import {
2
- decodeAbiParameters,
3
- isAddressEqual,
4
- toFunctionSelector
5
- } from "viem";
6
- import {
7
- resolveProtocolCall
8
- } from "../../common-utils/utils/trace.js";
9
- const WITHDRAW_PHANTOM_TOKEN_SELECTOR = toFunctionSelector(
10
- "withdrawPhantomToken(address,uint256)"
11
- );
12
- const GET_PHANTOM_TOKEN_INFO_SELECTOR = toFunctionSelector(
13
- "getPhantomTokenInfo()"
14
- );
15
- function isSynthesizedPhantomWithdrawal(siblings, index) {
16
- const node = siblings[index];
17
- if (node.type !== "CALL" || node.input.slice(0, 10).toLowerCase() !== WITHDRAW_PHANTOM_TOKEN_SELECTOR) {
18
- return false;
19
- }
20
- const [token] = decodeAbiParameters(
21
- [{ type: "address" }, { type: "uint256" }],
22
- `0x${node.input.slice(10)}`
23
- );
24
- for (let i = 0; i < index; i++) {
25
- const sib = siblings[i];
26
- if (sib.type === "STATICCALL" && sib.input.slice(0, 10).toLowerCase() === GET_PHANTOM_TOKEN_INFO_SELECTOR && isAddressEqual(sib.to, token)) {
27
- return true;
28
- }
29
- }
30
- return false;
31
- }
32
- function extractAdapterCallTraces(facadeTrace) {
33
- const subtraces = facadeTrace.calls ?? [];
34
- return subtraces.filter(
35
- (sub, index) => resolveProtocolCall(sub) !== void 0 && !isSynthesizedPhantomWithdrawal(subtraces, index)
36
- );
37
- }
38
- export {
39
- extractAdapterCallTraces
40
- };
@@ -1,5 +0,0 @@
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";
File without changes
@@ -1,73 +0,0 @@
1
- import { type Address, type Hex } from "viem";
2
- /**
3
- * A single frame from Ethereum's `debug_traceTransaction` callTracer output.
4
- * Recursive: each frame may contain nested sub-calls.
5
- */
6
- export interface CallTrace {
7
- from: Address;
8
- to: Address;
9
- input: Hex;
10
- output: Hex;
11
- value: Hex;
12
- /** "CALL", "DELEGATECALL", "STATICCALL", "CREATE", etc. */
13
- type: string;
14
- /** Present when the call reverted (e.g. "execution reverted"). */
15
- error?: string;
16
- /** ABI-encoded revert data, if available. */
17
- revertReason?: Hex;
18
- calls?: CallTrace[];
19
- }
20
- /**
21
- * Selector of `CreditManagerV3.execute(bytes)` (`0x09c5eabe`).
22
- *
23
- * This is the authoritative marker of an adapter performing an external
24
- * protocol call: the adapter calls the credit manager's `execute(bytes)`, which
25
- * forwards the calldata to the credit account, which in turn CALLs the target
26
- * (protocol) contract. Adapter approvals use a different selector
27
- * (`execute(address,bytes)` on the credit account), so matching on this
28
- * selector isolates the real protocol call.
29
- */
30
- export declare const EXECUTE_BYTES_SELECTOR: "0x09c5eabe";
31
- /**
32
- * Finds the shallowest non-reverted `CreditManager.execute(bytes)` call in a
33
- * trace subtree (breadth-first), or `undefined` if none exists.
34
- *
35
- * "Shallowest" matters for account migration: a migrate adapter nests the
36
- * entire target `openCreditAccount` multicall - including that account's own
37
- * `execute(bytes)` calls - inside its subtree. The shallowest match is the
38
- * adapter's own protocol call, not a nested one.
39
- */
40
- export declare function findExecuteBytes(node: CallTrace): CallTrace | undefined;
41
- /**
42
- * Finds the first non-reverted CALL in a subtree whose `input` exactly matches
43
- * `input` (case-insensitive). Used to locate the leaf CALL to the target
44
- * contract: `execute(bytes)` forwards the calldata unchanged through the credit
45
- * account proxy DELEGATECALL down to the final CALL to the protocol contract.
46
- */
47
- export declare function findCallWithInput(node: CallTrace, input: Hex): CallTrace | undefined;
48
- /**
49
- * Resolves the external protocol call performed by an adapter-level call trace.
50
- *
51
- * Locates the shallowest `CreditManager.execute(bytes)`, decodes the forwarded
52
- * calldata, then finds the leaf CALL whose input matches that calldata to
53
- * recover the target (protocol) contract address. Returns `undefined` when the
54
- * subtree does not actually reach an external protocol CALL (e.g. the
55
- * facade-internal `depositPhantomToken` / `withdrawPhantomToken` accounting
56
- * calls, which forward calldata but make no external CALL).
57
- *
58
- * @param node - direct child node of the upper-level facade call trace
59
- */
60
- export declare function resolveProtocolCall(node: CallTrace): {
61
- contract: Address;
62
- calldata: Hex;
63
- } | undefined;
64
- /**
65
- * Finds the first non-reverted CALL to `target` anywhere in a trace subtree.
66
- */
67
- export declare function findCallTo(node: CallTrace, target: Address): CallTrace | undefined;
68
- /**
69
- * DFS walk of the call trace tree, collecting non-reverted CALL entries
70
- * to the given address.
71
- * Does not recurse into children of matched nodes
72
- */
73
- export declare function collectTraces(node: CallTrace, target: Address): CallTrace[];
@@ -1,82 +0,0 @@
1
- import type { Address, PublicClient } from "viem";
2
- /**
3
- * Address is stable, contract deployed via create2
4
- */
5
- export declare const ONCHAIN_EXECUTION_ID_ADDRESS: Address;
6
- /**
7
- * This contract is deployed on every Gearbox testnet and contains
8
- * execution id and alias of the testnet
9
- */
10
- export declare const iOnchainExecutionIdAbi: readonly [{
11
- readonly type: "function";
12
- readonly name: "deployer";
13
- readonly inputs: readonly [];
14
- readonly outputs: readonly [{
15
- readonly name: "";
16
- readonly type: "string";
17
- readonly internalType: "string";
18
- }];
19
- readonly stateMutability: "view";
20
- }, {
21
- readonly type: "function";
22
- readonly name: "executionId";
23
- readonly inputs: readonly [];
24
- readonly outputs: readonly [{
25
- readonly name: "";
26
- readonly type: "string";
27
- readonly internalType: "string";
28
- }];
29
- readonly stateMutability: "view";
30
- }, {
31
- readonly type: "function";
32
- readonly name: "forkAlias";
33
- readonly inputs: readonly [];
34
- readonly outputs: readonly [{
35
- readonly name: "";
36
- readonly type: "string";
37
- readonly internalType: "string";
38
- }];
39
- readonly stateMutability: "view";
40
- }, {
41
- readonly type: "function";
42
- readonly name: "info";
43
- readonly inputs: readonly [];
44
- readonly outputs: readonly [{
45
- readonly name: "";
46
- readonly type: "tuple";
47
- readonly internalType: "struct ExecutionId.Info";
48
- readonly components: readonly [{
49
- readonly name: "deployer";
50
- readonly type: "string";
51
- readonly internalType: "string";
52
- }, {
53
- readonly name: "executionId";
54
- readonly type: "string";
55
- readonly internalType: "string";
56
- }, {
57
- readonly name: "forkAlias";
58
- readonly type: "string";
59
- readonly internalType: "string";
60
- }];
61
- }];
62
- readonly stateMutability: "view";
63
- }];
64
- export type VerifyTestnetParams = {
65
- executionId: string;
66
- } | {
67
- alias: string;
68
- } | {
69
- executionId: string;
70
- alias: string;
71
- };
72
- /**
73
- * Tries to read the contract that is deployed on every Gearbox testnet
74
- * and verify that we're on expected testnet.
75
- *
76
- * Used to check that wallet is using correct RPC for the testnet.
77
- *
78
- * @param client - Public client
79
- * @param expected - Expected tesnet alias or execution id
80
- * @returns True if we're on expected testnet
81
- */
82
- export declare function verifyTestnet(client: PublicClient, expected: VerifyTestnetParams): Promise<boolean>;