@gearbox-protocol/sdk 3.0.0-vfourabi.1 → 3.0.0-vfourabi.3

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 (275) hide show
  1. package/.eslintignore +3 -0
  2. package/.github/workflows/lint_pr.yml +18 -0
  3. package/.github/workflows/pr.yml +39 -0
  4. package/.github/workflows/release.yml +47 -0
  5. package/.gitignore +19 -0
  6. package/.husky/commit-msg +1 -0
  7. package/.husky/pre-commit +1 -0
  8. package/.nvmrc +1 -0
  9. package/.releaserc.json +34 -0
  10. package/.vscode/extensions.json +7 -0
  11. package/.vscode/settings.json +16 -0
  12. package/.yarn/install-state.gz +0 -0
  13. package/.yarnrc.yml +1 -0
  14. package/ContributionAgreement +72 -0
  15. package/dist/cjs/abi/iZapper.cjs +85 -0
  16. package/dist/cjs/abi/iZapper.d.ts +123 -0
  17. package/dist/cjs/sdk/index.cjs +19830 -19764
  18. package/dist/cjs/sdk/index.d.ts +3746 -3061
  19. package/dist/esm/abi/iZapper.d.mts +123 -0
  20. package/dist/esm/abi/iZapper.mjs +83 -0
  21. package/dist/esm/sdk/index.d.mts +3746 -3061
  22. package/dist/esm/sdk/index.mjs +19807 -19765
  23. package/jest.config.js +7 -0
  24. package/package.json +32 -2
  25. package/scripts/example.ts +30 -0
  26. package/src/abi/compressors.ts +3962 -0
  27. package/src/abi/errors.ts +196 -0
  28. package/src/abi/iERC20.ts +122 -0
  29. package/src/abi/iPausable.ts +35 -0
  30. package/src/abi/iPriceFeedStore.ts +227 -0
  31. package/src/abi/iUpdatablePriceFeed.ts +16 -0
  32. package/src/abi/iVersion.ts +28 -0
  33. package/src/abi/iZapper.ts +84 -0
  34. package/src/abi/routerV300.ts +378 -0
  35. package/src/abi/v300.ts +4151 -0
  36. package/src/abi/v310.ts +5179 -0
  37. package/src/adapters/AbstractAdapter.ts +28 -0
  38. package/src/adapters/BalancerV2VaultAdapterContract.ts +19 -0
  39. package/src/adapters/BalancerV3RouterAdapterContract.ts +19 -0
  40. package/src/adapters/CamelotV3AdapterContract.ts +20 -0
  41. package/src/adapters/ConvexV1BaseRewardPoolAdapterContract.ts +20 -0
  42. package/src/adapters/ConvexV1BoosterAdapterContract.ts +20 -0
  43. package/src/adapters/Curve2AssetsAdapterContract.ts +20 -0
  44. package/src/adapters/Curve3AssetsAdapterContract.ts +20 -0
  45. package/src/adapters/Curve4AssetsAdapterContract.ts +20 -0
  46. package/src/adapters/CurveV1AdapterStETHContract.ts +20 -0
  47. package/src/adapters/CurveV1StableNGAdapterContract.ts +20 -0
  48. package/src/adapters/DaiUsdsAdapterContract.ts +21 -0
  49. package/src/adapters/ERC4626AdapterContract.ts +20 -0
  50. package/src/adapters/MellowERC4626VaultAdapterContract.ts +20 -0
  51. package/src/adapters/MellowVaultAdapterContract.ts +20 -0
  52. package/src/adapters/PendleRouterAdapterContract.ts +21 -0
  53. package/src/adapters/StakingRewardsAdapterContract.ts +21 -0
  54. package/src/adapters/UniswapV2AdapterContract.ts +20 -0
  55. package/src/adapters/UniswapV3AdapterContract.ts +170 -0
  56. package/src/adapters/VelodromeV2AdapterContract.ts +20 -0
  57. package/src/adapters/WstETHV1AdapterContract.ts +20 -0
  58. package/src/adapters/YearnV2AdapterContract.ts +20 -0
  59. package/src/adapters/abi/adapters.ts +4325 -0
  60. package/src/adapters/abi/iBalancerV3RouterAdapter.ts +126 -0
  61. package/src/adapters/abi/index.ts +2 -0
  62. package/src/adapters/index.ts +2 -0
  63. package/src/adapters/plugin.ts +90 -0
  64. package/src/adapters/types.ts +62 -0
  65. package/src/dev/AccountOpener.ts +611 -0
  66. package/src/dev/PriceFeedStore.ts +95 -0
  67. package/src/dev/SDKExample.ts +167 -0
  68. package/src/dev/abi.ts +14 -0
  69. package/src/dev/calcLiquidatableLTs.ts +77 -0
  70. package/src/dev/createAnvilClient.ts +155 -0
  71. package/src/dev/index.ts +7 -0
  72. package/src/dev/setLTZero.ts +127 -0
  73. package/src/dev/setLTs.ts +68 -0
  74. package/src/sdk/GearboxSDK.ts +488 -0
  75. package/src/sdk/abi/index.ts +1 -0
  76. package/src/sdk/abi/oracles.ts +4614 -0
  77. package/src/sdk/accounts/CreditAccountsService.ts +1123 -0
  78. package/src/sdk/accounts/index.ts +1 -0
  79. package/src/sdk/base/AddressLabeller.ts +35 -0
  80. package/src/sdk/base/BaseContract.ts +237 -0
  81. package/src/sdk/base/IAddressLabeller.ts +13 -0
  82. package/src/sdk/base/PlaceholderContract.ts +12 -0
  83. package/src/sdk/base/SDKConstruct.ts +35 -0
  84. package/src/sdk/base/TokensMeta.ts +45 -0
  85. package/src/sdk/base/index.ts +6 -0
  86. package/src/sdk/base/types.ts +102 -0
  87. package/src/sdk/bots/BotsService.ts +92 -0
  88. package/src/sdk/bots/index.ts +2 -0
  89. package/src/sdk/bots/utils.ts +19 -0
  90. package/src/sdk/chain/Provider.ts +99 -0
  91. package/src/sdk/chain/chains.ts +41 -0
  92. package/src/sdk/chain/detectChain.ts +21 -0
  93. package/src/sdk/chain/index.ts +3 -0
  94. package/src/sdk/constants/address-provider.ts +47 -0
  95. package/src/sdk/constants/addresses.ts +82 -0
  96. package/src/sdk/constants/bot-permissions.ts +36 -0
  97. package/src/sdk/constants/index.ts +6 -0
  98. package/src/sdk/constants/math.ts +23 -0
  99. package/src/sdk/constants/networks.ts +38 -0
  100. package/src/sdk/constants/periphery.ts +7 -0
  101. package/src/sdk/core/BotListV3Contract.ts +103 -0
  102. package/src/sdk/core/GearStakingV3Contract.ts +84 -0
  103. package/src/sdk/core/address-provider/AbstractAddressProviderContract.ts +101 -0
  104. package/src/sdk/core/address-provider/AddressProviderV3Contract.ts +105 -0
  105. package/src/sdk/core/address-provider/AddressProviderV3_1Contract.ts +92 -0
  106. package/src/sdk/core/address-provider/getAddressProvider.ts +45 -0
  107. package/src/sdk/core/address-provider/index.ts +4 -0
  108. package/src/sdk/core/address-provider/types.ts +17 -0
  109. package/src/sdk/core/index.ts +3 -0
  110. package/src/sdk/gauges/GaugeStakingService.ts +100 -0
  111. package/src/sdk/gauges/index.ts +2 -0
  112. package/src/sdk/gauges/utils.ts +25 -0
  113. package/src/sdk/index.ts +17 -0
  114. package/src/sdk/market/MarketConfiguratorContract.ts +78 -0
  115. package/src/sdk/market/MarketRegister.ts +330 -0
  116. package/src/sdk/market/MarketSuite.ts +83 -0
  117. package/src/sdk/market/adapters/PlaceholderAdapterContracts.ts +18 -0
  118. package/src/sdk/market/adapters/factory.ts +34 -0
  119. package/src/sdk/market/adapters/index.ts +3 -0
  120. package/src/sdk/market/adapters/types.ts +7 -0
  121. package/src/sdk/market/credit/CreditConfiguratorV300Contract.ts +164 -0
  122. package/src/sdk/market/credit/CreditConfiguratorV310Contract.ts +139 -0
  123. package/src/sdk/market/credit/CreditFacadeV300Contract.ts +206 -0
  124. package/src/sdk/market/credit/CreditFacadeV310Contract.ts +190 -0
  125. package/src/sdk/market/credit/CreditManagerV300Contract.ts +122 -0
  126. package/src/sdk/market/credit/CreditManagerV310Contract.ts +122 -0
  127. package/src/sdk/market/credit/CreditSuite.ts +65 -0
  128. package/src/sdk/market/credit/createCreditConfigurator.ts +18 -0
  129. package/src/sdk/market/credit/createCreditFacade.ts +18 -0
  130. package/src/sdk/market/credit/createCreditManager.ts +18 -0
  131. package/src/sdk/market/credit/index.ts +8 -0
  132. package/src/sdk/market/credit/types.ts +42 -0
  133. package/src/sdk/market/index.ts +7 -0
  134. package/src/sdk/market/oracle/PriceOracleBaseContract.ts +376 -0
  135. package/src/sdk/market/oracle/PriceOracleV300Contract.ts +71 -0
  136. package/src/sdk/market/oracle/PriceOracleV310Contract.ts +43 -0
  137. package/src/sdk/market/oracle/createPriceOracle.ts +22 -0
  138. package/src/sdk/market/oracle/index.ts +4 -0
  139. package/src/sdk/market/oracle/types.ts +48 -0
  140. package/src/sdk/market/pool/GaugeContract.ts +120 -0
  141. package/src/sdk/market/pool/LinearInterestRateModelContract.ts +75 -0
  142. package/src/sdk/market/pool/PoolQuotaKeeperV300Contract.ts +89 -0
  143. package/src/sdk/market/pool/PoolQuotaKeeperV310Contract.ts +89 -0
  144. package/src/sdk/market/pool/PoolSuite.ts +76 -0
  145. package/src/sdk/market/pool/PoolV300Contract.ts +144 -0
  146. package/src/sdk/market/pool/PoolV310Contract.ts +144 -0
  147. package/src/sdk/market/pool/TumblerContract.ts +73 -0
  148. package/src/sdk/market/pool/createInterestRateModel.ts +33 -0
  149. package/src/sdk/market/pool/createPool.ts +19 -0
  150. package/src/sdk/market/pool/createPoolQuotaKeeper.ts +20 -0
  151. package/src/sdk/market/pool/createRateKeeper.ts +25 -0
  152. package/src/sdk/market/pool/index.ts +6 -0
  153. package/src/sdk/market/pool/types.ts +28 -0
  154. package/src/sdk/market/pricefeeds/AbstractLPPriceFeed.ts +71 -0
  155. package/src/sdk/market/pricefeeds/AbstractPriceFeed.ts +137 -0
  156. package/src/sdk/market/pricefeeds/BalancerStablePriceFeed.ts +24 -0
  157. package/src/sdk/market/pricefeeds/BalancerWeightedPriceFeed.ts +70 -0
  158. package/src/sdk/market/pricefeeds/BoundedPriceFeed.ts +34 -0
  159. package/src/sdk/market/pricefeeds/ChainlinkPriceFeed.ts +16 -0
  160. package/src/sdk/market/pricefeeds/CompositePriceFeed.ts +25 -0
  161. package/src/sdk/market/pricefeeds/CurveCryptoPriceFeed.ts +24 -0
  162. package/src/sdk/market/pricefeeds/CurveStablePriceFeed.ts +24 -0
  163. package/src/sdk/market/pricefeeds/CurveUSDPriceFeed.ts +24 -0
  164. package/src/sdk/market/pricefeeds/Erc4626PriceFeed.ts +36 -0
  165. package/src/sdk/market/pricefeeds/MellowLRTPriceFeed.ts +26 -0
  166. package/src/sdk/market/pricefeeds/PendleTWAPPTPriceFeed.ts +44 -0
  167. package/src/sdk/market/pricefeeds/PriceFeedRef.ts +34 -0
  168. package/src/sdk/market/pricefeeds/PriceFeedsRegister.ts +293 -0
  169. package/src/sdk/market/pricefeeds/RedstonePriceFeed.ts +65 -0
  170. package/src/sdk/market/pricefeeds/RedstoneUpdater.ts +304 -0
  171. package/src/sdk/market/pricefeeds/WstETHPriceFeed.ts +24 -0
  172. package/src/sdk/market/pricefeeds/YearnPriceFeed.ts +24 -0
  173. package/src/sdk/market/pricefeeds/ZeroPriceFeed.ts +17 -0
  174. package/src/sdk/market/pricefeeds/index.ts +20 -0
  175. package/src/sdk/market/pricefeeds/types.ts +82 -0
  176. package/src/sdk/market/pricefeeds/utils.ts +24 -0
  177. package/src/sdk/plugins/index.ts +10 -0
  178. package/src/sdk/router/PathOptionFactory.ts +147 -0
  179. package/src/sdk/router/RouterV3Contract.ts +558 -0
  180. package/src/sdk/router/index.ts +2 -0
  181. package/src/sdk/router/types.ts +48 -0
  182. package/src/sdk/sdk-gov-legacy/contracts/adapters.ts +39 -0
  183. package/src/sdk/sdk-gov-legacy/contracts/contracts.ts +647 -0
  184. package/src/sdk/sdk-gov-legacy/contracts/index.ts +2 -0
  185. package/src/sdk/sdk-gov-legacy/core/constants.ts +11 -0
  186. package/src/sdk/sdk-gov-legacy/index.ts +4 -0
  187. package/src/sdk/sdk-gov-legacy/oracles/PriceFeedType.ts +24 -0
  188. package/src/sdk/sdk-gov-legacy/oracles/index.ts +1 -0
  189. package/src/sdk/sdk-gov-legacy/tokens/aave.ts +101 -0
  190. package/src/sdk/sdk-gov-legacy/tokens/aura.ts +284 -0
  191. package/src/sdk/sdk-gov-legacy/tokens/balancer.ts +421 -0
  192. package/src/sdk/sdk-gov-legacy/tokens/compound.ts +79 -0
  193. package/src/sdk/sdk-gov-legacy/tokens/convex.ts +561 -0
  194. package/src/sdk/sdk-gov-legacy/tokens/curveLP.ts +480 -0
  195. package/src/sdk/sdk-gov-legacy/tokens/decimals.ts +301 -0
  196. package/src/sdk/sdk-gov-legacy/tokens/erc4626.ts +75 -0
  197. package/src/sdk/sdk-gov-legacy/tokens/gear.ts +273 -0
  198. package/src/sdk/sdk-gov-legacy/tokens/index.ts +18 -0
  199. package/src/sdk/sdk-gov-legacy/tokens/normal.ts +613 -0
  200. package/src/sdk/sdk-gov-legacy/tokens/quoted.ts +10 -0
  201. package/src/sdk/sdk-gov-legacy/tokens/stakingRewards.ts +41 -0
  202. package/src/sdk/sdk-gov-legacy/tokens/token.ts +2354 -0
  203. package/src/sdk/sdk-gov-legacy/tokens/tokenData.ts +44 -0
  204. package/src/sdk/sdk-gov-legacy/tokens/tokenType.ts +33 -0
  205. package/src/sdk/sdk-gov-legacy/tokens/wrapped.ts +28 -0
  206. package/src/sdk/sdk-gov-legacy/tokens/yearn.ts +122 -0
  207. package/src/sdk/sdk-gov-legacy/tokens/zircuit.ts +44 -0
  208. package/src/sdk/sdk-legacy/apy/index.ts +149 -0
  209. package/src/sdk/sdk-legacy/core/assets.ts +200 -0
  210. package/src/sdk/sdk-legacy/core/creditAccount.spec.ts +1966 -0
  211. package/src/sdk/sdk-legacy/core/creditAccount.ts +816 -0
  212. package/src/sdk/sdk-legacy/core/creditManager.ts +316 -0
  213. package/src/sdk/sdk-legacy/core/creditSession.ts +352 -0
  214. package/src/sdk/sdk-legacy/core/endpoint.ts +131 -0
  215. package/src/sdk/sdk-legacy/core/eventOrTx.ts +101 -0
  216. package/src/sdk/sdk-legacy/core/pool.ts +439 -0
  217. package/src/sdk/sdk-legacy/core/strategy.ts +82 -0
  218. package/src/sdk/sdk-legacy/core/transactions.ts +865 -0
  219. package/src/sdk/sdk-legacy/gearboxRewards/api.ts +704 -0
  220. package/src/sdk/sdk-legacy/gearboxRewards/apy.ts +267 -0
  221. package/src/sdk/sdk-legacy/gearboxRewards/extraAPY.ts +165 -0
  222. package/src/sdk/sdk-legacy/gearboxRewards/index.ts +3 -0
  223. package/src/sdk/sdk-legacy/gearboxRewards/merklAPI.ts +151 -0
  224. package/src/sdk/sdk-legacy/index.ts +21 -0
  225. package/src/sdk/sdk-legacy/pathfinder/core.ts +18 -0
  226. package/src/sdk/sdk-legacy/pathfinder/index.ts +1 -0
  227. package/src/sdk/sdk-legacy/payload/creditAccount.ts +48 -0
  228. package/src/sdk/sdk-legacy/payload/creditManager.ts +133 -0
  229. package/src/sdk/sdk-legacy/payload/creditSession.ts +143 -0
  230. package/src/sdk/sdk-legacy/payload/graphPayload.ts +10 -0
  231. package/src/sdk/sdk-legacy/payload/pool.ts +198 -0
  232. package/src/sdk/sdk-legacy/payload/token.ts +13 -0
  233. package/src/sdk/sdk-legacy/tokens/tokenData.ts +57 -0
  234. package/src/sdk/sdk-legacy/types/IAirdropDistributor.ts +103 -0
  235. package/src/sdk/sdk-legacy/types/IBaseRewardPool.ts +249 -0
  236. package/src/sdk/sdk-legacy/types/IDataCompressorV3.ts +957 -0
  237. package/src/sdk/sdk-legacy/types/IDegenDistributor.ts +70 -0
  238. package/src/sdk/sdk-legacy/types/IERC20Permit.ts +35 -0
  239. package/src/sdk/sdk-legacy/types/IERC20ZapperDeposits.ts +99 -0
  240. package/src/sdk/sdk-legacy/types/IETHZapperDeposits.ts +27 -0
  241. package/src/sdk/sdk-legacy/types/IFarmingPool.ts +229 -0
  242. package/src/sdk/sdk-legacy/types/IInterestRateModel.ts +23 -0
  243. package/src/sdk/sdk-legacy/types/IMulticall3.ts +242 -0
  244. package/src/sdk/sdk-legacy/types/IOffchainOracle.ts +31 -0
  245. package/src/sdk/sdk-legacy/types/index.ts +11 -0
  246. package/src/sdk/sdk-legacy/utils/formatter.ts +46 -0
  247. package/src/sdk/sdk-legacy/utils/index.ts +3 -0
  248. package/src/sdk/sdk-legacy/utils/math.ts +6 -0
  249. package/src/sdk/sdk-legacy/utils/price.ts +27 -0
  250. package/src/sdk/types/index.ts +5 -0
  251. package/src/sdk/types/logger.ts +13 -0
  252. package/src/sdk/types/state-human.ts +224 -0
  253. package/src/sdk/types/state.ts +8 -0
  254. package/src/sdk/types/transactions.ts +22 -0
  255. package/src/sdk/types/tvl.ts +4 -0
  256. package/src/sdk/utils/AddressMap.ts +111 -0
  257. package/src/sdk/utils/bytes32ToString.ts +6 -0
  258. package/src/sdk/utils/childLogger.ts +8 -0
  259. package/src/sdk/utils/createRawTx.ts +86 -0
  260. package/src/sdk/utils/etherscan.ts +42 -0
  261. package/src/sdk/utils/filterDust.ts +20 -0
  262. package/src/sdk/utils/formatter.ts +124 -0
  263. package/src/sdk/utils/index.ts +10 -0
  264. package/src/sdk/utils/internal/Hooks.ts +51 -0
  265. package/src/sdk/utils/internal/index.ts +1 -0
  266. package/src/sdk/utils/json.ts +27 -0
  267. package/src/sdk/utils/mappers.ts +38 -0
  268. package/src/sdk/utils/retry.ts +24 -0
  269. package/src/sdk/utils/viem/detectNetwork.ts +27 -0
  270. package/src/sdk/utils/viem/index.ts +3 -0
  271. package/src/sdk/utils/viem/sendRawTx.ts +36 -0
  272. package/src/sdk/utils/viem/simulateMulticall.ts +262 -0
  273. package/tsconfig.build.json +4 -0
  274. package/tsconfig.json +16 -0
  275. package/tsup.config.ts +77 -0
@@ -0,0 +1,111 @@
1
+ import type { Address } from "viem";
2
+ import { getAddress } from "viem";
3
+
4
+ export class AddressMap<T> {
5
+ #map: Map<Address, T>;
6
+ #frozen = false;
7
+ #name?: string;
8
+
9
+ constructor(entries?: Array<[string, T]>, name?: string) {
10
+ this.#map = new Map<Address, T>();
11
+ if (entries) {
12
+ for (const [address, value] of entries) {
13
+ const key = getAddress(address);
14
+ this.#map.set(key, value);
15
+ }
16
+ }
17
+ this.#name = name;
18
+ }
19
+
20
+ /**
21
+ * Adds or updates value
22
+ * @param address
23
+ * @param value
24
+ */
25
+ public upsert(address: string, value: T): void {
26
+ if (this.#frozen) {
27
+ throw new Error(`AddressMap ${this.#name} is frozen`);
28
+ }
29
+ const key = getAddress(address);
30
+ this.#map.set(key, value);
31
+ }
32
+
33
+ /**
34
+ * Adds value, throws if this address is already used
35
+ * @param address
36
+ * @param value
37
+ */
38
+ public insert(address: string, value: T): void {
39
+ if (this.#frozen) {
40
+ throw new Error(`AddressMap ${this.#name} is frozen`);
41
+ }
42
+ const key = getAddress(address);
43
+ if (this.#map.has(key)) {
44
+ throw new Error(
45
+ `address ${address} already exists in ${this.#name ?? "map"}`,
46
+ );
47
+ }
48
+ this.#map.set(key, value);
49
+ }
50
+
51
+ /**
52
+ * Checks if address is present in map
53
+ * @param address
54
+ * @returns
55
+ */
56
+ public has(address: string): boolean {
57
+ const key = getAddress(address);
58
+ return this.#map.has(key);
59
+ }
60
+
61
+ /**
62
+ * Returns value, or undefined if the address is not in map
63
+ * @param address
64
+ * @returns
65
+ */
66
+ public get(address: string): T | undefined {
67
+ const key = getAddress(address);
68
+ return this.#map.get(key);
69
+ }
70
+
71
+ /**
72
+ * Gets address from map, throws if not found
73
+ * @param address
74
+ * @returns
75
+ */
76
+ public mustGet(address: string): T {
77
+ const key = getAddress(address);
78
+ if (!this.#map.has(key)) {
79
+ throw new Error(`address ${address} not found in ${this.#name ?? "map"}`);
80
+ }
81
+ return this.#map.get(key)!;
82
+ }
83
+
84
+ public clear(): void {
85
+ this.#map.clear();
86
+ }
87
+
88
+ public entries(): Array<[Address, T]> {
89
+ return Array.from(this.#map.entries());
90
+ }
91
+
92
+ public values(): T[] {
93
+ return Array.from(this.#map.values());
94
+ }
95
+
96
+ public keys(): Address[] {
97
+ return Array.from(this.#map.keys());
98
+ }
99
+
100
+ public asRecord(): Record<Address, T> {
101
+ return Object.fromEntries(this.#map.entries());
102
+ }
103
+
104
+ public get size(): number {
105
+ return this.#map.size;
106
+ }
107
+
108
+ public freeze(): void {
109
+ this.#frozen = true;
110
+ }
111
+ }
@@ -0,0 +1,6 @@
1
+ import type { Hex } from "viem";
2
+ import { bytesToString, toBytes } from "viem";
3
+
4
+ export function bytes32ToString(bytes: Hex): string {
5
+ return bytesToString(toBytes(bytes)).replaceAll("\x00", "");
6
+ }
@@ -0,0 +1,8 @@
1
+ import type { ILogger } from "../types";
2
+
3
+ export function childLogger(
4
+ module: string,
5
+ logger?: ILogger,
6
+ ): ILogger | undefined {
7
+ return logger?.child?.({ module }) ?? logger;
8
+ }
@@ -0,0 +1,86 @@
1
+ import type {
2
+ Abi,
3
+ Address,
4
+ ContractFunctionName,
5
+ EncodeFunctionDataParameters,
6
+ Hex,
7
+ } from "viem";
8
+ import {
9
+ concatHex,
10
+ encodeAbiParameters,
11
+ prepareEncodeFunctionData,
12
+ } from "viem";
13
+ import { formatAbiItem } from "viem/utils";
14
+
15
+ import type { RawTx } from "../types";
16
+ import { json_stringify } from "./json";
17
+
18
+ /**
19
+ * @dev Creates a raw transaction data to be processed by the TxBatcher
20
+ * RawTx is a type that contains all the data needed to create different types of batches,
21
+ * like Multisig Safe batch over governor/timelock, or multisig direct call.
22
+ * Also RawTx data used to generate Governor execution batch, used to execute queued txs from EOA.
23
+ * @returns
24
+ */
25
+
26
+ export function createRawTx<
27
+ const abi extends Abi | readonly unknown[],
28
+ functionName extends ContractFunctionName<abi> | undefined = undefined,
29
+ >(
30
+ to: Address,
31
+ parameters: EncodeFunctionDataParameters<abi, functionName>,
32
+ description?: string,
33
+ ): RawTx {
34
+ const { args } = parameters as EncodeFunctionDataParameters;
35
+
36
+ const fname = parameters.functionName as string;
37
+
38
+ const { abi, functionName } = (() => {
39
+ if (
40
+ parameters.abi.length === 1 &&
41
+ parameters.functionName?.startsWith("0x")
42
+ )
43
+ return parameters as { abi: Abi; functionName: Hex };
44
+ return prepareEncodeFunctionData(parameters);
45
+ })();
46
+
47
+ const abiItem = abi[0];
48
+ const signature = functionName;
49
+
50
+ const data =
51
+ "inputs" in abiItem && abiItem.inputs
52
+ ? encodeAbiParameters(abiItem.inputs, args ?? [])
53
+ : undefined;
54
+ const functionEncodedData = concatHex([signature, data ?? "0x"]);
55
+
56
+ const inputs =
57
+ "inputs" in abiItem && abiItem.inputs ? [...abiItem.inputs] : [];
58
+
59
+ const payable = "payble" in abiItem ? abiItem.payble === true : false;
60
+
61
+ const contractInputsValues: Record<string, any> = {};
62
+
63
+ if (inputs.length > 0 && args && args.length !== 0) {
64
+ args.forEach((arg, i) => {
65
+ const methodName = inputs[i].name as string;
66
+ let stringifiedArg = arg instanceof BigInt ? arg.toString() : arg;
67
+ contractInputsValues[methodName] = Array.isArray(stringifiedArg)
68
+ ? json_stringify(stringifiedArg)
69
+ : stringifiedArg;
70
+ });
71
+ }
72
+
73
+ return {
74
+ to,
75
+ value: "0",
76
+ contractMethod: {
77
+ inputs,
78
+ name: fname,
79
+ payable,
80
+ },
81
+ signature: formatAbiItem(abiItem),
82
+ callData: functionEncodedData,
83
+ contractInputsValues,
84
+ description,
85
+ };
86
+ }
@@ -0,0 +1,42 @@
1
+ import type { TransactionReceipt } from "viem";
2
+
3
+ import type { CreditAccountData } from "../base";
4
+ import type { NetworkType } from "../chain";
5
+
6
+ export type EtherscanURLParam =
7
+ | { block: number }
8
+ | { tx: string }
9
+ | { address: string };
10
+
11
+ export function etherscanUrl(
12
+ entity: EtherscanURLParam | TransactionReceipt | CreditAccountData,
13
+ network: NetworkType,
14
+ ): string {
15
+ let [prefix, domain] = ["", "etherscan.io"];
16
+
17
+ let param: EtherscanURLParam;
18
+ if ("transactionHash" in entity && "blockHash" in entity) {
19
+ param = { tx: entity.transactionHash };
20
+ } else if ("creditAccount" in entity && "creditManager" in entity) {
21
+ param = { address: entity.creditAccount };
22
+ } else {
23
+ param = entity;
24
+ }
25
+
26
+ switch (network) {
27
+ case "Optimism":
28
+ prefix = "optimistic.";
29
+ break;
30
+ case "Arbitrum":
31
+ domain = "arbiscan.io";
32
+ break;
33
+ case "Base":
34
+ domain = "basescan.org";
35
+ break;
36
+ case "Sonic":
37
+ domain = "sonicscan.org";
38
+ break;
39
+ }
40
+ const [key, value] = Object.entries(param)[0];
41
+ return `https://${prefix}${domain}/${key}/${value}`;
42
+ }
@@ -0,0 +1,20 @@
1
+ import type { Address } from "viem";
2
+
3
+ import type { CreditAccountData } from "../base";
4
+
5
+ /**
6
+ * Helper function to filter out low-balance assets
7
+ * @param account
8
+ * @returns
9
+ */
10
+ export function filterDust(
11
+ account: CreditAccountData,
12
+ ): Record<Address, bigint> {
13
+ const result: Record<Address, bigint> = {};
14
+ for (const { token, balance } of account.tokens) {
15
+ if (balance > 10n) {
16
+ result[token] = balance;
17
+ }
18
+ }
19
+ return result;
20
+ }
@@ -0,0 +1,124 @@
1
+ import { formatDuration as fmtDuration, intervalToDuration } from "date-fns";
2
+
3
+ export const toBigInt = (
4
+ v: string | number | bigint | { type: "BigNumber"; hex: string },
5
+ ): bigint => {
6
+ const value =
7
+ typeof v === "object" && v.type === "BigNumber" ? v.hex : v.toString();
8
+ return BigInt(value);
9
+ };
10
+
11
+ export const percentFmt = (v: number | bigint | string, raw = true): string =>
12
+ `${(Number(v) / 100).toFixed(2)}%` + (raw ? ` [${v}]` : "");
13
+
14
+ export function formatBNvalue(
15
+ num: number | bigint | string | undefined,
16
+ decimals: number,
17
+ precision?: number,
18
+ raw = true,
19
+ ): string {
20
+ return `${formatBN(num, decimals, precision)}` + (raw ? ` [ ${num} ]` : "");
21
+ }
22
+
23
+ export function formatBN(
24
+ num: number | bigint | string | undefined,
25
+ decimals: number,
26
+ precision?: number,
27
+ ): string {
28
+ if (num === undefined) {
29
+ return "-";
30
+ }
31
+ const numBInt = BigInt(num);
32
+ // GUSD: 2 decimals
33
+ const limitedNum = limitNum(numBInt, decimals);
34
+ const limitedPrecision = limitPrecision(limitedNum, precision);
35
+ return toHumanFormat(limitedNum, limitedPrecision);
36
+ }
37
+
38
+ const limitPrecision = (n: bigint, p?: number) => {
39
+ const notZero = n !== 0n;
40
+ if (n <= 10n && notZero) {
41
+ return 6;
42
+ }
43
+ if (n <= 100n && notZero) {
44
+ return 5;
45
+ }
46
+ if (n <= 1000n && notZero) {
47
+ return 4;
48
+ }
49
+ if (n <= 10000n && notZero) {
50
+ return 3;
51
+ }
52
+ if (p === undefined && n > 10n ** 21n) {
53
+ return 2;
54
+ }
55
+ if (p === undefined && n > 10n ** 24n) {
56
+ return 0;
57
+ }
58
+
59
+ return p;
60
+ };
61
+
62
+ const limitNum = (n: bigint, d = 18): bigint => {
63
+ let limited = n <= 2n ? 0n : n;
64
+ if (d <= 6) {
65
+ return limited * 10n ** BigInt(6 - d);
66
+ } else {
67
+ return limited / 10n ** BigInt(d - 6);
68
+ }
69
+ };
70
+
71
+ export function toHumanFormat(num: bigint, precision = 2): string {
72
+ if (num >= BigInt(1e15)) {
73
+ return `${formatBn4dig(num / BigInt(1e9), precision)}Bn`;
74
+ }
75
+
76
+ if (num >= BigInt(1e12)) {
77
+ return `${formatBn4dig(num / BigInt(1e6), precision)}M`;
78
+ }
79
+
80
+ if (num >= BigInt(1e9)) {
81
+ return `${formatBn4dig(num / BigInt(1e3), precision)}K`;
82
+ }
83
+
84
+ return formatBn4dig(num, precision);
85
+ }
86
+
87
+ export function formatBn4dig(num: bigint, precision = 2): string {
88
+ if (precision > 6) {
89
+ throw new Error("Precision is too high, try <= 6");
90
+ }
91
+
92
+ const numStr = num.toString();
93
+ if (numStr.length <= 6) {
94
+ const completed = "0".repeat(6 - numStr.length) + numStr;
95
+ return `0.${completed.slice(0, precision)}`;
96
+ }
97
+ return `${numStr.slice(0, numStr.length - 6)}.${numStr.slice(
98
+ numStr.length - 6,
99
+ numStr.length - 6 + precision,
100
+ )}`;
101
+ }
102
+
103
+ export function fmtBinaryMask(mask: bigint): string {
104
+ return mask.toString(2).padStart(64, "0");
105
+ }
106
+
107
+ export function numberWithCommas(x: number | bigint): string {
108
+ return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
109
+ }
110
+
111
+ export function formatDuration(seconds: number, raw = true): string {
112
+ const now = Math.floor(Date.now() / 1_000) * 1_000;
113
+ const start = new Date(now);
114
+ const end = new Date(now + seconds * 1_000);
115
+ const duration = intervalToDuration({ start, end });
116
+
117
+ return `${fmtDuration(duration)}` + (raw ? `[${seconds.toString()}]` : "");
118
+ }
119
+
120
+ export function formatNumberToString_(value: bigint | number): string {
121
+ return value
122
+ .toLocaleString("en-US", { minimumIntegerDigits: 1, useGrouping: true })
123
+ .replaceAll(",", "_");
124
+ }
@@ -0,0 +1,10 @@
1
+ export * from "./AddressMap";
2
+ export * from "./bytes32ToString";
3
+ export * from "./childLogger";
4
+ export * from "./createRawTx";
5
+ export * from "./etherscan";
6
+ export * from "./filterDust";
7
+ export * from "./formatter";
8
+ export * from "./json";
9
+ export * from "./mappers";
10
+ export * from "./retry";
@@ -0,0 +1,51 @@
1
+ export interface IHooks<HookMap extends Record<string, any[]>> {
2
+ addHook: <K extends keyof HookMap>(
3
+ hookName: K,
4
+ fn: (...args: HookMap[K]) => void | Promise<void>,
5
+ ) => void;
6
+ removeHook: <K extends keyof HookMap>(
7
+ hookName: K,
8
+ fn: (...args: HookMap[K]) => void | Promise<void>,
9
+ ) => void;
10
+ }
11
+
12
+ export class Hooks<HookMap extends Record<string, any[]>>
13
+ implements IHooks<HookMap>
14
+ {
15
+ #reg: {
16
+ [K in keyof HookMap]: Array<(...args: HookMap[K]) => void | Promise<void>>;
17
+ } = {} as any;
18
+
19
+ public addHook<K extends keyof HookMap>(
20
+ hookName: K,
21
+ fn: (...args: HookMap[K]) => void | Promise<void>,
22
+ ): void {
23
+ if (!this.#reg[hookName]) {
24
+ this.#reg[hookName] = [];
25
+ }
26
+ this.#reg[hookName].push(fn);
27
+ }
28
+
29
+ public removeHook<K extends keyof HookMap>(
30
+ hookName: K,
31
+ fn: (...args: HookMap[K]) => void | Promise<void>,
32
+ ): void {
33
+ if (!this.#reg[hookName]) {
34
+ return;
35
+ }
36
+ this.#reg[hookName] =
37
+ this.#reg[hookName]?.filter(hookFn => hookFn !== fn) ?? [];
38
+ }
39
+
40
+ public async triggerHooks<K extends keyof HookMap>(
41
+ hookName: K,
42
+ ...args: HookMap[K]
43
+ ): Promise<void> {
44
+ if (!this.#reg[hookName]) {
45
+ return;
46
+ }
47
+ for (const fn of this.#reg[hookName]) {
48
+ await fn(...args);
49
+ }
50
+ }
51
+ }
@@ -0,0 +1 @@
1
+ export * from "./Hooks";
@@ -0,0 +1,27 @@
1
+ // Wrapper around JSON stringify/parse methods to support bigint serialization
2
+
3
+ function replacer(_key: string, value: any) {
4
+ if (typeof value === "bigint") {
5
+ return {
6
+ __type: "bigint",
7
+ __value: value.toString(),
8
+ };
9
+ } else {
10
+ return value;
11
+ }
12
+ }
13
+
14
+ function reviver(_key: string, value: any) {
15
+ if (value && value.__type === "bigint") {
16
+ return BigInt(value.__value);
17
+ }
18
+ return value;
19
+ }
20
+
21
+ export const json_stringify = (obj: any, space = 2) => {
22
+ return JSON.stringify(obj, replacer, space);
23
+ };
24
+
25
+ export const json_parse = (s: string) => {
26
+ return JSON.parse(s, reviver);
27
+ };
@@ -0,0 +1,38 @@
1
+ export type PartialRecord<K extends keyof any, T> = {
2
+ [P in K]?: T;
3
+ };
4
+
5
+ export type SupportedValue = string | number;
6
+
7
+ export class TypedObjectUtils {
8
+ static keys = <K extends SupportedValue, T>(o: Record<K, T>): Array<K> =>
9
+ Object.keys(o) as Array<K>;
10
+
11
+ static entries = <K extends SupportedValue, T>(
12
+ o: Record<K, T>,
13
+ ): Array<[K, T]> => Object.entries(o) as Array<[K, T]>;
14
+
15
+ static fromEntries = <K extends SupportedValue, T>(
16
+ o: Array<[K, T]>,
17
+ ): Record<K, T> => Object.fromEntries(o) as Record<K, T>;
18
+
19
+ static swapKeyValue = <K extends SupportedValue, T extends SupportedValue>(
20
+ o: Record<K, T>,
21
+ ): Record<T, K> =>
22
+ TypedObjectUtils.entries(o).reduce(
23
+ (acc, [key, value]) => ({ ...acc, [value]: key }),
24
+ {} as Record<T, K>,
25
+ );
26
+
27
+ static keyToLowercase = <K extends SupportedValue, T>(
28
+ o: Record<K, T>,
29
+ ): Record<K, T> =>
30
+ TypedObjectUtils.entries(o).reduce(
31
+ (acc, [key, value]) => {
32
+ const keyTransformed =
33
+ typeof key === "string" ? key.toLowerCase() : key;
34
+ return { ...acc, [keyTransformed]: value };
35
+ },
36
+ {} as Record<K, T>,
37
+ );
38
+ }
@@ -0,0 +1,24 @@
1
+ export interface RetryOptions {
2
+ attempts?: number;
3
+ interval?: number;
4
+ }
5
+
6
+ export async function retry<T>(
7
+ fn: () => Promise<T>,
8
+ options: RetryOptions = {},
9
+ ): Promise<T> {
10
+ const { attempts = 3, interval = 200 } = options;
11
+ let cause: any;
12
+ for (let i = 0; i < attempts; i++) {
13
+ try {
14
+ const result = await fn();
15
+ return result;
16
+ } catch (e) {
17
+ cause = e;
18
+ await new Promise(resolve => {
19
+ setTimeout(resolve, interval);
20
+ });
21
+ }
22
+ }
23
+ throw new Error(`all attempts failed: ${cause}`);
24
+ }
@@ -0,0 +1,27 @@
1
+ import type { Address, PublicClient } from "viem";
2
+
3
+ import { ierc20Abi } from "../../../abi/iERC20";
4
+ import { type NetworkType, SUPPORTED_CHAINS } from "../../chain";
5
+ import { USDC } from "../../constants";
6
+
7
+ const WELL_KNOWN_TOKENS: Record<NetworkType, Address> = {
8
+ ...USDC,
9
+ Sonic: "0x29219dd400f2Bf60E5a23d13Be72B486D4038894", // USDC_e
10
+ };
11
+
12
+ export async function detectNetwork(
13
+ client: PublicClient,
14
+ ): Promise<NetworkType> {
15
+ for (const chain of SUPPORTED_CHAINS) {
16
+ try {
17
+ await client.readContract({
18
+ abi: ierc20Abi,
19
+ address: WELL_KNOWN_TOKENS[chain],
20
+ functionName: "symbol",
21
+ });
22
+ return chain;
23
+ } catch {}
24
+ }
25
+
26
+ throw new Error("Unsupported network");
27
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./detectNetwork";
2
+ export * from "./sendRawTx";
3
+ export * from "./simulateMulticall";
@@ -0,0 +1,36 @@
1
+ import type {
2
+ Account,
3
+ Chain,
4
+ Client,
5
+ SendTransactionReturnType,
6
+ Transport,
7
+ } from "viem";
8
+ import { sendTransaction } from "viem/actions";
9
+ import { getAction } from "viem/utils";
10
+
11
+ import type { RawTx } from "../../types";
12
+
13
+ export interface SendRawTxParameters {
14
+ account?: Account;
15
+ tx: RawTx;
16
+ }
17
+
18
+ export async function sendRawTx<
19
+ chain extends Chain | undefined = Chain | undefined,
20
+ >(
21
+ client: Client<Transport, chain, Account | undefined>,
22
+ params: SendRawTxParameters,
23
+ ): Promise<SendTransactionReturnType> {
24
+ const { account, tx } = params;
25
+ return getAction(
26
+ client,
27
+ sendTransaction,
28
+ "sendTransaction",
29
+ )({
30
+ // @ts-expect-error
31
+ account,
32
+ data: tx.callData,
33
+ to: tx.to,
34
+ value: BigInt(tx.value),
35
+ }) as Promise<SendTransactionReturnType>;
36
+ }