viem 0.0.1-sushi.27 → 0.1.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 (523) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +132 -2
  3. package/abi/package.json +4 -0
  4. package/dist/abi.d.ts +5 -0
  5. package/dist/abi.js +21 -0
  6. package/dist/abi.js.map +1 -0
  7. package/dist/abi.mjs +21 -0
  8. package/dist/abi.mjs.map +1 -0
  9. package/dist/{chain-83ece55b.d.ts → chain-688e1663.d.ts} +1 -1
  10. package/dist/chain-d64be356.d.ts +553 -0
  11. package/dist/chains.d.ts +6 -5
  12. package/dist/chains.js +46 -46
  13. package/dist/chains.mjs +1 -1
  14. package/dist/{chunk-RPR4ZSAP.mjs → chunk-HDZRBHNX.mjs} +2754 -456
  15. package/dist/chunk-HDZRBHNX.mjs.map +1 -0
  16. package/dist/chunk-N5WJ5FTW.mjs +208 -0
  17. package/dist/chunk-N5WJ5FTW.mjs.map +1 -0
  18. package/dist/chunk-NM6QXEYF.js +208 -0
  19. package/dist/chunk-NM6QXEYF.js.map +1 -0
  20. package/dist/chunk-PZIHILNK.js +5326 -0
  21. package/dist/chunk-PZIHILNK.js.map +1 -0
  22. package/dist/contract.d.ts +8 -122
  23. package/dist/contract.js +4 -4
  24. package/dist/contract.mjs +18 -18
  25. package/dist/{createClient-cc01b906.d.ts → createClient-8575dcd6.d.ts} +13 -13
  26. package/dist/createPublicClient-c13b17f9.d.ts +771 -0
  27. package/dist/{eip1193-bbebfb3d.d.ts → eip1193-029d52f0.d.ts} +14 -3
  28. package/dist/encodeFunctionResult-12963e93.d.ts +75 -0
  29. package/dist/encodePacked-98b20b4d.d.ts +12 -0
  30. package/dist/ens.d.ts +7 -69
  31. package/dist/ens.js +4 -199
  32. package/dist/ens.js.map +1 -1
  33. package/dist/ens.mjs +6 -201
  34. package/dist/ens.mjs.map +1 -1
  35. package/dist/formatAbiItem-8ee3a7fa.d.ts +14 -0
  36. package/dist/getAbiItem-de103f9b.d.ts +22 -0
  37. package/dist/index.d.ts +105 -55
  38. package/dist/index.js +451 -41
  39. package/dist/index.js.map +1 -1
  40. package/dist/index.mjs +445 -35
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/namehash-afff0feb.d.ts +25 -0
  43. package/dist/parseGwei-23d1c213.d.ts +497 -0
  44. package/dist/public.d.ts +10 -336
  45. package/dist/public.js +4 -3
  46. package/dist/public.mjs +3 -2
  47. package/dist/test-f964519b.d.ts +205 -0
  48. package/dist/test.d.ts +7 -149
  49. package/dist/test.js +19 -222
  50. package/dist/test.js.map +1 -1
  51. package/dist/test.mjs +29 -232
  52. package/dist/test.mjs.map +1 -1
  53. package/dist/utils/index.d.ts +43 -231
  54. package/dist/utils/index.js +30 -2
  55. package/dist/utils/index.mjs +61 -33
  56. package/dist/wallet.d.ts +5 -41
  57. package/dist/wallet.js +2 -3
  58. package/dist/wallet.mjs +5 -6
  59. package/dist/window.d.ts +3 -2
  60. package/package.json +9 -6
  61. package/dist/call-14050d5c.d.ts +0 -23
  62. package/dist/chain-9a8c6614.d.ts +0 -372
  63. package/dist/chunk-3MFDRMZW.js +0 -3028
  64. package/dist/chunk-3MFDRMZW.js.map +0 -1
  65. package/dist/chunk-4MP6LO5V.js +0 -192
  66. package/dist/chunk-4MP6LO5V.js.map +0 -1
  67. package/dist/chunk-MV7PYF3D.mjs +0 -192
  68. package/dist/chunk-MV7PYF3D.mjs.map +0 -1
  69. package/dist/chunk-PSLMBGQ4.mjs +0 -1091
  70. package/dist/chunk-PSLMBGQ4.mjs.map +0 -1
  71. package/dist/chunk-RPR4ZSAP.mjs.map +0 -1
  72. package/dist/chunk-XB55RCBE.js +0 -1091
  73. package/dist/chunk-XB55RCBE.js.map +0 -1
  74. package/dist/contract-3b4a1df6.d.ts +0 -166
  75. package/dist/createPublicClient-9823f081.d.ts +0 -19
  76. package/dist/createTestClient-63b16109.d.ts +0 -34
  77. package/dist/createWalletClient-6dbbe0ee.d.ts +0 -30
  78. package/dist/decodeErrorResult-b0d3ce71.d.ts +0 -16
  79. package/dist/getAbiItem-540089dd.d.ts +0 -97
  80. package/dist/readContract-5c96b3bc.d.ts +0 -10
  81. package/dist/rpc-c367eceb.d.ts +0 -121
  82. package/dist/sendTransaction-50d22f3e.d.ts +0 -12
  83. package/dist/transactionReceipt-504958d3.d.ts +0 -26
  84. package/dist/transactionRequest-37f60d32.d.ts +0 -15
  85. package/dist/watchEvent-ca77f9e9.d.ts +0 -41
  86. package/src/_test/abis.ts +0 -1420
  87. package/src/_test/bench.ts +0 -15
  88. package/src/_test/constants.ts +0 -63
  89. package/src/_test/generated.ts +0 -128
  90. package/src/_test/globalSetup.ts +0 -11
  91. package/src/_test/index.ts +0 -25
  92. package/src/_test/setup.ts +0 -8
  93. package/src/_test/utils.ts +0 -155
  94. package/src/actions/ens/getEnsAddress.bench.ts +0 -26
  95. package/src/actions/ens/getEnsAddress.test.ts +0 -97
  96. package/src/actions/ens/getEnsAddress.ts +0 -122
  97. package/src/actions/ens/getEnsName.bench.ts +0 -30
  98. package/src/actions/ens/getEnsName.test.ts +0 -101
  99. package/src/actions/ens/getEnsName.ts +0 -106
  100. package/src/actions/ens/index.test.ts +0 -12
  101. package/src/actions/ens/index.ts +0 -3
  102. package/src/actions/index.test.ts +0 -81
  103. package/src/actions/index.ts +0 -182
  104. package/src/actions/public/call.bench.ts +0 -48
  105. package/src/actions/public/call.test.ts +0 -99
  106. package/src/actions/public/call.ts +0 -97
  107. package/src/actions/public/createBlockFilter.bench.ts +0 -11
  108. package/src/actions/public/createBlockFilter.test.ts +0 -9
  109. package/src/actions/public/createBlockFilter.ts +0 -14
  110. package/src/actions/public/createContractEventFilter.test.ts +0 -119
  111. package/src/actions/public/createContractEventFilter.ts +0 -69
  112. package/src/actions/public/createEventFilter.test.ts +0 -277
  113. package/src/actions/public/createEventFilter.ts +0 -93
  114. package/src/actions/public/createPendingTransactionFilter.bench.ts +0 -11
  115. package/src/actions/public/createPendingTransactionFilter.test.ts +0 -9
  116. package/src/actions/public/createPendingTransactionFilter.ts +0 -14
  117. package/src/actions/public/estimateGas.bench.ts +0 -46
  118. package/src/actions/public/estimateGas.test.ts +0 -92
  119. package/src/actions/public/estimateGas.ts +0 -61
  120. package/src/actions/public/getBalance.test.ts +0 -83
  121. package/src/actions/public/getBalance.ts +0 -37
  122. package/src/actions/public/getBlock.bench.ts +0 -28
  123. package/src/actions/public/getBlock.test.ts +0 -575
  124. package/src/actions/public/getBlock.ts +0 -65
  125. package/src/actions/public/getBlockNumber.bench.ts +0 -28
  126. package/src/actions/public/getBlockNumber.test.ts +0 -27
  127. package/src/actions/public/getBlockNumber.ts +0 -32
  128. package/src/actions/public/getBlockTransactionCount.bench.ts +0 -15
  129. package/src/actions/public/getBlockTransactionCount.test.ts +0 -57
  130. package/src/actions/public/getBlockTransactionCount.ts +0 -52
  131. package/src/actions/public/getBytecode.test.ts +0 -27
  132. package/src/actions/public/getBytecode.ts +0 -32
  133. package/src/actions/public/getChainId.bench.ts +0 -15
  134. package/src/actions/public/getChainId.test.ts +0 -8
  135. package/src/actions/public/getChainId.ts +0 -7
  136. package/src/actions/public/getFeeHistory.bench.ts +0 -18
  137. package/src/actions/public/getFeeHistory.test.ts +0 -137
  138. package/src/actions/public/getFeeHistory.ts +0 -44
  139. package/src/actions/public/getFilterChanges.bench.ts +0 -13
  140. package/src/actions/public/getFilterChanges.test.ts +0 -383
  141. package/src/actions/public/getFilterChanges.ts +0 -23
  142. package/src/actions/public/getFilterLogs.test.ts +0 -297
  143. package/src/actions/public/getFilterLogs.ts +0 -20
  144. package/src/actions/public/getGasPrice.bench.ts +0 -19
  145. package/src/actions/public/getGasPrice.test.ts +0 -8
  146. package/src/actions/public/getGasPrice.ts +0 -15
  147. package/src/actions/public/getLogs.test.ts +0 -306
  148. package/src/actions/public/getLogs.ts +0 -84
  149. package/src/actions/public/getStorageAt.test.ts +0 -34
  150. package/src/actions/public/getStorageAt.ts +0 -32
  151. package/src/actions/public/getTransaction.bench.ts +0 -33
  152. package/src/actions/public/getTransaction.test.ts +0 -311
  153. package/src/actions/public/getTransaction.ts +0 -95
  154. package/src/actions/public/getTransactionConfirmations.test.ts +0 -69
  155. package/src/actions/public/getTransactionConfirmations.ts +0 -38
  156. package/src/actions/public/getTransactionCount.test.ts +0 -56
  157. package/src/actions/public/getTransactionCount.ts +0 -34
  158. package/src/actions/public/getTransactionReceipt.bench.ts +0 -33
  159. package/src/actions/public/getTransactionReceipt.test.ts +0 -179
  160. package/src/actions/public/getTransactionReceipt.ts +0 -34
  161. package/src/actions/public/index.test.ts +0 -43
  162. package/src/actions/public/index.ts +0 -146
  163. package/src/actions/public/multicall.test.ts +0 -452
  164. package/src/actions/public/multicall.ts +0 -108
  165. package/src/actions/public/readContract.test.ts +0 -328
  166. package/src/actions/public/readContract.ts +0 -73
  167. package/src/actions/public/simulateContract.bench.ts +0 -41
  168. package/src/actions/public/simulateContract.test.ts +0 -410
  169. package/src/actions/public/simulateContract.ts +0 -91
  170. package/src/actions/public/uninstallFilter.bench.ts +0 -13
  171. package/src/actions/public/uninstallFilter.test.ts +0 -65
  172. package/src/actions/public/uninstallFilter.ts +0 -17
  173. package/src/actions/public/waitForTransactionReceipt.test.ts +0 -322
  174. package/src/actions/public/waitForTransactionReceipt.ts +0 -170
  175. package/src/actions/public/watchBlockNumber.test.ts +0 -166
  176. package/src/actions/public/watchBlockNumber.ts +0 -79
  177. package/src/actions/public/watchBlocks.test.ts +0 -210
  178. package/src/actions/public/watchBlocks.ts +0 -114
  179. package/src/actions/public/watchContractEvent.test.ts +0 -305
  180. package/src/actions/public/watchContractEvent.ts +0 -108
  181. package/src/actions/public/watchEvent.test.ts +0 -195
  182. package/src/actions/public/watchEvent.ts +0 -95
  183. package/src/actions/public/watchPendingTransactions.test.ts +0 -116
  184. package/src/actions/public/watchPendingTransactions.ts +0 -74
  185. package/src/actions/test/dropTransaction.test.ts +0 -34
  186. package/src/actions/test/dropTransaction.ts +0 -17
  187. package/src/actions/test/getAutomine.test.ts +0 -14
  188. package/src/actions/test/getAutomine.ts +0 -11
  189. package/src/actions/test/getTxpoolContent.test.ts +0 -45
  190. package/src/actions/test/getTxpoolContent.ts +0 -7
  191. package/src/actions/test/getTxpoolStatus.test.ts +0 -41
  192. package/src/actions/test/getTxpoolStatus.ts +0 -12
  193. package/src/actions/test/impersonateAccount.test.ts +0 -26
  194. package/src/actions/test/impersonateAccount.ts +0 -17
  195. package/src/actions/test/increaseTime.test.ts +0 -18
  196. package/src/actions/test/increaseTime.ts +0 -17
  197. package/src/actions/test/index.test.ts +0 -38
  198. package/src/actions/test/index.ts +0 -77
  199. package/src/actions/test/inspectTxpool.test.ts +0 -50
  200. package/src/actions/test/inspectTxpool.ts +0 -7
  201. package/src/actions/test/mine.test.ts +0 -20
  202. package/src/actions/test/mine.ts +0 -16
  203. package/src/actions/test/removeBlockTimestampInterval.test.ts +0 -23
  204. package/src/actions/test/removeBlockTimestampInterval.ts +0 -7
  205. package/src/actions/test/reset.test.ts +0 -19
  206. package/src/actions/test/reset.ts +0 -18
  207. package/src/actions/test/revert.test.ts +0 -39
  208. package/src/actions/test/revert.ts +0 -14
  209. package/src/actions/test/sendUnsignedTransaction.test.ts +0 -52
  210. package/src/actions/test/sendUnsignedTransaction.ts +0 -19
  211. package/src/actions/test/setAutomine.test.ts +0 -14
  212. package/src/actions/test/setAutomine.ts +0 -8
  213. package/src/actions/test/setBalance.test.ts +0 -29
  214. package/src/actions/test/setBalance.ts +0 -20
  215. package/src/actions/test/setBlockGasLimit.test.ts +0 -21
  216. package/src/actions/test/setBlockGasLimit.ts +0 -17
  217. package/src/actions/test/setBlockTimestampInterval.test.ts +0 -23
  218. package/src/actions/test/setBlockTimestampInterval.ts +0 -16
  219. package/src/actions/test/setCode.test.ts +0 -26
  220. package/src/actions/test/setCode.ts +0 -19
  221. package/src/actions/test/setCoinbase.test.ts +0 -11
  222. package/src/actions/test/setCoinbase.ts +0 -17
  223. package/src/actions/test/setIntervalMining.test.ts +0 -30
  224. package/src/actions/test/setIntervalMining.ts +0 -16
  225. package/src/actions/test/setLoggingEnabled.test.ts +0 -10
  226. package/src/actions/test/setLoggingEnabled.ts +0 -8
  227. package/src/actions/test/setMinGasPrice.test.ts +0 -22
  228. package/src/actions/test/setMinGasPrice.ts +0 -17
  229. package/src/actions/test/setNextBlockBaseFeePerGas.test.ts +0 -23
  230. package/src/actions/test/setNextBlockBaseFeePerGas.ts +0 -17
  231. package/src/actions/test/setNextBlockTimestamp.test.ts +0 -19
  232. package/src/actions/test/setNextBlockTimestamp.ts +0 -17
  233. package/src/actions/test/setNonce.test.ts +0 -28
  234. package/src/actions/test/setNonce.ts +0 -20
  235. package/src/actions/test/setRpcUrl.test.ts +0 -9
  236. package/src/actions/test/setRpcUrl.ts +0 -8
  237. package/src/actions/test/setStorageAt.test.ts +0 -36
  238. package/src/actions/test/setStorageAt.ts +0 -26
  239. package/src/actions/test/snapshot.test.ts +0 -18
  240. package/src/actions/test/snapshot.ts +0 -7
  241. package/src/actions/test/stopImpersonatingAccount.test.ts +0 -29
  242. package/src/actions/test/stopImpersonatingAccount.ts +0 -17
  243. package/src/actions/wallet/addChain.test.ts +0 -14
  244. package/src/actions/wallet/addChain.ts +0 -21
  245. package/src/actions/wallet/deployContract.test.ts +0 -55
  246. package/src/actions/wallet/deployContract.ts +0 -38
  247. package/src/actions/wallet/getAccounts.test.ts +0 -22
  248. package/src/actions/wallet/getAccounts.ts +0 -7
  249. package/src/actions/wallet/getPermissions.test.ts +0 -24
  250. package/src/actions/wallet/getPermissions.ts +0 -9
  251. package/src/actions/wallet/index.test.ts +0 -21
  252. package/src/actions/wallet/index.ts +0 -36
  253. package/src/actions/wallet/requestAccounts.test.ts +0 -13
  254. package/src/actions/wallet/requestAccounts.ts +0 -7
  255. package/src/actions/wallet/requestPermissions.test.ts +0 -26
  256. package/src/actions/wallet/requestPermissions.ts +0 -19
  257. package/src/actions/wallet/sendTransaction.bench.ts +0 -57
  258. package/src/actions/wallet/sendTransaction.test.ts +0 -440
  259. package/src/actions/wallet/sendTransaction.ts +0 -77
  260. package/src/actions/wallet/signMessage.test.ts +0 -61
  261. package/src/actions/wallet/signMessage.ts +0 -35
  262. package/src/actions/wallet/switchChain.test.ts +0 -21
  263. package/src/actions/wallet/switchChain.ts +0 -19
  264. package/src/actions/wallet/watchAsset.test.ts +0 -40
  265. package/src/actions/wallet/watchAsset.ts +0 -16
  266. package/src/actions/wallet/writeContract.test.ts +0 -84
  267. package/src/actions/wallet/writeContract.ts +0 -47
  268. package/src/chains.test.ts +0 -439
  269. package/src/chains.ts +0 -99
  270. package/src/clients/createClient.test.ts +0 -295
  271. package/src/clients/createClient.ts +0 -81
  272. package/src/clients/createPublicClient.test.ts +0 -165
  273. package/src/clients/createPublicClient.ts +0 -49
  274. package/src/clients/createTestClient.test.ts +0 -145
  275. package/src/clients/createTestClient.ts +0 -72
  276. package/src/clients/createWalletClient.test.ts +0 -121
  277. package/src/clients/createWalletClient.ts +0 -54
  278. package/src/clients/index.test.ts +0 -19
  279. package/src/clients/index.ts +0 -31
  280. package/src/clients/transports/createTransport.test.ts +0 -58
  281. package/src/clients/transports/createTransport.ts +0 -48
  282. package/src/clients/transports/custom.test.ts +0 -98
  283. package/src/clients/transports/custom.ts +0 -34
  284. package/src/clients/transports/fallback.test.ts +0 -393
  285. package/src/clients/transports/fallback.ts +0 -58
  286. package/src/clients/transports/http.test.ts +0 -109
  287. package/src/clients/transports/http.ts +0 -51
  288. package/src/clients/transports/index.test.ts +0 -15
  289. package/src/clients/transports/index.ts +0 -17
  290. package/src/clients/transports/webSocket.test.ts +0 -164
  291. package/src/clients/transports/webSocket.ts +0 -118
  292. package/src/constants/abis.test.ts +0 -53
  293. package/src/constants/abis.ts +0 -44
  294. package/src/constants/index.test.ts +0 -14
  295. package/src/constants/index.ts +0 -3
  296. package/src/constants/solidity.test.ts +0 -41
  297. package/src/constants/solidity.ts +0 -35
  298. package/src/contract.test.ts +0 -32
  299. package/src/contract.ts +0 -68
  300. package/src/ens.test.ts +0 -15
  301. package/src/ens.ts +0 -8
  302. package/src/errors/abi.test.ts +0 -81
  303. package/src/errors/abi.ts +0 -254
  304. package/src/errors/address.test.ts +0 -14
  305. package/src/errors/address.ts +0 -9
  306. package/src/errors/base.test.ts +0 -114
  307. package/src/errors/base.ts +0 -57
  308. package/src/errors/block.test.ts +0 -24
  309. package/src/errors/block.ts +0 -18
  310. package/src/errors/chain.test.ts +0 -46
  311. package/src/errors/chain.ts +0 -33
  312. package/src/errors/contract.test.ts +0 -233
  313. package/src/errors/contract.ts +0 -178
  314. package/src/errors/data.ts +0 -20
  315. package/src/errors/encoding.ts +0 -60
  316. package/src/errors/index.ts +0 -82
  317. package/src/errors/log.ts +0 -8
  318. package/src/errors/request.test.ts +0 -330
  319. package/src/errors/request.ts +0 -163
  320. package/src/errors/rpc.test.ts +0 -87
  321. package/src/errors/rpc.ts +0 -113
  322. package/src/errors/transaction.test.ts +0 -83
  323. package/src/errors/transaction.ts +0 -54
  324. package/src/errors/transport.test.ts +0 -11
  325. package/src/errors/transport.ts +0 -12
  326. package/src/index.test.ts +0 -116
  327. package/src/index.ts +0 -132
  328. package/src/public.test.ts +0 -36
  329. package/src/public.ts +0 -76
  330. package/src/test.test.ts +0 -38
  331. package/src/test.ts +0 -52
  332. package/src/types/block.ts +0 -71
  333. package/src/types/chain.ts +0 -6
  334. package/src/types/contract.ts +0 -497
  335. package/src/types/eip1193.ts +0 -1041
  336. package/src/types/fee.ts +0 -47
  337. package/src/types/filter.ts +0 -8
  338. package/src/types/formatter.ts +0 -23
  339. package/src/types/index.ts +0 -84
  340. package/src/types/log.ts +0 -22
  341. package/src/types/misc.ts +0 -5
  342. package/src/types/multicall.ts +0 -82
  343. package/src/types/rpc.ts +0 -35
  344. package/src/types/transaction.ts +0 -145
  345. package/src/types/utils.ts +0 -88
  346. package/src/types/window.ts +0 -9
  347. package/src/utils/abi/decodeAbi.bench.ts +0 -135
  348. package/src/utils/abi/decodeAbi.test.ts +0 -1614
  349. package/src/utils/abi/decodeAbi.ts +0 -300
  350. package/src/utils/abi/decodeDeployData.test.ts +0 -151
  351. package/src/utils/abi/decodeDeployData.ts +0 -44
  352. package/src/utils/abi/decodeErrorResult.test.ts +0 -230
  353. package/src/utils/abi/decodeErrorResult.ts +0 -45
  354. package/src/utils/abi/decodeEventLog.test.ts +0 -542
  355. package/src/utils/abi/decodeEventLog.ts +0 -107
  356. package/src/utils/abi/decodeFunctionData.test.ts +0 -138
  357. package/src/utils/abi/decodeFunctionData.ts +0 -32
  358. package/src/utils/abi/decodeFunctionResult.test.ts +0 -333
  359. package/src/utils/abi/decodeFunctionResult.ts +0 -57
  360. package/src/utils/abi/encodeAbi.bench.ts +0 -163
  361. package/src/utils/abi/encodeAbi.test.ts +0 -1447
  362. package/src/utils/abi/encodeAbi.ts +0 -273
  363. package/src/utils/abi/encodeDeployData.test.ts +0 -124
  364. package/src/utils/abi/encodeDeployData.ts +0 -40
  365. package/src/utils/abi/encodeErrorResult.test.ts +0 -192
  366. package/src/utils/abi/encodeErrorResult.ts +0 -47
  367. package/src/utils/abi/encodeEventTopics.test.ts +0 -345
  368. package/src/utils/abi/encodeEventTopics.ts +0 -75
  369. package/src/utils/abi/encodeFunctionData.test.ts +0 -138
  370. package/src/utils/abi/encodeFunctionData.ts +0 -42
  371. package/src/utils/abi/encodeFunctionResult.test.ts +0 -279
  372. package/src/utils/abi/encodeFunctionResult.ts +0 -41
  373. package/src/utils/abi/formatAbiItem.test.ts +0 -335
  374. package/src/utils/abi/formatAbiItem.ts +0 -41
  375. package/src/utils/abi/formatAbiItemWithArgs.test.ts +0 -291
  376. package/src/utils/abi/formatAbiItemWithArgs.ts +0 -27
  377. package/src/utils/abi/getAbiItem.test.ts +0 -547
  378. package/src/utils/abi/getAbiItem.ts +0 -95
  379. package/src/utils/abi/index.test.ts +0 -24
  380. package/src/utils/abi/index.ts +0 -48
  381. package/src/utils/address/getAddress.bench.ts +0 -22
  382. package/src/utils/address/getAddress.test.ts +0 -46
  383. package/src/utils/address/getAddress.ts +0 -28
  384. package/src/utils/address/getContractAddress.bench.ts +0 -20
  385. package/src/utils/address/getContractAddress.test.ts +0 -78
  386. package/src/utils/address/getContractAddress.ts +0 -59
  387. package/src/utils/address/index.test.ts +0 -17
  388. package/src/utils/address/index.ts +0 -16
  389. package/src/utils/address/isAddress.test.ts +0 -10
  390. package/src/utils/address/isAddress.ts +0 -10
  391. package/src/utils/address/isAddressEqual.test.ts +0 -55
  392. package/src/utils/address/isAddressEqual.ts +0 -6
  393. package/src/utils/buildRequest.test.ts +0 -428
  394. package/src/utils/buildRequest.ts +0 -72
  395. package/src/utils/chain.test.ts +0 -43
  396. package/src/utils/chain.ts +0 -8
  397. package/src/utils/contract/extractFunctionParts.test.ts +0 -109
  398. package/src/utils/contract/extractFunctionParts.ts +0 -27
  399. package/src/utils/contract/getContractError.test.ts +0 -282
  400. package/src/utils/contract/getContractError.ts +0 -58
  401. package/src/utils/contract/index.test.ts +0 -15
  402. package/src/utils/contract/index.ts +0 -8
  403. package/src/utils/data/concat.test.ts +0 -35
  404. package/src/utils/data/concat.ts +0 -34
  405. package/src/utils/data/index.test.ts +0 -23
  406. package/src/utils/data/index.ts +0 -13
  407. package/src/utils/data/isBytes.test.ts +0 -9
  408. package/src/utils/data/isBytes.ts +0 -7
  409. package/src/utils/data/isHex.test.ts +0 -13
  410. package/src/utils/data/isHex.ts +0 -5
  411. package/src/utils/data/pad.bench.ts +0 -30
  412. package/src/utils/data/pad.test.ts +0 -367
  413. package/src/utils/data/pad.ts +0 -53
  414. package/src/utils/data/size.test.ts +0 -18
  415. package/src/utils/data/size.ts +0 -13
  416. package/src/utils/data/slice.test.ts +0 -203
  417. package/src/utils/data/slice.ts +0 -60
  418. package/src/utils/data/trim.bench.ts +0 -34
  419. package/src/utils/data/trim.test.ts +0 -175
  420. package/src/utils/data/trim.ts +0 -33
  421. package/src/utils/encoding/decodeBytes.bench.ts +0 -40
  422. package/src/utils/encoding/decodeBytes.test.ts +0 -144
  423. package/src/utils/encoding/decodeBytes.ts +0 -63
  424. package/src/utils/encoding/decodeHex.bench.ts +0 -24
  425. package/src/utils/encoding/decodeHex.test.ts +0 -167
  426. package/src/utils/encoding/decodeHex.ts +0 -76
  427. package/src/utils/encoding/decodeRlp.bench.ts +0 -34
  428. package/src/utils/encoding/decodeRlp.test.ts +0 -350
  429. package/src/utils/encoding/decodeRlp.ts +0 -121
  430. package/src/utils/encoding/encodeBytes.bench.ts +0 -29
  431. package/src/utils/encoding/encodeBytes.test.ts +0 -676
  432. package/src/utils/encoding/encodeBytes.ts +0 -59
  433. package/src/utils/encoding/encodeHex.bench.ts +0 -49
  434. package/src/utils/encoding/encodeHex.test.ts +0 -232
  435. package/src/utils/encoding/encodeHex.ts +0 -104
  436. package/src/utils/encoding/encodeRlp.bench.ts +0 -54
  437. package/src/utils/encoding/encodeRlp.test.ts +0 -254
  438. package/src/utils/encoding/encodeRlp.ts +0 -48
  439. package/src/utils/encoding/index.test.ts +0 -32
  440. package/src/utils/encoding/index.ts +0 -36
  441. package/src/utils/ens/index.test.ts +0 -14
  442. package/src/utils/ens/index.ts +0 -7
  443. package/src/utils/ens/labelhash.test.ts +0 -55
  444. package/src/utils/ens/labelhash.ts +0 -16
  445. package/src/utils/ens/namehash.test.ts +0 -65
  446. package/src/utils/ens/namehash.ts +0 -28
  447. package/src/utils/ens/normalize.bench.ts +0 -14
  448. package/src/utils/ens/normalize.test.ts +0 -35
  449. package/src/utils/ens/normalize.ts +0 -14
  450. package/src/utils/ens/packetToBytes.test.ts +0 -11
  451. package/src/utils/ens/packetToBytes.ts +0 -29
  452. package/src/utils/formatters/block.bench.ts +0 -51
  453. package/src/utils/formatters/block.test.ts +0 -115
  454. package/src/utils/formatters/block.ts +0 -37
  455. package/src/utils/formatters/extract.test.ts +0 -14
  456. package/src/utils/formatters/extract.ts +0 -18
  457. package/src/utils/formatters/feeHistory.test.ts +0 -66
  458. package/src/utils/formatters/feeHistory.ts +0 -12
  459. package/src/utils/formatters/format.test.ts +0 -93
  460. package/src/utils/formatters/format.ts +0 -90
  461. package/src/utils/formatters/index.test.ts +0 -27
  462. package/src/utils/formatters/index.ts +0 -34
  463. package/src/utils/formatters/log.test.ts +0 -79
  464. package/src/utils/formatters/log.ts +0 -12
  465. package/src/utils/formatters/transaction.test.ts +0 -271
  466. package/src/utils/formatters/transaction.ts +0 -63
  467. package/src/utils/formatters/transactionReceipt.bench.ts +0 -73
  468. package/src/utils/formatters/transactionReceipt.test.ts +0 -151
  469. package/src/utils/formatters/transactionReceipt.ts +0 -63
  470. package/src/utils/formatters/transactionRequest.bench.ts +0 -29
  471. package/src/utils/formatters/transactionRequest.test.ts +0 -237
  472. package/src/utils/formatters/transactionRequest.ts +0 -56
  473. package/src/utils/hash/getEventSignature.test.ts +0 -61
  474. package/src/utils/hash/getEventSignature.ts +0 -4
  475. package/src/utils/hash/getFunctionSignature.test.ts +0 -22
  476. package/src/utils/hash/getFunctionSignature.ts +0 -5
  477. package/src/utils/hash/hashFunction.test.ts +0 -65
  478. package/src/utils/hash/hashFunction.ts +0 -12
  479. package/src/utils/hash/index.test.ts +0 -13
  480. package/src/utils/hash/index.ts +0 -5
  481. package/src/utils/hash/keccak256.test.ts +0 -59
  482. package/src/utils/hash/keccak256.ts +0 -21
  483. package/src/utils/index.test.ts +0 -111
  484. package/src/utils/index.ts +0 -142
  485. package/src/utils/observe.test.ts +0 -176
  486. package/src/utils/observe.ts +0 -66
  487. package/src/utils/poll.test.ts +0 -127
  488. package/src/utils/poll.ts +0 -42
  489. package/src/utils/promise/index.test.ts +0 -14
  490. package/src/utils/promise/index.ts +0 -3
  491. package/src/utils/promise/withCache.test.ts +0 -97
  492. package/src/utils/promise/withCache.ts +0 -73
  493. package/src/utils/promise/withRetry.test.ts +0 -231
  494. package/src/utils/promise/withRetry.ts +0 -61
  495. package/src/utils/promise/withTimeout.test.ts +0 -37
  496. package/src/utils/promise/withTimeout.ts +0 -39
  497. package/src/utils/rpc.test.ts +0 -990
  498. package/src/utils/rpc.ts +0 -294
  499. package/src/utils/stringify.test.ts +0 -13
  500. package/src/utils/stringify.ts +0 -5
  501. package/src/utils/uid.ts +0 -14
  502. package/src/utils/unit/constants.test.ts +0 -22
  503. package/src/utils/unit/constants.ts +0 -12
  504. package/src/utils/unit/formatEther.test.ts +0 -75
  505. package/src/utils/unit/formatEther.ts +0 -6
  506. package/src/utils/unit/formatGwei.test.ts +0 -32
  507. package/src/utils/unit/formatGwei.ts +0 -6
  508. package/src/utils/unit/formatUnit.bench.ts +0 -21
  509. package/src/utils/unit/formatUnit.test.ts +0 -40
  510. package/src/utils/unit/formatUnit.ts +0 -16
  511. package/src/utils/unit/index.test.ts +0 -28
  512. package/src/utils/unit/index.ts +0 -7
  513. package/src/utils/unit/parseEther.test.ts +0 -126
  514. package/src/utils/unit/parseEther.ts +0 -6
  515. package/src/utils/unit/parseGwei.test.ts +0 -50
  516. package/src/utils/unit/parseGwei.ts +0 -6
  517. package/src/utils/unit/parseUnit.bench.ts +0 -21
  518. package/src/utils/unit/parseUnit.test.ts +0 -54
  519. package/src/utils/unit/parseUnit.ts +0 -27
  520. package/src/utils/wait.ts +0 -3
  521. package/src/wallet.test.ts +0 -19
  522. package/src/wallet.ts +0 -23
  523. package/src/window.ts +0 -1
@@ -5,11 +5,19 @@ var __publicField = (obj, key, value) => {
5
5
  return value;
6
6
  };
7
7
 
8
+ // src/utils/abi/index.ts
9
+ import {
10
+ parseAbi,
11
+ parseAbiItem,
12
+ parseAbiParameter,
13
+ parseAbiParameters
14
+ } from "abitype";
15
+
8
16
  // package.json
9
17
  var package_default = {
10
18
  name: "viem",
11
19
  description: "TypeScript Interface for Ethereum",
12
- version: "0.0.1-sushi.27",
20
+ version: "0.1.1",
13
21
  scripts: {
14
22
  anvil: "source .env && anvil --fork-url $VITE_ANVIL_FORK_URL --fork-block-number $VITE_ANVIL_BLOCK_NUMBER --block-time $VITE_ANVIL_BLOCK_TIME",
15
23
  bench: "vitest bench --no-threads",
@@ -18,32 +26,47 @@ var package_default = {
18
26
  changeset: "changeset",
19
27
  "changeset:release": "pnpm build && changeset publish",
20
28
  "changeset:version": "changeset version && pnpm install --lockfile-only",
29
+ clean: "rimraf dist abi chains contract ens public test utils wallet window",
21
30
  "contracts:build": "wagmi generate",
22
31
  dev: "DEV=true tsup",
23
32
  "dev:docs": "pnpm -r --filter site dev",
24
- format: "rome format src/ test/ --write",
33
+ format: "rome format src/ --write",
25
34
  lint: "rome check .",
26
35
  "lint:fix": "pnpm lint --apply-suggested",
27
- playground: "pnpm --filter playground-dev dev",
36
+ playground: "pnpm --filter playground-browser dev",
28
37
  postinstall: "pnpm dev && pnpm contracts:build",
29
38
  preinstall: "npx only-allow pnpm",
30
- prepublishOnly: "pnpm ts-node scripts/generate-package-json.ts",
39
+ prepublishOnly: "pnpm bun scripts/prepublishOnly.ts",
31
40
  prepare: "npx simple-git-hooks",
32
41
  test: "vitest dev --no-threads",
42
+ "test:cov": "vitest dev --coverage --no-threads",
33
43
  "test:ci": "CI=true vitest --coverage --no-threads",
34
44
  "test:ui": "vitest dev --ui --no-threads",
35
- "ts-node": "node --loader esbuild-register/loader -r esbuild-register",
45
+ "ts-node": "bun",
36
46
  typecheck: "tsc --noEmit"
37
47
  },
48
+ tsup: {
49
+ entry: [
50
+ "src/index.ts",
51
+ "src/abi.ts",
52
+ "src/chains.ts",
53
+ "src/contract.ts",
54
+ "src/ens.ts",
55
+ "src/public.ts",
56
+ "src/test.ts",
57
+ "src/utils/index.ts",
58
+ "src/wallet.ts",
59
+ "src/window.ts"
60
+ ]
61
+ },
38
62
  files: [
63
+ "/abi",
64
+ "/dist",
39
65
  "/chains",
40
66
  "/contract",
41
- "/dist",
42
67
  "/ens",
43
68
  "/public",
44
- "/src",
45
69
  "/test",
46
- "/types",
47
70
  "/utils",
48
71
  "/wallet",
49
72
  "/window"
@@ -51,47 +74,52 @@ var package_default = {
51
74
  exports: {
52
75
  ".": {
53
76
  types: "./dist/index.d.ts",
54
- module: "./dist/index.mjs",
77
+ module: "./dist/index.mts",
55
78
  default: "./dist/index.js"
56
79
  },
80
+ "./abi": {
81
+ types: "./dist/abi.d.ts",
82
+ module: "./dist/abi.mts",
83
+ default: "./dist/abi.js"
84
+ },
57
85
  "./chains": {
58
86
  types: "./dist/chains.d.ts",
59
- module: "./dist/chains.mjs",
87
+ module: "./dist/chains.mts",
60
88
  default: "./dist/chains.js"
61
89
  },
62
90
  "./contract": {
63
91
  types: "./dist/contract.d.ts",
64
- module: "./dist/contract.mjs",
92
+ module: "./dist/contract.mts",
65
93
  default: "./dist/contract.js"
66
94
  },
67
95
  "./ens": {
68
96
  types: "./dist/ens.d.ts",
69
- module: "./dist/ens.mjs",
97
+ module: "./dist/ens.mts",
70
98
  default: "./dist/ens.js"
71
99
  },
72
100
  "./public": {
73
101
  types: "./dist/public.d.ts",
74
- module: "./dist/public.mjs",
102
+ module: "./dist/public.mts",
75
103
  default: "./dist/public.js"
76
104
  },
77
105
  "./test": {
78
106
  types: "./dist/test.d.ts",
79
- module: "./dist/test.mjs",
107
+ module: "./dist/test.mts",
80
108
  default: "./dist/test.js"
81
109
  },
82
110
  "./utils": {
83
111
  types: "./dist/utils/index.d.ts",
84
- module: "./dist/utils/index.mjs",
112
+ module: "./dist/utils/index.mts",
85
113
  default: "./dist/utils/index.js"
86
114
  },
87
115
  "./wallet": {
88
116
  types: "./dist/wallet.d.ts",
89
- module: "./dist/wallet.mjs",
117
+ module: "./dist/wallet.mts",
90
118
  default: "./dist/wallet.js"
91
119
  },
92
120
  "./window": {
93
121
  types: "./dist/window.d.ts",
94
- module: "./dist/window.mjs",
122
+ module: "./dist/window.mts",
95
123
  default: "./dist/window.js"
96
124
  },
97
125
  "./package.json": "./package.json"
@@ -103,9 +131,8 @@ var package_default = {
103
131
  dependencies: {
104
132
  "@noble/hashes": "^1.1.2",
105
133
  "@wagmi/chains": "~0.2.8",
106
- abitype: "~0.3.0",
134
+ abitype: "~0.6.2",
107
135
  "idna-uts46-hx": "^4.1.2",
108
- "isomorphic-unfetch": "^4.0.2",
109
136
  "isomorphic-ws": "^5.0.0",
110
137
  ws: "^8.12.0"
111
138
  },
@@ -119,24 +146,23 @@ var package_default = {
119
146
  "@types/fs-extra": "^9.0.13",
120
147
  "@types/node": "^17.0.45",
121
148
  "@types/ws": "^8.5.4",
122
- "@vitest/coverage-c8": "^0.24.3",
123
- "@vitest/ui": "^0.19.1",
149
+ "@vitest/coverage-c8": "^0.29.2",
150
+ "@vitest/ui": "^0.29.2",
124
151
  "@wagmi/cli": "^0.1.6",
152
+ bun: "^0.5.5",
125
153
  bundlewatch: "^0.3.3",
126
154
  dedent: "^0.7.0",
127
- esbuild: "^0.16.17",
128
- "esbuild-register": "^3.4.2",
129
155
  ethers: "^5.7.2",
130
156
  "ethers@6": "npm:ethers@^6.0.2",
131
157
  execa: "^6.1.0",
132
158
  "fs-extra": "^10.1.0",
159
+ rimraf: "^4.1.2",
133
160
  rome: "^11.0.0",
134
161
  "simple-git-hooks": "^2.8.1",
135
162
  tsup: "^6.6.0",
136
163
  typescript: "^4.9.4",
137
- vite: "^3.2.5",
138
- vitest: "^0.25.8",
139
- web3: "^1.8.1"
164
+ vite: "^4.1.4",
165
+ vitest: "~0.29.2"
140
166
  },
141
167
  license: "MIT",
142
168
  repository: "wagmi-dev/viem",
@@ -152,17 +178,21 @@ var package_default = {
152
178
  "web3"
153
179
  ],
154
180
  "simple-git-hooks": {
155
- "pre-commit": "pnpm format & pnpm lint:fix"
181
+ "pre-commit": "pnpm format && pnpm lint:fix"
156
182
  },
157
183
  pnpm: {
158
184
  patchedDependencies: {
159
- "vitepress@1.0.0-alpha.34": "patches/vitepress@1.0.0-alpha.34.patch"
185
+ "vitepress@1.0.0-alpha.49": "patches/vitepress@1.0.0-alpha.49.patch"
160
186
  }
161
187
  }
162
188
  };
163
189
 
190
+ // src/errors/utils.ts
191
+ var getContractAddress = (address) => address;
192
+ var getUrl = (url) => url;
193
+ var getVersion = () => `${package_default.name}@${package_default.version}`;
194
+
164
195
  // src/errors/base.ts
165
- var version = process.env.TEST ? "1.0.2" : package_default.version;
166
196
  var BaseError = class extends Error {
167
197
  constructor(shortMessage, args = {}) {
168
198
  const details = args.cause instanceof BaseError ? args.cause.details : args.cause?.message ? args.cause.message : args.details;
@@ -173,7 +203,7 @@ var BaseError = class extends Error {
173
203
  ...args.metaMessages ? [...args.metaMessages, ""] : [],
174
204
  ...docsPath5 ? [`Docs: https://viem.sh${docsPath5}`] : [],
175
205
  ...details ? [`Details: ${details}`] : [],
176
- `Version: viem@${version}`
206
+ `Version: ${getVersion()}`
177
207
  ].join("\n");
178
208
  super(message);
179
209
  __publicField(this, "details");
@@ -252,6 +282,16 @@ var AbiEncodingArrayLengthMismatchError = class extends BaseError {
252
282
  __publicField(this, "name", "AbiEncodingArrayLengthMismatchError");
253
283
  }
254
284
  };
285
+ var AbiEncodingBytesSizeMismatchError = class extends BaseError {
286
+ constructor({ expectedSize, value }) {
287
+ super(
288
+ `Size of bytes "${value}" (bytes${size(
289
+ value
290
+ )}) does not match expected size (bytes${expectedSize}).`
291
+ );
292
+ __publicField(this, "name", "AbiEncodingBytesSizeMismatchError");
293
+ }
294
+ };
255
295
  var AbiEncodingLengthMismatchError = class extends BaseError {
256
296
  constructor({
257
297
  expectedLength,
@@ -384,6 +424,15 @@ var AbiFunctionSignatureNotFoundError = class extends BaseError {
384
424
  __publicField(this, "name", "AbiFunctionSignatureNotFoundError");
385
425
  }
386
426
  };
427
+ var BytesSizeMismatchError = class extends BaseError {
428
+ constructor({
429
+ expectedSize,
430
+ givenSize
431
+ }) {
432
+ super(`Expected bytes${expectedSize}, got bytes${givenSize}.`);
433
+ __publicField(this, "name", "BytesSizeMismatchError");
434
+ }
435
+ };
387
436
  var InvalidAbiEncodingTypeError = class extends BaseError {
388
437
  constructor(type, { docsPath: docsPath5 }) {
389
438
  super(
@@ -425,6 +474,12 @@ var InvalidDefinitionTypeError = class extends BaseError {
425
474
  __publicField(this, "name", "InvalidDefinitionTypeError");
426
475
  }
427
476
  };
477
+ var UnsupportedPackedAbiType = class extends BaseError {
478
+ constructor(type) {
479
+ super(`Type "${type}" is not supported for packed encoding.`);
480
+ __publicField(this, "name", "UnsupportedPackedAbiType");
481
+ }
482
+ };
428
483
 
429
484
  // src/errors/address.ts
430
485
  var InvalidAddressError = class extends BaseError {
@@ -473,6 +528,23 @@ var ChainDoesNotSupportContract = class extends BaseError {
473
528
  __publicField(this, "name", "ChainDoesNotSupportContract");
474
529
  }
475
530
  };
531
+ var ChainMismatchError = class extends BaseError {
532
+ constructor({
533
+ chain,
534
+ currentChainId
535
+ }) {
536
+ super(
537
+ `The current chain (id: ${currentChainId}) does not match the chain passed to the request (id: ${chain.id} \u2013 ${chain.name}).`,
538
+ {
539
+ metaMessages: [
540
+ `Current Chain ID: ${currentChainId}`,
541
+ `Expected Chain ID: ${chain.id} \u2013 ${chain.name}`
542
+ ]
543
+ }
544
+ );
545
+ __publicField(this, "name", "ChainMismatchError");
546
+ }
547
+ };
476
548
 
477
549
  // src/constants/abis.ts
478
550
  var multicall3Abi = [
@@ -552,7 +624,159 @@ var solidityPanic = {
552
624
  type: "error"
553
625
  };
554
626
 
627
+ // src/constants/unit.ts
628
+ var etherUnits = {
629
+ gwei: 9,
630
+ wei: 18
631
+ };
632
+ var gweiUnits = {
633
+ ether: -9,
634
+ wei: 9
635
+ };
636
+ var weiUnits = {
637
+ ether: -18,
638
+ gwei: -9
639
+ };
640
+
641
+ // src/errors/transaction.ts
642
+ function prettyPrint(args) {
643
+ const entries = Object.entries(args).map(([key, value]) => {
644
+ if (value === void 0 || value === false)
645
+ return null;
646
+ return [key, value];
647
+ }).filter(Boolean);
648
+ const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);
649
+ return entries.map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`).join("\n");
650
+ }
651
+ var FeeConflictError = class extends BaseError {
652
+ constructor() {
653
+ super(
654
+ [
655
+ "Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.",
656
+ "Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others."
657
+ ].join("\n")
658
+ );
659
+ __publicField(this, "name", "FeeConflictError");
660
+ }
661
+ };
662
+ var TransactionExecutionError = class extends BaseError {
663
+ constructor(cause, {
664
+ account,
665
+ docsPath: docsPath5,
666
+ chain,
667
+ data,
668
+ gas,
669
+ gasPrice,
670
+ maxFeePerGas,
671
+ maxPriorityFeePerGas,
672
+ nonce,
673
+ to,
674
+ value
675
+ }) {
676
+ const prettyArgs = prettyPrint({
677
+ chain: chain && `${chain?.name} (id: ${chain?.id})`,
678
+ from: account.address,
679
+ to,
680
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
681
+ data,
682
+ gas,
683
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
684
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
685
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
686
+ nonce
687
+ });
688
+ super(cause.shortMessage, {
689
+ cause,
690
+ docsPath: docsPath5,
691
+ metaMessages: [
692
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
693
+ "Request Arguments:",
694
+ prettyArgs
695
+ ].filter(Boolean)
696
+ });
697
+ __publicField(this, "cause");
698
+ __publicField(this, "name", "TransactionExecutionError");
699
+ this.cause = cause;
700
+ }
701
+ };
702
+ var TransactionNotFoundError = class extends BaseError {
703
+ constructor({
704
+ blockHash,
705
+ blockNumber,
706
+ blockTag,
707
+ hash: hash2,
708
+ index
709
+ }) {
710
+ let identifier = "Transaction";
711
+ if (blockTag && index !== void 0)
712
+ identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
713
+ if (blockHash && index !== void 0)
714
+ identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
715
+ if (blockNumber && index !== void 0)
716
+ identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
717
+ if (hash2)
718
+ identifier = `Transaction with hash "${hash2}"`;
719
+ super(`${identifier} could not be found.`);
720
+ __publicField(this, "name", "TransactionNotFoundError");
721
+ }
722
+ };
723
+ var TransactionReceiptNotFoundError = class extends BaseError {
724
+ constructor({ hash: hash2 }) {
725
+ super(
726
+ `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
727
+ );
728
+ __publicField(this, "name", "TransactionReceiptNotFoundError");
729
+ }
730
+ };
731
+ var WaitForTransactionReceiptTimeoutError = class extends BaseError {
732
+ constructor({ hash: hash2 }) {
733
+ super(
734
+ `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
735
+ );
736
+ __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
737
+ }
738
+ };
739
+
555
740
  // src/errors/contract.ts
741
+ var CallExecutionError = class extends BaseError {
742
+ constructor(cause, {
743
+ account,
744
+ docsPath: docsPath5,
745
+ chain,
746
+ data,
747
+ gas,
748
+ gasPrice,
749
+ maxFeePerGas,
750
+ maxPriorityFeePerGas,
751
+ nonce,
752
+ to,
753
+ value
754
+ }) {
755
+ const prettyArgs = prettyPrint({
756
+ from: account?.address,
757
+ to,
758
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
759
+ data,
760
+ gas,
761
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
762
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
763
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
764
+ nonce
765
+ });
766
+ super(cause.shortMessage, {
767
+ cause,
768
+ docsPath: docsPath5,
769
+ metaMessages: [
770
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
771
+ "Raw Call Arguments:",
772
+ prettyArgs
773
+ ].filter(Boolean)
774
+ });
775
+ __publicField(this, "cause");
776
+ __publicField(this, "name", "CallExecutionError");
777
+ this.cause = cause;
778
+ }
779
+ };
556
780
  var ContractFunctionExecutionError = class extends BaseError {
557
781
  constructor(cause, {
558
782
  abi,
@@ -570,6 +794,12 @@ var ContractFunctionExecutionError = class extends BaseError {
570
794
  includeName: false
571
795
  }) : void 0;
572
796
  const functionWithParams = abiItem ? formatAbiItem(abiItem, { includeName: true }) : void 0;
797
+ const prettyArgs = prettyPrint({
798
+ address: contractAddress && getContractAddress(contractAddress),
799
+ function: functionWithParams,
800
+ args: formattedArgs && formattedArgs !== "()" && `${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
801
+ sender
802
+ });
573
803
  super(
574
804
  cause.shortMessage || `An unknown error occurred while executing the contract function "${functionName}".`,
575
805
  {
@@ -577,11 +807,8 @@ var ContractFunctionExecutionError = class extends BaseError {
577
807
  docsPath: docsPath5,
578
808
  metaMessages: [
579
809
  ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
580
- contractAddress && `Contract: ${/* c8 ignore start */
581
- process.env.TEST ? "0x0000000000000000000000000000000000000000" : contractAddress}`,
582
- functionWithParams && `Function: ${functionWithParams}`,
583
- formattedArgs && formattedArgs !== "()" && `Arguments: ${[...Array(functionName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}`,
584
- sender && `Sender: ${sender}`
810
+ "Contract Call:",
811
+ prettyArgs
585
812
  ].filter(Boolean)
586
813
  }
587
814
  );
@@ -628,8 +855,8 @@ var ContractFunctionRevertedError = class extends BaseError {
628
855
  includeName: false
629
856
  }) : void 0;
630
857
  metaMessages = [
631
- errorWithParams ? `Error: ${errorWithParams}` : "",
632
- formattedArgs && formattedArgs !== "()" ? `Arguments: ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
858
+ errorWithParams ? `Error: ${errorWithParams}` : "",
859
+ formattedArgs && formattedArgs !== "()" ? ` ${[...Array(errorName?.length ?? 0).keys()].map(() => " ").join("")}${formattedArgs}` : ""
633
860
  ];
634
861
  }
635
862
  } else if (message)
@@ -655,9 +882,9 @@ var ContractFunctionZeroDataError = class extends BaseError {
655
882
  super(`The contract function "${functionName}" returned no data ("0x").`, {
656
883
  metaMessages: [
657
884
  "This could be due to any of the following:",
658
- `- The contract does not have the function "${functionName}",`,
659
- "- The parameters passed to the contract function may be invalid, or",
660
- "- The address is not a contract."
885
+ ` - The contract does not have the function "${functionName}",`,
886
+ " - The parameters passed to the contract function may be invalid, or",
887
+ " - The address is not a contract."
661
888
  ]
662
889
  });
663
890
  __publicField(this, "name", "ContractFunctionZeroDataError");
@@ -737,6 +964,47 @@ var OffsetOutOfBoundsError = class extends BaseError {
737
964
  }
738
965
  };
739
966
 
967
+ // src/errors/estimateGas.ts
968
+ var EstimateGasExecutionError = class extends BaseError {
969
+ constructor(cause, {
970
+ account,
971
+ docsPath: docsPath5,
972
+ chain,
973
+ data,
974
+ gas,
975
+ gasPrice,
976
+ maxFeePerGas,
977
+ maxPriorityFeePerGas,
978
+ nonce,
979
+ to,
980
+ value
981
+ }) {
982
+ const prettyArgs = prettyPrint({
983
+ from: account.address,
984
+ to,
985
+ value: typeof value !== "undefined" && `${formatEther(value)} ${chain?.nativeCurrency.symbol || "ETH"}`,
986
+ data,
987
+ gas,
988
+ gasPrice: typeof gasPrice !== "undefined" && `${formatGwei(gasPrice)} gwei`,
989
+ maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei(maxFeePerGas)} gwei`,
990
+ maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei(maxPriorityFeePerGas)} gwei`,
991
+ nonce
992
+ });
993
+ super(cause.shortMessage, {
994
+ cause,
995
+ docsPath: docsPath5,
996
+ metaMessages: [
997
+ ...cause.metaMessages ? [...cause.metaMessages, " "] : [],
998
+ "Estimate Gas Arguments:",
999
+ prettyArgs
1000
+ ].filter(Boolean)
1001
+ });
1002
+ __publicField(this, "cause");
1003
+ __publicField(this, "name", "EstimateGasExecutionError");
1004
+ this.cause = cause;
1005
+ }
1006
+ };
1007
+
740
1008
  // src/errors/log.ts
741
1009
  var FilterTypeNotSupportedError = class extends BaseError {
742
1010
  constructor(type) {
@@ -745,19 +1013,189 @@ var FilterTypeNotSupportedError = class extends BaseError {
745
1013
  }
746
1014
  };
747
1015
 
1016
+ // src/errors/node.ts
1017
+ var ExecutionRevertedError = class extends BaseError {
1018
+ constructor({
1019
+ cause,
1020
+ message
1021
+ } = {}) {
1022
+ const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", "");
1023
+ super(
1024
+ `Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`,
1025
+ {
1026
+ cause
1027
+ }
1028
+ );
1029
+ __publicField(this, "name", "ExecutionRevertedError");
1030
+ }
1031
+ };
1032
+ __publicField(ExecutionRevertedError, "code", 3);
1033
+ __publicField(ExecutionRevertedError, "nodeMessage", /execution reverted/);
1034
+ var FeeCapTooHighError = class extends BaseError {
1035
+ constructor({
1036
+ cause,
1037
+ maxFeePerGas
1038
+ } = {}) {
1039
+ super(
1040
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`,
1041
+ {
1042
+ cause
1043
+ }
1044
+ );
1045
+ __publicField(this, "name", "FeeCapTooHigh");
1046
+ }
1047
+ };
1048
+ __publicField(FeeCapTooHighError, "nodeMessage", /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/);
1049
+ var FeeCapTooLowError = class extends BaseError {
1050
+ constructor({
1051
+ cause,
1052
+ maxFeePerGas
1053
+ } = {}) {
1054
+ super(
1055
+ `The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`,
1056
+ {
1057
+ cause
1058
+ }
1059
+ );
1060
+ __publicField(this, "name", "FeeCapTooLow");
1061
+ }
1062
+ };
1063
+ __publicField(FeeCapTooLowError, "nodeMessage", /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/);
1064
+ var NonceTooHighError = class extends BaseError {
1065
+ constructor({ cause, nonce } = {}) {
1066
+ super(
1067
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`,
1068
+ { cause }
1069
+ );
1070
+ __publicField(this, "name", "NonceTooHighError");
1071
+ }
1072
+ };
1073
+ __publicField(NonceTooHighError, "nodeMessage", /nonce too high/);
1074
+ var NonceTooLowError = class extends BaseError {
1075
+ constructor({ cause, nonce } = {}) {
1076
+ super(
1077
+ [
1078
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`,
1079
+ "Try increasing the nonce or find the latest nonce with `getTransactionCount`."
1080
+ ].join("\n"),
1081
+ { cause }
1082
+ );
1083
+ __publicField(this, "name", "NonceTooLowError");
1084
+ }
1085
+ };
1086
+ __publicField(NonceTooLowError, "nodeMessage", /nonce too low|transaction already imported/);
1087
+ var NonceMaxValueError = class extends BaseError {
1088
+ constructor({ cause, nonce } = {}) {
1089
+ super(
1090
+ `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`,
1091
+ { cause }
1092
+ );
1093
+ __publicField(this, "name", "NonceMaxValueError");
1094
+ }
1095
+ };
1096
+ __publicField(NonceMaxValueError, "nodeMessage", /nonce has max value/);
1097
+ var InsufficientFundsError = class extends BaseError {
1098
+ constructor({ cause } = {}) {
1099
+ super(
1100
+ [
1101
+ "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account."
1102
+ ].join("\n"),
1103
+ {
1104
+ cause,
1105
+ metaMessages: [
1106
+ "This error could arise when the account does not have enough funds to:",
1107
+ " - pay for the total gas fee,",
1108
+ " - pay for the value to send.",
1109
+ " ",
1110
+ "The cost of the transaction is calculated as `gas * gas fee + value`, where:",
1111
+ " - `gas` is the amount of gas needed for transaction to execute,",
1112
+ " - `gas fee` is the gas fee,",
1113
+ " - `value` is the amount of ether to send to the recipient."
1114
+ ]
1115
+ }
1116
+ );
1117
+ __publicField(this, "name", "InsufficientFundsError");
1118
+ }
1119
+ };
1120
+ __publicField(InsufficientFundsError, "nodeMessage", /insufficient funds/);
1121
+ var IntrinsicGasTooHighError = class extends BaseError {
1122
+ constructor({ cause, gas } = {}) {
1123
+ super(
1124
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`,
1125
+ {
1126
+ cause
1127
+ }
1128
+ );
1129
+ __publicField(this, "name", "IntrinsicGasTooHighError");
1130
+ }
1131
+ };
1132
+ __publicField(IntrinsicGasTooHighError, "nodeMessage", /intrinsic gas too high|gas limit reached/);
1133
+ var IntrinsicGasTooLowError = class extends BaseError {
1134
+ constructor({ cause, gas } = {}) {
1135
+ super(
1136
+ `The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`,
1137
+ {
1138
+ cause
1139
+ }
1140
+ );
1141
+ __publicField(this, "name", "IntrinsicGasTooLowError");
1142
+ }
1143
+ };
1144
+ __publicField(IntrinsicGasTooLowError, "nodeMessage", /intrinsic gas too low/);
1145
+ var TransactionTypeNotSupportedError = class extends BaseError {
1146
+ constructor({ cause }) {
1147
+ super("The transaction type is not supported for this chain.", {
1148
+ cause
1149
+ });
1150
+ __publicField(this, "name", "TransactionTypeNotSupportedError");
1151
+ }
1152
+ };
1153
+ __publicField(TransactionTypeNotSupportedError, "nodeMessage", /transaction type not valid/);
1154
+ var TipAboveFeeCapError = class extends BaseError {
1155
+ constructor({
1156
+ cause,
1157
+ maxPriorityFeePerGas,
1158
+ maxFeePerGas
1159
+ } = {}) {
1160
+ super(
1161
+ [
1162
+ `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ""}).`
1163
+ ].join("\n"),
1164
+ {
1165
+ cause
1166
+ }
1167
+ );
1168
+ __publicField(this, "name", "TipAboveFeeCapError");
1169
+ }
1170
+ };
1171
+ __publicField(TipAboveFeeCapError, "nodeMessage", /max priority fee per gas higher than max fee per gas|tip higher than fee cap/);
1172
+ var UnknownNodeError = class extends BaseError {
1173
+ constructor({ cause }) {
1174
+ super(`An error occurred while executing: ${cause?.message}`, {
1175
+ cause
1176
+ });
1177
+ __publicField(this, "name", "UnknownNodeError");
1178
+ }
1179
+ };
1180
+
748
1181
  // src/errors/request.ts
749
1182
  var RequestError = class extends BaseError {
750
- constructor(err, { docsPath: docsPath5, shortMessage }) {
1183
+ constructor(err, {
1184
+ docsPath: docsPath5,
1185
+ metaMessages,
1186
+ shortMessage
1187
+ }) {
751
1188
  super(shortMessage, {
752
1189
  cause: err,
753
- docsPath: docsPath5
1190
+ docsPath: docsPath5,
1191
+ metaMessages
754
1192
  });
755
1193
  this.name = err.name;
756
1194
  }
757
1195
  };
758
1196
  var RpcRequestError = class extends RequestError {
759
1197
  constructor(err, { docsPath: docsPath5, shortMessage }) {
760
- super(err, { docsPath: docsPath5, shortMessage });
1198
+ super(err, { docsPath: docsPath5, metaMessages: err.metaMessages, shortMessage });
761
1199
  __publicField(this, "code");
762
1200
  this.code = err.code;
763
1201
  this.name = err.name;
@@ -863,6 +1301,24 @@ var JsonRpcVersionUnsupportedError = class extends RpcRequestError {
863
1301
  __publicField(this, "code", -32006);
864
1302
  }
865
1303
  };
1304
+ var UserRejectedRequestError = class extends RpcRequestError {
1305
+ constructor(err) {
1306
+ super(err, {
1307
+ shortMessage: "User rejected the request."
1308
+ });
1309
+ __publicField(this, "name", "UserRejectedRequestError");
1310
+ __publicField(this, "code", 4001);
1311
+ }
1312
+ };
1313
+ var SwitchChainError = class extends RpcRequestError {
1314
+ constructor(err) {
1315
+ super(err, {
1316
+ shortMessage: "An error occurred when attempting to switch chain."
1317
+ });
1318
+ __publicField(this, "name", "SwitchChainError");
1319
+ __publicField(this, "code", 4902);
1320
+ }
1321
+ };
866
1322
  var UnknownRpcError = class extends RequestError {
867
1323
  constructor(err) {
868
1324
  super(err, {
@@ -877,24 +1333,27 @@ var HttpRequestError = class extends BaseError {
877
1333
  constructor({
878
1334
  body,
879
1335
  details,
1336
+ headers,
880
1337
  status,
881
1338
  url
882
1339
  }) {
883
- super(
884
- [
885
- "HTTP request failed.",
886
- "",
887
- `Status: ${status}`,
888
- `URL: ${url}`,
1340
+ super("HTTP request failed.", {
1341
+ details,
1342
+ metaMessages: [
1343
+ status && `Status: ${status}`,
1344
+ `URL: ${getUrl(url)}`,
889
1345
  `Request body: ${stringify(body)}`
890
- ].join("\n"),
891
- {
892
- details
893
- }
894
- );
1346
+ ].filter(Boolean)
1347
+ });
895
1348
  __publicField(this, "name", "HttpRequestError");
1349
+ __publicField(this, "body");
1350
+ __publicField(this, "headers");
896
1351
  __publicField(this, "status");
1352
+ __publicField(this, "url");
1353
+ this.body = body;
1354
+ this.headers = headers;
897
1355
  this.status = status;
1356
+ this.url = url;
898
1357
  }
899
1358
  };
900
1359
  var WebSocketRequestError = class extends BaseError {
@@ -903,17 +1362,10 @@ var WebSocketRequestError = class extends BaseError {
903
1362
  details,
904
1363
  url
905
1364
  }) {
906
- super(
907
- [
908
- "WebSocket request failed.",
909
- "",
910
- `URL: ${url}`,
911
- `Request body: ${stringify(body)}`
912
- ].join("\n"),
913
- {
914
- details
915
- }
916
- );
1365
+ super("WebSocket request failed.", {
1366
+ details,
1367
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1368
+ });
917
1369
  __publicField(this, "name", "WebSocketRequestError");
918
1370
  }
919
1371
  };
@@ -923,18 +1375,11 @@ var RpcError = class extends BaseError {
923
1375
  error,
924
1376
  url
925
1377
  }) {
926
- super(
927
- [
928
- "RPC Request failed.",
929
- "",
930
- `URL: ${url}`,
931
- `Request body: ${stringify(body)}`
932
- ].join("\n"),
933
- {
934
- cause: error,
935
- details: error.message
936
- }
937
- );
1378
+ super("RPC Request failed.", {
1379
+ cause: error,
1380
+ details: error.message,
1381
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1382
+ });
938
1383
  __publicField(this, "code");
939
1384
  __publicField(this, "name", "RpcError");
940
1385
  this.code = error.code;
@@ -945,73 +1390,21 @@ var TimeoutError = class extends BaseError {
945
1390
  body,
946
1391
  url
947
1392
  }) {
1393
+ super("The request took too long to respond.", {
1394
+ details: "The request timed out.",
1395
+ metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`]
1396
+ });
1397
+ __publicField(this, "name", "TimeoutError");
1398
+ }
1399
+ };
1400
+
1401
+ // src/errors/transport.ts
1402
+ var UrlRequiredError = class extends BaseError {
1403
+ constructor() {
948
1404
  super(
949
- [
950
- "The request took too long to respond.",
951
- "",
952
- `URL: ${url}`,
953
- `Request body: ${stringify(body)}`
954
- ].join("\n"),
1405
+ "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
955
1406
  {
956
- details: "The request timed out."
957
- }
958
- );
959
- __publicField(this, "name", "TimeoutError");
960
- }
961
- };
962
-
963
- // src/errors/transaction.ts
964
- var InvalidGasArgumentsError = class extends BaseError {
965
- constructor() {
966
- super("`maxFeePerGas` cannot be less than `maxPriorityFeePerGas`");
967
- __publicField(this, "name", "InvalidGasArgumentsError");
968
- }
969
- };
970
- var TransactionNotFoundError = class extends BaseError {
971
- constructor({
972
- blockHash,
973
- blockNumber,
974
- blockTag,
975
- hash: hash2,
976
- index
977
- }) {
978
- let identifier = "Transaction";
979
- if (blockTag && index !== void 0)
980
- identifier = `Transaction at block time "${blockTag}" at index "${index}"`;
981
- if (blockHash && index !== void 0)
982
- identifier = `Transaction at block hash "${blockHash}" at index "${index}"`;
983
- if (blockNumber && index !== void 0)
984
- identifier = `Transaction at block number "${blockNumber}" at index "${index}"`;
985
- if (hash2)
986
- identifier = `Transaction with hash "${hash2}"`;
987
- super(`${identifier} could not be found.`);
988
- __publicField(this, "name", "TransactionNotFoundError");
989
- }
990
- };
991
- var TransactionReceiptNotFoundError = class extends BaseError {
992
- constructor({ hash: hash2 }) {
993
- super(
994
- `Transaction receipt with hash "${hash2}" could not be found. The Transaction may not be processed on a block yet.`
995
- );
996
- __publicField(this, "name", "TransactionReceiptNotFoundError");
997
- }
998
- };
999
- var WaitForTransactionReceiptTimeoutError = class extends BaseError {
1000
- constructor({ hash: hash2 }) {
1001
- super(
1002
- `Timed out while waiting for transaction with hash "${hash2}" to be confirmed.`
1003
- );
1004
- __publicField(this, "name", "WaitForTransactionReceiptTimeoutError");
1005
- }
1006
- };
1007
-
1008
- // src/errors/transport.ts
1009
- var UrlRequiredError = class extends BaseError {
1010
- constructor() {
1011
- super(
1012
- "No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.",
1013
- {
1014
- docsPath: "/docs/clients/intro"
1407
+ docsPath: "/docs/clients/intro"
1015
1408
  }
1016
1409
  );
1017
1410
  }
@@ -1049,6 +1442,8 @@ function isBytes(value) {
1049
1442
  return false;
1050
1443
  if (typeof value !== "object")
1051
1444
  return false;
1445
+ if (!("BYTES_PER_ELEMENT" in value))
1446
+ return false;
1052
1447
  return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
1053
1448
  }
1054
1449
 
@@ -1068,6 +1463,8 @@ function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) {
1068
1463
  return padBytes(hexOrBytes, { dir, size: size2 });
1069
1464
  }
1070
1465
  function padHex(hex_, { dir, size: size2 = 32 } = {}) {
1466
+ if (size2 === null)
1467
+ return hex_;
1071
1468
  let hex = hex_.replace("0x", "");
1072
1469
  if (hex.length > size2 * 2)
1073
1470
  throw new SizeExceedsPaddingSizeError({
@@ -1081,6 +1478,8 @@ function padHex(hex_, { dir, size: size2 = 32 } = {}) {
1081
1478
  )}`;
1082
1479
  }
1083
1480
  function padBytes(bytes, { dir, size: size2 = 32 } = {}) {
1481
+ if (size2 === null)
1482
+ return bytes;
1084
1483
  if (bytes.length > size2)
1085
1484
  throw new SizeExceedsPaddingSizeError({
1086
1485
  size: bytes.length,
@@ -1145,10 +1544,10 @@ function sliceHex(value_, start, end) {
1145
1544
  return `0x${value}`;
1146
1545
  }
1147
1546
 
1148
- // src/utils/encoding/encodeHex.ts
1547
+ // src/utils/encoding/toHex.ts
1149
1548
  var hexes = Array.from(
1150
1549
  { length: 256 },
1151
- (v, i) => i.toString(16).padStart(2, "0")
1550
+ (_v, i) => i.toString(16).padStart(2, "0")
1152
1551
  );
1153
1552
  function boolToHex(value) {
1154
1553
  return `0x${Number(value)}`;
@@ -1160,7 +1559,7 @@ function bytesToHex(value) {
1160
1559
  }
1161
1560
  return `0x${hex}`;
1162
1561
  }
1163
- function encodeHex(value) {
1562
+ function toHex(value) {
1164
1563
  if (typeof value === "number" || typeof value === "bigint")
1165
1564
  return numberToHex(value);
1166
1565
  if (typeof value === "string") {
@@ -1202,14 +1601,9 @@ function stringToHex(value) {
1202
1601
  return `0x${hex}`;
1203
1602
  }
1204
1603
 
1205
- // src/utils/encoding/encodeBytes.ts
1604
+ // src/utils/encoding/toBytes.ts
1206
1605
  var encoder = new TextEncoder();
1207
- function boolToBytes(value) {
1208
- const bytes = new Uint8Array(1);
1209
- bytes[0] = Number(value);
1210
- return bytes;
1211
- }
1212
- function encodeBytes(value) {
1606
+ function toBytes(value) {
1213
1607
  if (typeof value === "number" || typeof value === "bigint")
1214
1608
  return numberToBytes(value);
1215
1609
  if (typeof value === "boolean")
@@ -1218,6 +1612,11 @@ function encodeBytes(value) {
1218
1612
  return hexToBytes(value);
1219
1613
  return stringToBytes(value);
1220
1614
  }
1615
+ function boolToBytes(value) {
1616
+ const bytes = new Uint8Array(1);
1617
+ bytes[0] = Number(value);
1618
+ return bytes;
1619
+ }
1221
1620
  function hexToBytes(hex_) {
1222
1621
  let hex = hex_.slice(2);
1223
1622
  if (hex.length % 2)
@@ -1228,7 +1627,7 @@ function hexToBytes(hex_) {
1228
1627
  const hexByte = hex.slice(start, start + 2);
1229
1628
  const byte = Number.parseInt(hexByte, 16);
1230
1629
  if (Number.isNaN(byte) || byte < 0)
1231
- throw new Error("Invalid byte sequence");
1630
+ throw new BaseError(`Invalid byte sequence ("${hexByte}" in "${hex}").`);
1232
1631
  bytes[index] = byte;
1233
1632
  }
1234
1633
  return bytes;
@@ -1241,15 +1640,15 @@ function stringToBytes(value) {
1241
1640
  return encoder.encode(value);
1242
1641
  }
1243
1642
 
1244
- // src/utils/encoding/encodeRlp.ts
1245
- function encodeRlp(hexOrBytes, to_) {
1643
+ // src/utils/encoding/toRlp.ts
1644
+ function toRlp(hexOrBytes, to_) {
1246
1645
  const to = to_ || "hex";
1247
1646
  return format(bytesToRlp(parse(hexOrBytes)), to);
1248
1647
  }
1249
1648
  function parse(hexOrBytes) {
1250
1649
  if (Array.isArray(hexOrBytes))
1251
1650
  return hexOrBytes.map(parse);
1252
- return typeof hexOrBytes === "string" ? encodeBytes(hexOrBytes) : hexOrBytes;
1651
+ return typeof hexOrBytes === "string" ? toBytes(hexOrBytes) : hexOrBytes;
1253
1652
  }
1254
1653
  function format(bytes, type = "bytes") {
1255
1654
  return type === "hex" ? bytesToHex(bytes) : bytes;
@@ -1266,11 +1665,11 @@ function bytesToRlp(bytes) {
1266
1665
  function encodeLength(length, offset) {
1267
1666
  if (length < 56)
1268
1667
  return [offset + length];
1269
- return [encodeBytes(length).length + offset + 55, ...encodeBytes(length)];
1668
+ return [toBytes(length).length + offset + 55, ...toBytes(length)];
1270
1669
  }
1271
1670
 
1272
- // src/utils/encoding/decodeHex.ts
1273
- function decodeHex(hex, to) {
1671
+ // src/utils/encoding/fromHex.ts
1672
+ function fromHex(hex, to) {
1274
1673
  if (to === "number")
1275
1674
  return hexToNumber(hex);
1276
1675
  if (to === "bigint")
@@ -1307,8 +1706,8 @@ function hexToString(hex) {
1307
1706
  return new TextDecoder().decode(bytes);
1308
1707
  }
1309
1708
 
1310
- // src/utils/encoding/decodeBytes.ts
1311
- function decodeBytes(bytes, to) {
1709
+ // src/utils/encoding/fromBytes.ts
1710
+ function fromBytes(bytes, to) {
1312
1711
  if (to === "number")
1313
1712
  return bytesToNumber(bytes);
1314
1713
  if (to === "bigint")
@@ -1336,8 +1735,8 @@ function bytesToString(bytes) {
1336
1735
  return new TextDecoder().decode(bytes);
1337
1736
  }
1338
1737
 
1339
- // src/utils/encoding/decodeRlp.ts
1340
- function decodeRlp(value, to) {
1738
+ // src/utils/encoding/fromRlp.ts
1739
+ function fromRlp(value, to) {
1341
1740
  const bytes = parse2(value);
1342
1741
  const [data, consumed] = rlpToBytes(bytes);
1343
1742
  if (consumed < bytes.length)
@@ -1442,50 +1841,18 @@ function extractFunctionType(def) {
1442
1841
  return extractFunctionParts(def).type;
1443
1842
  }
1444
1843
 
1445
- // src/utils/contract/getContractError.ts
1446
- var EXECUTION_REVERTED_ERROR_CODE = 3;
1447
- function getContractError(err, {
1448
- abi,
1449
- address,
1450
- args,
1451
- docsPath: docsPath5,
1452
- functionName,
1453
- sender
1454
- }) {
1455
- const { code, data, message } = err instanceof RawContractError ? err : err.cause || {};
1456
- let cause = err;
1457
- if (err instanceof AbiDecodingZeroDataError) {
1458
- cause = new ContractFunctionZeroDataError({ functionName });
1459
- } else if (code === EXECUTION_REVERTED_ERROR_CODE && (data || message)) {
1460
- cause = new ContractFunctionRevertedError({
1461
- abi,
1462
- data,
1463
- functionName,
1464
- message
1465
- });
1466
- }
1467
- return new ContractFunctionExecutionError(cause, {
1468
- abi,
1469
- args,
1470
- contractAddress: address,
1471
- docsPath: docsPath5,
1472
- functionName,
1473
- sender
1474
- });
1475
- }
1476
-
1477
1844
  // src/utils/hash/keccak256.ts
1478
1845
  import { keccak_256 } from "@noble/hashes/sha3";
1479
1846
  function keccak256(value, to_) {
1480
1847
  const to = to_ || "hex";
1481
- const bytes = keccak_256(value);
1848
+ const bytes = keccak_256(isHex(value) ? toBytes(value) : value);
1482
1849
  if (to === "bytes")
1483
1850
  return bytes;
1484
- return encodeHex(bytes);
1851
+ return toHex(bytes);
1485
1852
  }
1486
1853
 
1487
1854
  // src/utils/hash/hashFunction.ts
1488
- var hash = (value) => keccak256(encodeBytes(value));
1855
+ var hash = (value) => keccak256(toBytes(value));
1489
1856
  function hashFunction(def) {
1490
1857
  const name = extractFunctionName(def);
1491
1858
  const params = extractFunctionParams(def);
@@ -1494,20 +1861,25 @@ function hashFunction(def) {
1494
1861
  return hash(`${name}(${params.map(({ type }) => type).join(",")})`);
1495
1862
  }
1496
1863
 
1497
- // src/utils/hash/getEventSignature.ts
1498
- var getEventSignature = (event) => hashFunction(event);
1864
+ // src/utils/hash/getEventSelector.ts
1865
+ var getEventSelector = (event) => hashFunction(event);
1499
1866
 
1500
- // src/utils/hash/getFunctionSignature.ts
1501
- var getFunctionSignature = (fn) => slice(hashFunction(fn), 0, 4);
1867
+ // src/utils/hash/getFunctionSelector.ts
1868
+ var getFunctionSelector = (fn) => slice(hashFunction(fn), 0, 4);
1869
+
1870
+ // src/utils/address/isAddress.ts
1871
+ var addressRegex = /^0x[a-fA-F0-9]{40}$/;
1872
+ function isAddress(address) {
1873
+ return addressRegex.test(address);
1874
+ }
1502
1875
 
1503
1876
  // src/utils/address/getAddress.ts
1504
- var addressRegex = /^(0x)?[a-fA-F0-9]{40}$/;
1505
1877
  function checksumAddress(address_) {
1506
1878
  const hexAddress = address_.substring(2).toLowerCase();
1507
1879
  const hash2 = keccak256(stringToBytes(hexAddress), "bytes");
1508
1880
  let address = hexAddress.split("");
1509
1881
  for (let i = 0; i < 40; i += 2) {
1510
- if (hash2?.[i >> 1] >> 4 >= 8 && address[i]) {
1882
+ if (hash2[i >> 1] >> 4 >= 8 && address[i]) {
1511
1883
  address[i] = address[i].toUpperCase();
1512
1884
  }
1513
1885
  if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) {
@@ -1517,61 +1889,52 @@ function checksumAddress(address_) {
1517
1889
  return `0x${address.join("")}`;
1518
1890
  }
1519
1891
  function getAddress(address) {
1520
- if (!addressRegex.test(address))
1892
+ if (!isAddress(address))
1521
1893
  throw new InvalidAddressError({ address });
1522
1894
  return checksumAddress(address);
1523
1895
  }
1524
1896
 
1525
1897
  // src/utils/address/getContractAddress.ts
1526
- function getContractAddress(opts) {
1898
+ function getContractAddress2(opts) {
1527
1899
  if (opts.opcode === "CREATE2")
1528
1900
  return getCreate2Address(opts);
1529
1901
  return getCreateAddress(opts);
1530
1902
  }
1531
1903
  function getCreateAddress(opts) {
1532
- const from = encodeBytes(getAddress(opts.from));
1533
- let nonce = encodeBytes(opts.nonce);
1904
+ const from = toBytes(getAddress(opts.from));
1905
+ let nonce = toBytes(opts.nonce);
1534
1906
  if (nonce[0] === 0)
1535
1907
  nonce = new Uint8Array([]);
1536
1908
  return getAddress(
1537
- `0x${keccak256(encodeRlp([from, nonce], "bytes")).slice(26)}`
1909
+ `0x${keccak256(toRlp([from, nonce], "bytes")).slice(26)}`
1538
1910
  );
1539
1911
  }
1540
1912
  function getCreate2Address(opts) {
1541
- const from = encodeBytes(getAddress(opts.from));
1542
- const salt = pad(
1543
- isBytes(opts.salt) ? opts.salt : encodeBytes(opts.salt),
1544
- { size: 32 }
1545
- );
1546
- const bytecodeHash = encodeBytes(
1913
+ const from = toBytes(getAddress(opts.from));
1914
+ const salt = pad(isBytes(opts.salt) ? opts.salt : toBytes(opts.salt), {
1915
+ size: 32
1916
+ });
1917
+ const bytecodeHash = toBytes(
1547
1918
  keccak256(
1548
- isBytes(opts.bytecode) ? opts.bytecode : encodeBytes(opts.bytecode)
1919
+ isBytes(opts.bytecode) ? opts.bytecode : toBytes(opts.bytecode)
1549
1920
  )
1550
1921
  );
1551
1922
  return getAddress(
1552
- slice(
1553
- keccak256(concat([encodeBytes("0xff"), from, salt, bytecodeHash])),
1554
- 12
1555
- )
1923
+ slice(keccak256(concat([toBytes("0xff"), from, salt, bytecodeHash])), 12)
1556
1924
  );
1557
1925
  }
1558
1926
 
1559
- // src/utils/address/isAddress.ts
1560
- function isAddress(address) {
1561
- try {
1562
- return Boolean(getAddress(address));
1563
- } catch {
1564
- return false;
1565
- }
1566
- }
1567
-
1568
1927
  // src/utils/address/isAddressEqual.ts
1569
1928
  function isAddressEqual(a, b) {
1570
- return getAddress(a) === getAddress(b);
1929
+ if (!isAddress(a))
1930
+ throw new InvalidAddressError({ address: a });
1931
+ if (!isAddress(b))
1932
+ throw new InvalidAddressError({ address: b });
1933
+ return a.toLowerCase() === b.toLowerCase();
1571
1934
  }
1572
1935
 
1573
- // src/utils/abi/encodeAbi.ts
1574
- function encodeAbi({ params, values }) {
1936
+ // src/utils/abi/encodeAbiParameters.ts
1937
+ function encodeAbiParameters(params, values) {
1575
1938
  if (params.length !== values.length)
1576
1939
  throw new AbiEncodingLengthMismatchError({
1577
1940
  expectedLength: params.length,
@@ -1621,13 +1984,13 @@ function prepareParam({
1621
1984
  return encodeNumber(value, { signed });
1622
1985
  }
1623
1986
  if (param.type.startsWith("bytes")) {
1624
- return encodeBytes2(value, { param });
1987
+ return encodeBytes(value, { param });
1625
1988
  }
1626
1989
  if (param.type === "string") {
1627
1990
  return encodeString(value);
1628
1991
  }
1629
1992
  throw new InvalidAbiEncodingTypeError(param.type, {
1630
- docsPath: "/docs/contract/encodeAbi"
1993
+ docsPath: "/docs/contract/encodeAbiParameters"
1631
1994
  });
1632
1995
  }
1633
1996
  function encodeParams(preparedParams) {
@@ -1655,6 +2018,8 @@ function encodeParams(preparedParams) {
1655
2018
  return concat([...staticParams, ...dynamicParams]);
1656
2019
  }
1657
2020
  function encodeAddress(value) {
2021
+ if (!isAddress(value))
2022
+ throw new InvalidAddressError({ address: value });
1658
2023
  return { dynamic: false, encoded: padHex(value.toLowerCase()) };
1659
2024
  }
1660
2025
  function encodeArray(value, {
@@ -1695,13 +2060,17 @@ function encodeArray(value, {
1695
2060
  encoded: concat(preparedParams.map(({ encoded }) => encoded))
1696
2061
  };
1697
2062
  }
1698
- function encodeBytes2(value, { param }) {
2063
+ function encodeBytes(value, { param }) {
1699
2064
  const [_, size_] = param.type.split("bytes");
1700
2065
  if (!size_) {
1701
2066
  const partsLength = Math.floor(size(value) / 32);
1702
2067
  const parts = [];
1703
2068
  for (let i = 0; i < partsLength + 1; i++) {
1704
- parts.push(padHex(slice(value, i * 32, (i + 1) * 32), { dir: "right" }));
2069
+ parts.push(
2070
+ padHex(slice(value, i * 32, (i + 1) * 32), {
2071
+ dir: "right"
2072
+ })
2073
+ );
1705
2074
  }
1706
2075
  return {
1707
2076
  dynamic: true,
@@ -1711,6 +2080,11 @@ function encodeBytes2(value, { param }) {
1711
2080
  ])
1712
2081
  };
1713
2082
  }
2083
+ if (size(value) !== parseInt(size_))
2084
+ throw new AbiEncodingBytesSizeMismatchError({
2085
+ expectedSize: parseInt(size_),
2086
+ value
2087
+ });
1714
2088
  return { dynamic: false, encoded: padHex(value, { dir: "right" }) };
1715
2089
  }
1716
2090
  function encodeBool(value) {
@@ -1745,7 +2119,8 @@ function encodeTuple(value, { param }) {
1745
2119
  value: value[index]
1746
2120
  });
1747
2121
  preparedParams.push(preparedParam);
1748
- dynamic = preparedParam.dynamic;
2122
+ if (preparedParam.dynamic)
2123
+ dynamic = true;
1749
2124
  }
1750
2125
  return {
1751
2126
  dynamic,
@@ -1760,19 +2135,16 @@ function getArrayComponents(type) {
1760
2135
  ) : void 0;
1761
2136
  }
1762
2137
 
1763
- // src/utils/abi/decodeAbi.ts
1764
- function decodeAbi({ data, params }) {
2138
+ // src/utils/abi/decodeAbiParameters.ts
2139
+ function decodeAbiParameters(params, data) {
1765
2140
  if (data === "0x" && params.length > 0)
1766
2141
  throw new AbiDecodingZeroDataError();
1767
2142
  if (size(data) % 32 !== 0)
1768
2143
  throw new AbiDecodingDataSizeInvalidError(size(data));
1769
- const values = decodeParams({
2144
+ return decodeParams({
1770
2145
  data,
1771
2146
  params
1772
2147
  });
1773
- if (values.length === 0)
1774
- return void 0;
1775
- return values;
1776
2148
  }
1777
2149
  function decodeParams({
1778
2150
  data,
@@ -1809,7 +2181,7 @@ function decodeParam({
1809
2181
  return decodeString(data, { position });
1810
2182
  }
1811
2183
  if (param.type.startsWith("bytes")) {
1812
- return decodeBytes2(data, { param, position });
2184
+ return decodeBytes(data, { param, position });
1813
2185
  }
1814
2186
  let value = slice(data, position, position + 32);
1815
2187
  if (param.type.startsWith("uint") || param.type.startsWith("int")) {
@@ -1822,7 +2194,7 @@ function decodeParam({
1822
2194
  return decodeBool(value);
1823
2195
  }
1824
2196
  throw new InvalidAbiDecodingTypeError(param.type, {
1825
- docsPath: "/docs/contract/decodeAbi"
2197
+ docsPath: "/docs/contract/decodeAbiParameters"
1826
2198
  });
1827
2199
  }
1828
2200
  function decodeAddress(value) {
@@ -1882,12 +2254,15 @@ function decodeArray(data, {
1882
2254
  function decodeBool(value) {
1883
2255
  return { consumed: 32, value: hexToBool(value) };
1884
2256
  }
1885
- function decodeBytes2(data, { param, position }) {
2257
+ function decodeBytes(data, { param, position }) {
1886
2258
  const [_, size2] = param.type.split("bytes");
1887
2259
  if (!size2) {
1888
2260
  const offset = hexToNumber(slice(data, position, position + 32));
1889
2261
  const length = hexToNumber(slice(data, offset, offset + 32));
1890
- const value2 = slice(data, offset + 32, offset + 32 + length);
2262
+ const value2 = (
2263
+ // If there is no length, we have zero data.
2264
+ length === 0 ? "0x" : slice(data, offset + 32, offset + 32 + length)
2265
+ );
1891
2266
  return { consumed: 32, value: value2 };
1892
2267
  }
1893
2268
  const value = slice(data, position, position + parseInt(size2));
@@ -1986,7 +2361,7 @@ function decodeErrorResult({
1986
2361
  throw new AbiDecodingZeroDataError();
1987
2362
  const abi_ = [...abi || [], solidityError, solidityPanic];
1988
2363
  const abiItem = abi_.find(
1989
- (x) => x.type === "error" && signature === getFunctionSignature(formatAbiItem(x))
2364
+ (x) => x.type === "error" && signature === getFunctionSelector(formatAbiItem(x))
1990
2365
  );
1991
2366
  if (!abiItem)
1992
2367
  throw new AbiErrorSignatureNotFoundError(signature, {
@@ -1994,7 +2369,7 @@ function decodeErrorResult({
1994
2369
  });
1995
2370
  return {
1996
2371
  abiItem,
1997
- args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: abiItem.inputs }) : void 0,
2372
+ args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : void 0,
1998
2373
  errorName: abiItem.name
1999
2374
  };
2000
2375
  }
@@ -2007,7 +2382,7 @@ function decodeEventLog({
2007
2382
  }) {
2008
2383
  const [signature, ...argTopics] = topics;
2009
2384
  const abiItem = abi.find(
2010
- (x) => signature === getEventSignature(formatAbiItem(x))
2385
+ (x) => signature === getEventSelector(formatAbiItem(x))
2011
2386
  );
2012
2387
  if (!(abiItem && "name" in abiItem))
2013
2388
  throw new AbiEventSignatureNotFoundError(signature, {
@@ -2029,9 +2404,9 @@ function decodeEventLog({
2029
2404
  args[param.name || i] = decodeTopic({ param, value: topic });
2030
2405
  }
2031
2406
  }
2032
- if (data) {
2407
+ if (data && data !== "0x") {
2033
2408
  const params = inputs.filter((x) => !("indexed" in x && x.indexed));
2034
- const decodedData = decodeAbi({ params, data });
2409
+ const decodedData = decodeAbiParameters(params, data);
2035
2410
  if (decodedData) {
2036
2411
  if (isUnnamed)
2037
2412
  args = [...args, ...decodedData];
@@ -2050,15 +2425,18 @@ function decodeEventLog({
2050
2425
  function decodeTopic({ param, value }) {
2051
2426
  if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
2052
2427
  return value;
2053
- const decodedArg = decodeAbi({ params: [param], data: value }) || [];
2428
+ const decodedArg = decodeAbiParameters([param], value) || [];
2054
2429
  return decodedArg[0];
2055
2430
  }
2056
2431
 
2057
2432
  // src/utils/abi/decodeFunctionData.ts
2058
- function decodeFunctionData({ abi, data }) {
2433
+ function decodeFunctionData({
2434
+ abi,
2435
+ data
2436
+ }) {
2059
2437
  const signature = slice(data, 0, 4);
2060
2438
  const description = abi.find(
2061
- (x) => signature === getFunctionSignature(formatAbiItem(x))
2439
+ (x) => signature === getFunctionSelector(formatAbiItem(x))
2062
2440
  );
2063
2441
  if (!description)
2064
2442
  throw new AbiFunctionSignatureNotFoundError(signature, {
@@ -2066,12 +2444,16 @@ function decodeFunctionData({ abi, data }) {
2066
2444
  });
2067
2445
  return {
2068
2446
  functionName: description.name,
2069
- args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbi({ data: slice(data, 4), params: description.inputs }) : void 0
2447
+ args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbiParameters(description.inputs, slice(data, 4)) : void 0
2070
2448
  };
2071
2449
  }
2072
2450
 
2073
2451
  // src/utils/abi/getAbiItem.ts
2074
- function getAbiItem({ abi, args = [], name }) {
2452
+ function getAbiItem({
2453
+ abi,
2454
+ args = [],
2455
+ name
2456
+ }) {
2075
2457
  const abiItems = abi.filter((x) => "name" in x && x.name === name);
2076
2458
  if (abiItems.length === 0)
2077
2459
  return void 0;
@@ -2159,7 +2541,7 @@ function decodeFunctionResult({
2159
2541
  throw new AbiFunctionNotFoundError(functionName, { docsPath });
2160
2542
  if (!("outputs" in description))
2161
2543
  throw new AbiFunctionOutputsNotFoundError(functionName, { docsPath });
2162
- const values = decodeAbi({ data, params: description.outputs });
2544
+ const values = decodeAbiParameters(description.outputs, data);
2163
2545
  if (values && values.length > 1)
2164
2546
  return values;
2165
2547
  if (values && values.length === 1)
@@ -2185,10 +2567,10 @@ function encodeDeployData({
2185
2567
  throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
2186
2568
  if (!description.inputs || description.inputs.length === 0)
2187
2569
  throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath2 });
2188
- const data = encodeAbi({
2189
- params: description.inputs,
2190
- values: args
2191
- });
2570
+ const data = encodeAbiParameters(
2571
+ description.inputs,
2572
+ args
2573
+ );
2192
2574
  return concatHex([bytecode, data]);
2193
2575
  }
2194
2576
 
@@ -2203,25 +2585,29 @@ function encodeErrorResult({ abi, errorName, args }) {
2203
2585
  if (!description)
2204
2586
  throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath3 });
2205
2587
  const definition = formatAbiItem(description);
2206
- const signature = getFunctionSignature(definition);
2588
+ const signature = getFunctionSelector(definition);
2207
2589
  let data = "0x";
2208
2590
  if (args && args.length > 0) {
2209
2591
  if (!("inputs" in description && description.inputs))
2210
2592
  throw new AbiErrorInputsNotFoundError(errorName, { docsPath: docsPath3 });
2211
- data = encodeAbi({ params: description.inputs, values: args });
2593
+ data = encodeAbiParameters(description.inputs, args);
2212
2594
  }
2213
2595
  return concatHex([signature, data]);
2214
2596
  }
2215
2597
 
2216
2598
  // src/utils/abi/encodeEventTopics.ts
2217
2599
  function encodeEventTopics({ abi, eventName, args }) {
2218
- const abiItem = getAbiItem({ abi, args, name: eventName });
2600
+ const abiItem = getAbiItem({
2601
+ abi,
2602
+ args,
2603
+ name: eventName
2604
+ });
2219
2605
  if (!abiItem)
2220
2606
  throw new AbiEventNotFoundError(eventName, {
2221
2607
  docsPath: "/docs/contract/encodeEventTopics"
2222
2608
  });
2223
2609
  const definition = formatAbiItem(abiItem);
2224
- const signature = getEventSignature(definition);
2610
+ const signature = getEventSelector(definition);
2225
2611
  let topics = [];
2226
2612
  if (args && "inputs" in abiItem) {
2227
2613
  const args_ = Array.isArray(args) ? args : abiItem.inputs?.map((x) => args[x.name]) ?? [];
@@ -2238,14 +2624,18 @@ function encodeArg({
2238
2624
  value
2239
2625
  }) {
2240
2626
  if (param.type === "string" || param.type === "bytes")
2241
- return keccak256(encodeBytes(value));
2627
+ return keccak256(toBytes(value));
2242
2628
  if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/))
2243
2629
  throw new FilterTypeNotSupportedError(param.type);
2244
- return encodeAbi({ params: [param], values: [value] });
2630
+ return encodeAbiParameters([param], [value]);
2245
2631
  }
2246
2632
 
2247
2633
  // src/utils/abi/encodeFunctionData.ts
2248
- function encodeFunctionData({ abi, args, functionName }) {
2634
+ function encodeFunctionData({
2635
+ abi,
2636
+ args,
2637
+ functionName
2638
+ }) {
2249
2639
  const description = getAbiItem({
2250
2640
  abi,
2251
2641
  args,
@@ -2256,11 +2646,11 @@ function encodeFunctionData({ abi, args, functionName }) {
2256
2646
  docsPath: "/docs/contract/encodeFunctionData"
2257
2647
  });
2258
2648
  const definition = formatAbiItem(description);
2259
- const signature = getFunctionSignature(definition);
2260
- const data = "inputs" in description && description.inputs ? encodeAbi({
2261
- params: description.inputs,
2262
- values: args ?? []
2263
- }) : void 0;
2649
+ const signature = getFunctionSelector(definition);
2650
+ const data = "inputs" in description && description.inputs ? encodeAbiParameters(
2651
+ description.inputs,
2652
+ args ?? []
2653
+ ) : void 0;
2264
2654
  return concatHex([signature, data ?? "0x"]);
2265
2655
  }
2266
2656
 
@@ -2281,7 +2671,73 @@ function encodeFunctionResult({
2281
2671
  let values = Array.isArray(result) ? result : [result];
2282
2672
  if (description.outputs.length === 0 && !values[0])
2283
2673
  values = [];
2284
- return encodeAbi({ params: description.outputs, values });
2674
+ return encodeAbiParameters(description.outputs, values);
2675
+ }
2676
+
2677
+ // src/utils/regex.ts
2678
+ var arrayRegex = /^(.*)\[([0-9]*)\]$/;
2679
+ var bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;
2680
+ var integerRegex = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;
2681
+
2682
+ // src/utils/abi/encodePacked.ts
2683
+ function encodePacked(types, values) {
2684
+ if (types.length !== values.length)
2685
+ throw new AbiEncodingLengthMismatchError({
2686
+ expectedLength: types.length,
2687
+ givenLength: values.length
2688
+ });
2689
+ let data = [];
2690
+ for (let i = 0; i < types.length; i++) {
2691
+ const type = types[i];
2692
+ const value = values[i];
2693
+ data.push(encode(type, value));
2694
+ }
2695
+ return concat(data);
2696
+ }
2697
+ function encode(type, value, isArray = false) {
2698
+ if (type === "address") {
2699
+ let address = value;
2700
+ if (!isAddress(address))
2701
+ throw new InvalidAddressError({ address });
2702
+ return pad(address.toLowerCase(), {
2703
+ size: isArray ? 32 : null
2704
+ });
2705
+ }
2706
+ if (type === "string")
2707
+ return stringToHex(value);
2708
+ if (type === "bytes")
2709
+ return value;
2710
+ if (type === "bool")
2711
+ return pad(boolToHex(value), { size: isArray ? 32 : 1 });
2712
+ const intMatch = type.match(integerRegex);
2713
+ if (intMatch) {
2714
+ const [_type, baseType, bits = "256"] = intMatch;
2715
+ const size2 = parseInt(bits) / 8;
2716
+ return numberToHex(value, {
2717
+ size: isArray ? 32 : size2,
2718
+ signed: baseType === "int"
2719
+ });
2720
+ }
2721
+ const bytesMatch = type.match(bytesRegex);
2722
+ if (bytesMatch) {
2723
+ const [_type, size2] = bytesMatch;
2724
+ if (parseInt(size2) !== (value.length - 2) / 2)
2725
+ throw new BytesSizeMismatchError({
2726
+ expectedSize: parseInt(size2),
2727
+ givenSize: (value.length - 2) / 2
2728
+ });
2729
+ return pad(value, { dir: "right", size: isArray ? 32 : null });
2730
+ }
2731
+ const arrayMatch = type.match(arrayRegex);
2732
+ if (arrayMatch && Array.isArray(value)) {
2733
+ const [_type, childType] = arrayMatch;
2734
+ let data = [];
2735
+ for (let i = 0; i < value.length; i++) {
2736
+ data.push(encode(childType, value[i], true));
2737
+ }
2738
+ return concat(data);
2739
+ }
2740
+ throw new UnsupportedPackedAbiType(type);
2285
2741
  }
2286
2742
 
2287
2743
  // src/utils/abi/formatAbiItemWithArgs.ts
@@ -2302,18 +2758,33 @@ function formatAbiItemWithArgs({
2302
2758
  ).join(", ")})`;
2303
2759
  }
2304
2760
 
2761
+ // src/utils/account.ts
2762
+ function getAccount(account) {
2763
+ if (typeof account === "string") {
2764
+ if (!isAddress(account))
2765
+ throw new InvalidAddressError({ address: account });
2766
+ return { address: account, type: "json-rpc" };
2767
+ }
2768
+ if (!isAddress(account.address))
2769
+ throw new InvalidAddressError({ address: account.address });
2770
+ return {
2771
+ ...account,
2772
+ type: "local"
2773
+ };
2774
+ }
2775
+
2305
2776
  // src/utils/promise/withCache.ts
2306
2777
  var promiseCache = /* @__PURE__ */ new Map();
2307
2778
  var responseCache = /* @__PURE__ */ new Map();
2308
- function getCache(cacheKey) {
2309
- const buildCache = (cacheKey2, cache) => ({
2310
- clear: () => cache.delete(cacheKey2),
2311
- get: () => cache.get(cacheKey2),
2312
- set: (data) => cache.set(cacheKey2, data)
2779
+ function getCache(cacheKey2) {
2780
+ const buildCache = (cacheKey3, cache) => ({
2781
+ clear: () => cache.delete(cacheKey3),
2782
+ get: () => cache.get(cacheKey3),
2783
+ set: (data) => cache.set(cacheKey3, data)
2313
2784
  });
2314
- const promise = buildCache(cacheKey, promiseCache);
2785
+ const promise = buildCache(cacheKey2, promiseCache);
2315
2786
  const response = buildCache(
2316
- cacheKey,
2787
+ cacheKey2,
2317
2788
  responseCache
2318
2789
  );
2319
2790
  return {
@@ -2325,8 +2796,8 @@ function getCache(cacheKey) {
2325
2796
  response
2326
2797
  };
2327
2798
  }
2328
- async function withCache(fn, { cacheKey, maxAge = Infinity }) {
2329
- const cache = getCache(cacheKey);
2799
+ async function withCache(fn, { cacheKey: cacheKey2, maxAge = Infinity }) {
2800
+ const cache = getCache(cacheKey2);
2330
2801
  const response = cache.response.get();
2331
2802
  if (response && maxAge > 0) {
2332
2803
  const age = (/* @__PURE__ */ new Date()).getTime() - response.created.getTime();
@@ -2353,25 +2824,22 @@ async function wait(time) {
2353
2824
  function withRetry(fn, {
2354
2825
  delay: delay_ = 100,
2355
2826
  retryCount = 2,
2356
- shouldRetryOnResponse = () => false,
2357
- shouldRetryOnError = () => false
2827
+ shouldRetry = () => true
2358
2828
  } = {}) {
2359
2829
  return new Promise((resolve, reject) => {
2360
2830
  const attemptRetry = async ({ count = 0 } = {}) => {
2361
- const retry = async ({ data } = {}) => {
2362
- const delay = typeof delay_ === "function" ? delay_({ count, data }) : delay_;
2831
+ const retry = async ({ error }) => {
2832
+ const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_;
2363
2833
  if (delay)
2364
2834
  await wait(delay);
2365
2835
  attemptRetry({ count: count + 1 });
2366
2836
  };
2367
2837
  try {
2368
2838
  const data = await fn();
2369
- if (count < retryCount && await shouldRetryOnResponse({ count, data }))
2370
- return retry({ data });
2371
2839
  resolve(data);
2372
2840
  } catch (err) {
2373
- if (count < retryCount && await shouldRetryOnError({ count, error: err }))
2374
- return retry();
2841
+ if (count < retryCount && await shouldRetry({ count, error: err }))
2842
+ return retry({ error: err });
2375
2843
  reject(err);
2376
2844
  }
2377
2845
  };
@@ -2413,11 +2881,11 @@ function withTimeout(fn, {
2413
2881
  }
2414
2882
 
2415
2883
  // src/utils/buildRequest.ts
2416
- var isNonDeterministicError = (error) => {
2417
- if (error instanceof UnknownRpcError)
2418
- return true;
2884
+ var isDeterministicError = (error) => {
2419
2885
  if ("code" in error)
2420
- return error.code === -32603 || error.code === -32e3 || error.code === -32005;
2886
+ return error.code !== -32603 && error.code !== -32005;
2887
+ if (error instanceof HttpRequestError && error.status)
2888
+ return error.status !== 408 && error.status !== 413 && error.status !== 429 && error.status !== 500 && error.status !== 502 && error.status !== 503 && error.status !== 504;
2421
2889
  return false;
2422
2890
  };
2423
2891
  function buildRequest(request, {
@@ -2429,7 +2897,7 @@ function buildRequest(request, {
2429
2897
  try {
2430
2898
  return await request(args);
2431
2899
  } catch (err_) {
2432
- let err = err_;
2900
+ const err = err_;
2433
2901
  if (err.code === -32700)
2434
2902
  throw new ParseRpcError(err);
2435
2903
  if (err.code === -32600)
@@ -2454,15 +2922,26 @@ function buildRequest(request, {
2454
2922
  throw new LimitExceededRpcError(err);
2455
2923
  if (err.code === -32006)
2456
2924
  throw new JsonRpcVersionUnsupportedError(err);
2925
+ if (err.code === 4001)
2926
+ throw new UserRejectedRequestError(err);
2927
+ if (err.code === 4902)
2928
+ throw new SwitchChainError(err);
2457
2929
  if (err_ instanceof BaseError)
2458
2930
  throw err_;
2459
2931
  throw new UnknownRpcError(err);
2460
2932
  }
2461
2933
  },
2462
2934
  {
2463
- delay: ({ count }) => ~~(1 << count) * retryDelay,
2935
+ delay: ({ count, error }) => {
2936
+ if (error && error instanceof HttpRequestError) {
2937
+ const retryAfter = error?.headers?.get("Retry-After");
2938
+ if (retryAfter?.match(/\d/))
2939
+ return parseInt(retryAfter) * 1e3;
2940
+ }
2941
+ return ~~(1 << count) * retryDelay;
2942
+ },
2464
2943
  retryCount,
2465
- shouldRetryOnError: ({ error }) => isNonDeterministicError(error)
2944
+ shouldRetry: ({ error }) => !isDeterministicError(error)
2466
2945
  }
2467
2946
  );
2468
2947
  }
@@ -2506,6 +2985,7 @@ function formatTransaction(transaction) {
2506
2985
  const transaction_ = {
2507
2986
  ...transaction,
2508
2987
  blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null,
2988
+ chainId: transaction.chainId ? hexToNumber(transaction.chainId) : void 0,
2509
2989
  gas: transaction.gas ? BigInt(transaction.gas) : void 0,
2510
2990
  gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : void 0,
2511
2991
  maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : void 0,
@@ -2578,12 +3058,13 @@ function formatFeeHistory(feeHistory) {
2578
3058
  }
2579
3059
 
2580
3060
  // src/utils/formatters/log.ts
2581
- function formatLog(log) {
3061
+ function formatLog(log, { args, eventName } = {}) {
2582
3062
  return {
2583
3063
  ...log,
2584
3064
  blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null,
2585
3065
  logIndex: log.logIndex ? BigInt(log.logIndex) : null,
2586
- transactionIndex: log.transactionIndex ? BigInt(log.transactionIndex) : null
3066
+ transactionIndex: log.transactionIndex ? BigInt(log.transactionIndex) : null,
3067
+ ...eventName ? { args, eventName } : {}
2587
3068
  };
2588
3069
  }
2589
3070
 
@@ -2599,7 +3080,7 @@ function formatTransactionReceipt(transactionReceipt) {
2599
3080
  cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null,
2600
3081
  effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null,
2601
3082
  gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null,
2602
- logs: transactionReceipt.logs ? transactionReceipt.logs.map(formatLog) : null,
3083
+ logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null,
2603
3084
  transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null,
2604
3085
  status: transactionReceipt.status ? statuses[transactionReceipt.status] : null,
2605
3086
  type: transactionReceipt.type ? transactionType[transactionReceipt.type] : null
@@ -2625,36 +3106,155 @@ var defineTransactionRequest = defineFormatter({
2625
3106
  format: formatTransactionRequest
2626
3107
  });
2627
3108
 
3109
+ // src/utils/errors/getNodeError.ts
3110
+ function containsNodeError(err) {
3111
+ return err instanceof TransactionRejectedRpcError || err instanceof InvalidInputRpcError || err instanceof RpcError && err.code === ExecutionRevertedError.code;
3112
+ }
3113
+ function getNodeError(err, args) {
3114
+ const message = err.details.toLowerCase();
3115
+ if (FeeCapTooHighError.nodeMessage.test(message))
3116
+ return new FeeCapTooHighError({
3117
+ cause: err,
3118
+ maxFeePerGas: args?.maxFeePerGas
3119
+ });
3120
+ else if (FeeCapTooLowError.nodeMessage.test(message))
3121
+ return new FeeCapTooLowError({
3122
+ cause: err,
3123
+ maxFeePerGas: args?.maxFeePerGas
3124
+ });
3125
+ else if (NonceTooHighError.nodeMessage.test(message))
3126
+ return new NonceTooHighError({ cause: err, nonce: args?.nonce });
3127
+ else if (NonceTooLowError.nodeMessage.test(message))
3128
+ return new NonceTooLowError({ cause: err, nonce: args?.nonce });
3129
+ else if (NonceMaxValueError.nodeMessage.test(message))
3130
+ return new NonceMaxValueError({ cause: err, nonce: args?.nonce });
3131
+ else if (InsufficientFundsError.nodeMessage.test(message))
3132
+ return new InsufficientFundsError({ cause: err });
3133
+ else if (IntrinsicGasTooHighError.nodeMessage.test(message))
3134
+ return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas });
3135
+ else if (IntrinsicGasTooLowError.nodeMessage.test(message))
3136
+ return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas });
3137
+ else if (TransactionTypeNotSupportedError.nodeMessage.test(message))
3138
+ return new TransactionTypeNotSupportedError({ cause: err });
3139
+ else if (TipAboveFeeCapError.nodeMessage.test(message))
3140
+ return new TipAboveFeeCapError({
3141
+ cause: err,
3142
+ maxFeePerGas: args?.maxFeePerGas,
3143
+ maxPriorityFeePerGas: args?.maxPriorityFeePerGas
3144
+ });
3145
+ else if (message.match(ExecutionRevertedError.nodeMessage) || "code" in err.cause && err.cause?.code === ExecutionRevertedError.code)
3146
+ return new ExecutionRevertedError({
3147
+ cause: err,
3148
+ message: err.cause.details
3149
+ });
3150
+ return new UnknownNodeError({
3151
+ cause: err.cause.cause
3152
+ });
3153
+ }
3154
+
3155
+ // src/utils/errors/getCallError.ts
3156
+ function getCallError(err, {
3157
+ docsPath: docsPath5,
3158
+ ...args
3159
+ }) {
3160
+ let cause = err;
3161
+ if (containsNodeError(err))
3162
+ cause = getNodeError(err, args);
3163
+ return new CallExecutionError(cause, {
3164
+ docsPath: docsPath5,
3165
+ ...args
3166
+ });
3167
+ }
3168
+
3169
+ // src/utils/errors/getContractError.ts
3170
+ var EXECUTION_REVERTED_ERROR_CODE = 3;
3171
+ function getContractError(err, {
3172
+ abi,
3173
+ address,
3174
+ args,
3175
+ docsPath: docsPath5,
3176
+ functionName,
3177
+ sender
3178
+ }) {
3179
+ const { code, data, message } = err instanceof RawContractError ? err : err instanceof CallExecutionError || err instanceof EstimateGasExecutionError ? err.cause?.cause?.cause || {} : err.cause || {};
3180
+ let cause = err;
3181
+ if (err instanceof AbiDecodingZeroDataError) {
3182
+ cause = new ContractFunctionZeroDataError({ functionName });
3183
+ } else if (code === EXECUTION_REVERTED_ERROR_CODE && (data || message)) {
3184
+ cause = new ContractFunctionRevertedError({
3185
+ abi,
3186
+ data,
3187
+ functionName,
3188
+ message
3189
+ });
3190
+ }
3191
+ return new ContractFunctionExecutionError(cause, {
3192
+ abi,
3193
+ args,
3194
+ contractAddress: address,
3195
+ docsPath: docsPath5,
3196
+ functionName,
3197
+ sender
3198
+ });
3199
+ }
3200
+
3201
+ // src/utils/errors/getEstimateGasError.ts
3202
+ function getEstimateGasError(err, {
3203
+ docsPath: docsPath5,
3204
+ ...args
3205
+ }) {
3206
+ let cause = err;
3207
+ if (containsNodeError(err))
3208
+ cause = getNodeError(err, args);
3209
+ return new EstimateGasExecutionError(cause, {
3210
+ docsPath: docsPath5,
3211
+ ...args
3212
+ });
3213
+ }
3214
+
3215
+ // src/utils/errors/getTransactionError.ts
3216
+ function getTransactionError(err, {
3217
+ docsPath: docsPath5,
3218
+ ...args
3219
+ }) {
3220
+ let cause = err;
3221
+ if (containsNodeError(err))
3222
+ cause = getNodeError(err, args);
3223
+ return new TransactionExecutionError(cause, {
3224
+ docsPath: docsPath5,
3225
+ ...args
3226
+ });
3227
+ }
3228
+
2628
3229
  // src/utils/rpc.ts
2629
- import fetch from "isomorphic-unfetch";
2630
3230
  import WebSocket from "isomorphic-ws";
2631
3231
 
2632
3232
  // src/utils/stringify.ts
2633
- function stringify(value) {
2634
- return JSON.stringify(
2635
- value,
2636
- (_, value2) => typeof value2 === "bigint" ? value2.toString() : value2
2637
- );
2638
- }
3233
+ var stringify = (value, replacer, space) => JSON.stringify(
3234
+ value,
3235
+ (key, value_) => {
3236
+ const value2 = typeof value_ === "bigint" ? value_.toString() : value_;
3237
+ return typeof replacer === "function" ? replacer(key, value2) : value2;
3238
+ },
3239
+ space
3240
+ );
2639
3241
 
2640
3242
  // src/utils/rpc.ts
2641
3243
  var id = 0;
2642
- async function http(url, {
2643
- body,
2644
- retryDelay = 150,
2645
- retryCount = 3,
2646
- timeout = 0
2647
- }) {
2648
- const response = await withRetry(
2649
- () => withTimeout(
3244
+ async function http(url, { body, fetchOptions = {}, timeout = 1e4 }) {
3245
+ const { headers, method, signal: signal_ } = fetchOptions;
3246
+ try {
3247
+ const response = await withTimeout(
2650
3248
  async ({ signal }) => {
2651
3249
  const response2 = await fetch(url, {
3250
+ ...fetchOptions,
3251
+ body: stringify({ jsonrpc: "2.0", id: id++, ...body }),
2652
3252
  headers: {
3253
+ ...headers,
2653
3254
  "Content-Type": "application/json"
2654
3255
  },
2655
- method: "POST",
2656
- body: stringify({ jsonrpc: "2.0", id: id++, ...body }),
2657
- signal: timeout > 0 ? signal : void 0
3256
+ method: method || "POST",
3257
+ signal: signal_ || (timeout > 0 ? signal : void 0)
2658
3258
  });
2659
3259
  return response2;
2660
3260
  },
@@ -2663,42 +3263,39 @@ async function http(url, {
2663
3263
  timeout,
2664
3264
  signal: true
2665
3265
  }
2666
- ),
2667
- {
2668
- delay: ({ count, data: data2 }) => {
2669
- const retryAfter = data2?.headers.get("Retry-After");
2670
- if (retryAfter?.match(/\d/))
2671
- return parseInt(retryAfter) * 1e3;
2672
- return ~~(1 << count) * retryDelay;
2673
- },
2674
- retryCount,
2675
- shouldRetryOnResponse: async ({ data: data2 }) => {
2676
- if (data2.status >= 500)
2677
- return true;
2678
- if ([408, 413, 429].includes(data2.status))
2679
- return true;
2680
- return false;
2681
- }
3266
+ );
3267
+ let data;
3268
+ if (response.headers.get("Content-Type")?.startsWith("application/json")) {
3269
+ data = await response.json();
3270
+ } else {
3271
+ data = await response.text();
2682
3272
  }
2683
- );
2684
- let data;
2685
- if (response.headers.get("Content-Type")?.startsWith("application/json")) {
2686
- data = await response.json();
2687
- } else {
2688
- data = await response.text();
2689
- }
2690
- if (!response.ok) {
3273
+ if (!response.ok) {
3274
+ throw new HttpRequestError({
3275
+ body,
3276
+ details: stringify(data.error) || response.statusText,
3277
+ headers: response.headers,
3278
+ status: response.status,
3279
+ url
3280
+ });
3281
+ }
3282
+ if (data.error) {
3283
+ throw new RpcError({ body, error: data.error, url });
3284
+ }
3285
+ return data;
3286
+ } catch (err) {
3287
+ if (err instanceof HttpRequestError)
3288
+ throw err;
3289
+ if (err instanceof RpcError)
3290
+ throw err;
3291
+ if (err instanceof TimeoutError)
3292
+ throw err;
2691
3293
  throw new HttpRequestError({
2692
3294
  body,
2693
- details: stringify(data.error) || response.statusText,
2694
- status: response.status,
3295
+ details: err.message,
2695
3296
  url
2696
3297
  });
2697
3298
  }
2698
- if (data.error) {
2699
- throw new RpcError({ body, error: data.error, url });
2700
- }
2701
- return data;
2702
3299
  }
2703
3300
  var sockets = /* @__PURE__ */ new Map();
2704
3301
  async function getSocket(url_) {
@@ -2777,7 +3374,7 @@ function webSocket(socket, {
2777
3374
  }
2778
3375
  async function webSocketAsync(socket, {
2779
3376
  body,
2780
- timeout = 0
3377
+ timeout = 1e4
2781
3378
  }) {
2782
3379
  return withTimeout(
2783
3380
  () => new Promise(
@@ -2799,47 +3396,1584 @@ var rpc = {
2799
3396
  webSocketAsync
2800
3397
  };
2801
3398
 
2802
- // src/utils/unit/constants.ts
2803
- var etherUnits = {
2804
- gwei: 9,
2805
- wei: 18
2806
- };
2807
- var gweiUnits = {
2808
- ether: -9,
2809
- wei: 9
2810
- };
2811
- var weiUnits = {
2812
- ether: -18,
2813
- gwei: -9
2814
- };
3399
+ // src/utils/transaction/assertRequest.ts
3400
+ function assertRequest(args) {
3401
+ const { account, gasPrice, maxFeePerGas, maxPriorityFeePerGas, to } = args;
3402
+ if (account && !isAddress(account.address))
3403
+ throw new InvalidAddressError({ address: account.address });
3404
+ if (to && !isAddress(to))
3405
+ throw new InvalidAddressError({ address: to });
3406
+ if (typeof gasPrice !== "undefined" && (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined"))
3407
+ throw new FeeConflictError();
3408
+ if (maxFeePerGas && maxFeePerGas > 2n ** 256n - 1n)
3409
+ throw new FeeCapTooHighError({ maxFeePerGas });
3410
+ if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas)
3411
+ throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });
3412
+ }
3413
+
3414
+ // src/actions/public/call.ts
3415
+ async function call(client, args) {
3416
+ const {
3417
+ account,
3418
+ blockNumber,
3419
+ blockTag = "latest",
3420
+ accessList,
3421
+ data,
3422
+ gas,
3423
+ gasPrice,
3424
+ maxFeePerGas,
3425
+ maxPriorityFeePerGas,
3426
+ nonce,
3427
+ to,
3428
+ value,
3429
+ ...rest
3430
+ } = args;
3431
+ try {
3432
+ assertRequest(args);
3433
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
3434
+ const formatter = client.chain?.formatters?.transactionRequest;
3435
+ const request_ = format3(
3436
+ {
3437
+ from: account?.address,
3438
+ accessList,
3439
+ data,
3440
+ gas,
3441
+ gasPrice,
3442
+ maxFeePerGas,
3443
+ maxPriorityFeePerGas,
3444
+ nonce,
3445
+ to,
3446
+ value,
3447
+ // Pick out extra data that might exist on the chain's transaction request type.
3448
+ ...extract(rest, { formatter })
3449
+ },
3450
+ {
3451
+ formatter: formatter || formatTransactionRequest
3452
+ }
3453
+ );
3454
+ const response = await client.request({
3455
+ method: "eth_call",
3456
+ params: [request_, blockNumberHex || blockTag]
3457
+ });
3458
+ if (response === "0x")
3459
+ return { data: void 0 };
3460
+ return { data: response };
3461
+ } catch (err) {
3462
+ throw getCallError(err, {
3463
+ ...args,
3464
+ chain: client.chain
3465
+ });
3466
+ }
3467
+ }
3468
+
3469
+ // src/actions/public/simulateContract.ts
3470
+ async function simulateContract(client, {
3471
+ abi,
3472
+ address,
3473
+ args,
3474
+ functionName,
3475
+ ...callRequest
3476
+ }) {
3477
+ const calldata = encodeFunctionData({
3478
+ abi,
3479
+ args,
3480
+ functionName
3481
+ });
3482
+ try {
3483
+ const { data } = await call(client, {
3484
+ data: calldata,
3485
+ to: address,
3486
+ ...callRequest
3487
+ });
3488
+ const result = decodeFunctionResult({
3489
+ abi,
3490
+ args,
3491
+ functionName,
3492
+ data: data || "0x"
3493
+ });
3494
+ return {
3495
+ result,
3496
+ request: {
3497
+ abi,
3498
+ address,
3499
+ args,
3500
+ functionName,
3501
+ ...callRequest
3502
+ }
3503
+ };
3504
+ } catch (err) {
3505
+ throw getContractError(err, {
3506
+ abi,
3507
+ address,
3508
+ args,
3509
+ docsPath: "/docs/contract/simulateContract",
3510
+ functionName,
3511
+ sender: callRequest.account?.address
3512
+ });
3513
+ }
3514
+ }
3515
+
3516
+ // src/actions/public/createPendingTransactionFilter.ts
3517
+ async function createPendingTransactionFilter(client) {
3518
+ const id2 = await client.request({
3519
+ method: "eth_newPendingTransactionFilter"
3520
+ });
3521
+ return { id: id2, type: "transaction" };
3522
+ }
3523
+
3524
+ // src/actions/public/createBlockFilter.ts
3525
+ async function createBlockFilter(client) {
3526
+ const id2 = await client.request({
3527
+ method: "eth_newBlockFilter"
3528
+ });
3529
+ return { id: id2, type: "block" };
3530
+ }
3531
+
3532
+ // src/actions/public/createEventFilter.ts
3533
+ async function createEventFilter(client, {
3534
+ address,
3535
+ args,
3536
+ event,
3537
+ fromBlock,
3538
+ toBlock
3539
+ } = {}) {
3540
+ let topics = [];
3541
+ if (event)
3542
+ topics = encodeEventTopics({
3543
+ abi: [event],
3544
+ eventName: event.name,
3545
+ args
3546
+ });
3547
+ const id2 = await client.request({
3548
+ method: "eth_newFilter",
3549
+ params: [
3550
+ {
3551
+ address,
3552
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
3553
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
3554
+ ...topics.length ? { topics } : {}
3555
+ }
3556
+ ]
3557
+ });
3558
+ return {
3559
+ abi: event ? [event] : void 0,
3560
+ args,
3561
+ eventName: event ? event.name : void 0,
3562
+ id: id2,
3563
+ type: "event"
3564
+ };
3565
+ }
3566
+
3567
+ // src/actions/public/createContractEventFilter.ts
3568
+ async function createContractEventFilter(client, {
3569
+ address,
3570
+ abi,
3571
+ args,
3572
+ eventName,
3573
+ fromBlock,
3574
+ toBlock
3575
+ }) {
3576
+ const topics = eventName ? encodeEventTopics({
3577
+ abi,
3578
+ args,
3579
+ eventName
3580
+ }) : void 0;
3581
+ const id2 = await client.request({
3582
+ method: "eth_newFilter",
3583
+ params: [
3584
+ {
3585
+ address,
3586
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
3587
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock,
3588
+ topics
3589
+ }
3590
+ ]
3591
+ });
3592
+ return {
3593
+ abi,
3594
+ args,
3595
+ eventName,
3596
+ id: id2,
3597
+ type: "event"
3598
+ };
3599
+ }
3600
+
3601
+ // src/actions/public/estimateGas.ts
3602
+ async function estimateGas(client, args) {
3603
+ try {
3604
+ const {
3605
+ account,
3606
+ accessList,
3607
+ blockNumber,
3608
+ blockTag = "latest",
3609
+ data,
3610
+ gas,
3611
+ gasPrice,
3612
+ maxFeePerGas,
3613
+ maxPriorityFeePerGas,
3614
+ nonce,
3615
+ to,
3616
+ value,
3617
+ ...rest
3618
+ } = args.account.type === "local" ? await prepareRequest(client, args) : args;
3619
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
3620
+ assertRequest(args);
3621
+ const formatter = client.chain?.formatters?.transactionRequest;
3622
+ const request = format3(
3623
+ {
3624
+ from: account.address,
3625
+ accessList,
3626
+ data,
3627
+ gas,
3628
+ gasPrice,
3629
+ maxFeePerGas,
3630
+ maxPriorityFeePerGas,
3631
+ nonce,
3632
+ to,
3633
+ value,
3634
+ // Pick out extra data that might exist on the chain's transaction request type.
3635
+ ...extract(rest, { formatter })
3636
+ },
3637
+ {
3638
+ formatter: formatter || formatTransactionRequest
3639
+ }
3640
+ );
3641
+ const balance = await client.request({
3642
+ method: "eth_estimateGas",
3643
+ params: [request, blockNumberHex || blockTag]
3644
+ });
3645
+ return BigInt(balance);
3646
+ } catch (err) {
3647
+ throw getEstimateGasError(err, {
3648
+ ...args,
3649
+ chain: client.chain
3650
+ });
3651
+ }
3652
+ }
3653
+
3654
+ // src/actions/public/estimateContractGas.ts
3655
+ async function estimateContractGas(client, {
3656
+ abi,
3657
+ address,
3658
+ args,
3659
+ functionName,
3660
+ ...request
3661
+ }) {
3662
+ const data = encodeFunctionData({
3663
+ abi,
3664
+ args,
3665
+ functionName
3666
+ });
3667
+ try {
3668
+ const gas = await estimateGas(client, {
3669
+ data,
3670
+ to: address,
3671
+ ...request
3672
+ });
3673
+ return gas;
3674
+ } catch (err) {
3675
+ throw getContractError(err, {
3676
+ abi,
3677
+ address,
3678
+ args,
3679
+ docsPath: "/docs/contract/simulateContract",
3680
+ functionName,
3681
+ sender: request.account?.address
3682
+ });
3683
+ }
3684
+ }
3685
+
3686
+ // src/actions/public/getBalance.ts
3687
+ async function getBalance(client, { address, blockNumber, blockTag = "latest" }) {
3688
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
3689
+ const balance = await client.request({
3690
+ method: "eth_getBalance",
3691
+ params: [address, blockNumberHex || blockTag]
3692
+ });
3693
+ return BigInt(balance);
3694
+ }
3695
+
3696
+ // src/actions/public/getBlock.ts
3697
+ async function getBlock(client, {
3698
+ blockHash,
3699
+ blockNumber,
3700
+ blockTag = "latest",
3701
+ includeTransactions = false
3702
+ } = {}) {
3703
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
3704
+ let block = null;
3705
+ if (blockHash) {
3706
+ block = await client.request({
3707
+ method: "eth_getBlockByHash",
3708
+ params: [blockHash, includeTransactions]
3709
+ });
3710
+ } else {
3711
+ block = await client.request({
3712
+ method: "eth_getBlockByNumber",
3713
+ params: [blockNumberHex || blockTag, includeTransactions]
3714
+ });
3715
+ }
3716
+ if (!block)
3717
+ throw new BlockNotFoundError({ blockHash, blockNumber });
3718
+ return format3(block, {
3719
+ formatter: client.chain?.formatters?.block || formatBlock
3720
+ });
3721
+ }
3722
+
3723
+ // src/actions/public/getBlockNumber.ts
3724
+ var cacheKey = (id2) => `blockNumber.${id2}`;
3725
+ function getBlockNumberCache(id2) {
3726
+ return getCache(cacheKey(id2));
3727
+ }
3728
+ async function getBlockNumber(client, { maxAge = client.pollingInterval } = {}) {
3729
+ const blockNumberHex = await withCache(
3730
+ () => client.request({
3731
+ method: "eth_blockNumber"
3732
+ }),
3733
+ { cacheKey: cacheKey(client.uid), maxAge }
3734
+ );
3735
+ return BigInt(blockNumberHex);
3736
+ }
3737
+
3738
+ // src/actions/public/getBlockTransactionCount.ts
3739
+ async function getBlockTransactionCount(client, {
3740
+ blockHash,
3741
+ blockNumber,
3742
+ blockTag = "latest"
3743
+ } = {}) {
3744
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
3745
+ let count = null;
3746
+ if (blockHash) {
3747
+ count = await client.request({
3748
+ method: "eth_getBlockTransactionCountByHash",
3749
+ params: [blockHash]
3750
+ });
3751
+ } else {
3752
+ count = await client.request({
3753
+ method: "eth_getBlockTransactionCountByNumber",
3754
+ params: [blockNumberHex || blockTag]
3755
+ });
3756
+ }
3757
+ return hexToNumber(count);
3758
+ }
3759
+
3760
+ // src/actions/public/getBytecode.ts
3761
+ async function getBytecode(client, { address, blockNumber, blockTag = "latest" }) {
3762
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
3763
+ const hex = await client.request({
3764
+ method: "eth_getCode",
3765
+ params: [address, blockNumberHex || blockTag]
3766
+ });
3767
+ if (hex === "0x")
3768
+ return void 0;
3769
+ return hex;
3770
+ }
3771
+
3772
+ // src/actions/public/getChainId.ts
3773
+ async function getChainId(client) {
3774
+ const chainIdHex = await client.request({ method: "eth_chainId" });
3775
+ return hexToNumber(chainIdHex);
3776
+ }
3777
+
3778
+ // src/actions/public/getFeeHistory.ts
3779
+ async function getFeeHistory(client, {
3780
+ blockCount,
3781
+ blockNumber,
3782
+ blockTag = "latest",
3783
+ rewardPercentiles
3784
+ }) {
3785
+ const blockNumberHex = blockNumber ? numberToHex(blockNumber) : void 0;
3786
+ const feeHistory = await client.request({
3787
+ method: "eth_feeHistory",
3788
+ params: [
3789
+ numberToHex(blockCount),
3790
+ blockNumberHex || blockTag,
3791
+ rewardPercentiles
3792
+ ]
3793
+ });
3794
+ return formatFeeHistory(feeHistory);
3795
+ }
3796
+
3797
+ // src/actions/public/getFilterChanges.ts
3798
+ async function getFilterChanges(client, {
3799
+ filter
3800
+ }) {
3801
+ const logs = await client.request({
3802
+ method: "eth_getFilterChanges",
3803
+ params: [filter.id]
3804
+ });
3805
+ return logs.map((log) => {
3806
+ if (typeof log === "string")
3807
+ return log;
3808
+ const { eventName, args } = "abi" in filter && filter.abi ? decodeEventLog({
3809
+ abi: filter.abi,
3810
+ data: log.data,
3811
+ topics: log.topics
3812
+ }) : { eventName: void 0, args: void 0 };
3813
+ return formatLog(log, { args, eventName });
3814
+ });
3815
+ }
3816
+
3817
+ // src/actions/public/getFilterLogs.ts
3818
+ async function getFilterLogs(client, { filter }) {
3819
+ const logs = await client.request({
3820
+ method: "eth_getFilterLogs",
3821
+ params: [filter.id]
3822
+ });
3823
+ return logs.map((log) => {
3824
+ const { eventName, args } = "abi" in filter && filter.abi ? decodeEventLog({
3825
+ abi: filter.abi,
3826
+ data: log.data,
3827
+ topics: log.topics
3828
+ }) : { eventName: void 0, args: void 0 };
3829
+ return formatLog(log, { args, eventName });
3830
+ });
3831
+ }
3832
+
3833
+ // src/actions/public/getGasPrice.ts
3834
+ async function getGasPrice(client) {
3835
+ const gasPrice = await client.request({
3836
+ method: "eth_gasPrice"
3837
+ });
3838
+ return BigInt(gasPrice);
3839
+ }
3840
+
3841
+ // src/actions/public/getLogs.ts
3842
+ async function getLogs(client, {
3843
+ address,
3844
+ blockHash,
3845
+ fromBlock,
3846
+ toBlock,
3847
+ event,
3848
+ args
3849
+ } = {}) {
3850
+ let topics = [];
3851
+ if (event)
3852
+ topics = encodeEventTopics({
3853
+ abi: [event],
3854
+ eventName: event.name,
3855
+ args
3856
+ });
3857
+ let logs;
3858
+ if (blockHash) {
3859
+ logs = await client.request({
3860
+ method: "eth_getLogs",
3861
+ params: [{ address, topics, blockHash }]
3862
+ });
3863
+ } else {
3864
+ logs = await client.request({
3865
+ method: "eth_getLogs",
3866
+ params: [
3867
+ {
3868
+ address,
3869
+ topics,
3870
+ fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock,
3871
+ toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock
3872
+ }
3873
+ ]
3874
+ });
3875
+ }
3876
+ return logs.map((log) => {
3877
+ const { eventName, args: args2 } = event ? decodeEventLog({
3878
+ abi: [event],
3879
+ data: log.data,
3880
+ topics: log.topics
3881
+ }) : { eventName: void 0, args: void 0 };
3882
+ return formatLog(log, { args: args2, eventName });
3883
+ });
3884
+ }
3885
+
3886
+ // src/actions/public/getStorageAt.ts
3887
+ async function getStorageAt(client, { address, blockNumber, blockTag = "latest", slot }) {
3888
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
3889
+ const data = await client.request({
3890
+ method: "eth_getStorageAt",
3891
+ params: [address, slot, blockNumberHex || blockTag]
3892
+ });
3893
+ return data;
3894
+ }
3895
+
3896
+ // src/actions/public/getTransaction.ts
3897
+ async function getTransaction(client, {
3898
+ blockHash,
3899
+ blockNumber,
3900
+ blockTag = "latest",
3901
+ hash: hash2,
3902
+ index
3903
+ }) {
3904
+ const blockNumberHex = blockNumber !== void 0 ? numberToHex(blockNumber) : void 0;
3905
+ let transaction = null;
3906
+ if (hash2) {
3907
+ transaction = await client.request({
3908
+ method: "eth_getTransactionByHash",
3909
+ params: [hash2]
3910
+ });
3911
+ } else if (blockHash) {
3912
+ transaction = await client.request({
3913
+ method: "eth_getTransactionByBlockHashAndIndex",
3914
+ params: [blockHash, numberToHex(index)]
3915
+ });
3916
+ } else if (blockNumberHex || blockTag) {
3917
+ transaction = await client.request({
3918
+ method: "eth_getTransactionByBlockNumberAndIndex",
3919
+ params: [blockNumberHex || blockTag, numberToHex(index)]
3920
+ });
3921
+ }
3922
+ if (!transaction)
3923
+ throw new TransactionNotFoundError({
3924
+ blockHash,
3925
+ blockNumber,
3926
+ blockTag,
3927
+ hash: hash2,
3928
+ index
3929
+ });
3930
+ return format3(transaction, {
3931
+ formatter: client.chain?.formatters?.transaction || formatTransaction
3932
+ });
3933
+ }
3934
+
3935
+ // src/actions/public/getTransactionConfirmations.ts
3936
+ async function getTransactionConfirmations(client, { hash: hash2, transactionReceipt }) {
3937
+ const [blockNumber, transaction] = await Promise.all([
3938
+ getBlockNumber(client),
3939
+ hash2 ? getTransaction(client, { hash: hash2 }) : void 0
3940
+ ]);
3941
+ const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber;
3942
+ if (!transactionBlockNumber)
3943
+ return 0n;
3944
+ return blockNumber - transactionBlockNumber + 1n;
3945
+ }
3946
+
3947
+ // src/actions/public/getTransactionCount.ts
3948
+ async function getTransactionCount(client, { address, blockTag = "latest", blockNumber }) {
3949
+ const count = await client.request({
3950
+ method: "eth_getTransactionCount",
3951
+ params: [address, blockNumber ? numberToHex(blockNumber) : blockTag]
3952
+ });
3953
+ return hexToNumber(count);
3954
+ }
3955
+
3956
+ // src/actions/public/getTransactionReceipt.ts
3957
+ async function getTransactionReceipt(client, { hash: hash2 }) {
3958
+ const receipt = await client.request({
3959
+ method: "eth_getTransactionReceipt",
3960
+ params: [hash2]
3961
+ });
3962
+ if (!receipt)
3963
+ throw new TransactionReceiptNotFoundError({ hash: hash2 });
3964
+ return format3(receipt, {
3965
+ formatter: client.chain?.formatters?.transactionReceipt || formatTransactionReceipt
3966
+ });
3967
+ }
3968
+
3969
+ // src/actions/public/readContract.ts
3970
+ async function readContract(client, {
3971
+ abi,
3972
+ address,
3973
+ args,
3974
+ functionName,
3975
+ ...callRequest
3976
+ }) {
3977
+ const calldata = encodeFunctionData({
3978
+ abi,
3979
+ args,
3980
+ functionName
3981
+ });
3982
+ try {
3983
+ const { data } = await call(client, {
3984
+ data: calldata,
3985
+ to: address,
3986
+ ...callRequest
3987
+ });
3988
+ return decodeFunctionResult({
3989
+ abi,
3990
+ args,
3991
+ functionName,
3992
+ data: data || "0x"
3993
+ });
3994
+ } catch (err) {
3995
+ throw getContractError(err, {
3996
+ abi,
3997
+ address,
3998
+ args,
3999
+ docsPath: "/docs/contract/readContract",
4000
+ functionName
4001
+ });
4002
+ }
4003
+ }
4004
+
4005
+ // src/actions/public/multicall.ts
4006
+ async function multicall(client, args) {
4007
+ const {
4008
+ allowFailure = true,
4009
+ blockNumber,
4010
+ blockTag,
4011
+ contracts,
4012
+ multicallAddress
4013
+ } = args;
4014
+ const calls = contracts.map(({ abi, address, args: args2, functionName }) => {
4015
+ try {
4016
+ const callData = encodeFunctionData({
4017
+ abi,
4018
+ args: args2,
4019
+ functionName
4020
+ });
4021
+ return {
4022
+ allowFailure: true,
4023
+ callData,
4024
+ target: address
4025
+ };
4026
+ } catch (err) {
4027
+ const error = getContractError(err, {
4028
+ abi,
4029
+ address,
4030
+ args: args2,
4031
+ docsPath: "/docs/contract/multicall",
4032
+ functionName
4033
+ });
4034
+ if (!allowFailure)
4035
+ throw error;
4036
+ return {
4037
+ allowFailure: true,
4038
+ callData: "0x",
4039
+ target: address
4040
+ };
4041
+ }
4042
+ });
4043
+ const results = await readContract(client, {
4044
+ abi: multicall3Abi,
4045
+ address: multicallAddress,
4046
+ args: [calls],
4047
+ blockNumber,
4048
+ blockTag,
4049
+ functionName: "aggregate3"
4050
+ });
4051
+ return results.map(({ returnData, success }, i) => {
4052
+ const { callData } = calls[i];
4053
+ const { abi, address, functionName, args: args2 } = contracts[i];
4054
+ try {
4055
+ if (callData === "0x")
4056
+ throw new AbiDecodingZeroDataError();
4057
+ if (!success)
4058
+ throw new RawContractError({ data: returnData });
4059
+ const result = decodeFunctionResult({
4060
+ abi,
4061
+ data: returnData,
4062
+ functionName
4063
+ });
4064
+ return { result, status: "success" };
4065
+ } catch (err) {
4066
+ const error = getContractError(err, {
4067
+ abi,
4068
+ address,
4069
+ args: args2,
4070
+ docsPath: "/docs/contract/multicall",
4071
+ functionName
4072
+ });
4073
+ if (!allowFailure)
4074
+ throw error;
4075
+ return { error, result: void 0, status: "failure" };
4076
+ }
4077
+ });
4078
+ }
4079
+
4080
+ // src/actions/public/uninstallFilter.ts
4081
+ async function uninstallFilter(client, { filter }) {
4082
+ return client.request({
4083
+ method: "eth_uninstallFilter",
4084
+ params: [filter.id]
4085
+ });
4086
+ }
4087
+
4088
+ // src/utils/observe.ts
4089
+ var listenersCache = /* @__PURE__ */ new Map();
4090
+ var cleanupCache = /* @__PURE__ */ new Map();
4091
+ var callbackCount = 0;
4092
+ function observe(observerId, callbacks, fn) {
4093
+ const callbackId = ++callbackCount;
4094
+ const getListeners = () => listenersCache.get(observerId) || [];
4095
+ const unsubscribe = () => {
4096
+ const listeners2 = getListeners();
4097
+ listenersCache.set(
4098
+ observerId,
4099
+ listeners2.filter((cb) => cb.id !== callbackId)
4100
+ );
4101
+ };
4102
+ const unwatch = () => {
4103
+ const cleanup2 = cleanupCache.get(observerId);
4104
+ if (getListeners().length === 1 && cleanup2)
4105
+ cleanup2();
4106
+ unsubscribe();
4107
+ };
4108
+ const listeners = getListeners();
4109
+ listenersCache.set(observerId, [
4110
+ ...listeners,
4111
+ { id: callbackId, fns: callbacks }
4112
+ ]);
4113
+ if (listeners && listeners.length > 0)
4114
+ return unwatch;
4115
+ let emit = {};
4116
+ for (const key in callbacks) {
4117
+ emit[key] = (...args) => {
4118
+ const listeners2 = getListeners();
4119
+ if (listeners2.length === 0)
4120
+ return;
4121
+ listeners2.forEach((listener) => listener.fns[key]?.(...args));
4122
+ };
4123
+ }
4124
+ const cleanup = fn(emit);
4125
+ if (typeof cleanup === "function")
4126
+ cleanupCache.set(observerId, cleanup);
4127
+ return unwatch;
4128
+ }
4129
+
4130
+ // src/actions/public/waitForTransactionReceipt.ts
4131
+ async function waitForTransactionReceipt(client, {
4132
+ confirmations = 1,
4133
+ hash: hash2,
4134
+ onReplaced,
4135
+ pollingInterval = client.pollingInterval,
4136
+ timeout
4137
+ }) {
4138
+ const observerId = JSON.stringify([
4139
+ "waitForTransactionReceipt",
4140
+ client.uid,
4141
+ hash2
4142
+ ]);
4143
+ let transaction;
4144
+ let replacedTransaction;
4145
+ let receipt;
4146
+ return new Promise((resolve, reject) => {
4147
+ if (timeout)
4148
+ setTimeout(
4149
+ () => reject(new WaitForTransactionReceiptTimeoutError({ hash: hash2 })),
4150
+ timeout
4151
+ );
4152
+ const _unobserve = observe(
4153
+ observerId,
4154
+ { onReplaced, resolve, reject },
4155
+ (emit) => {
4156
+ const unwatch = watchBlockNumber(client, {
4157
+ emitMissed: true,
4158
+ emitOnBegin: true,
4159
+ pollingInterval,
4160
+ async onBlockNumber(blockNumber) {
4161
+ const done = async (fn) => {
4162
+ unwatch();
4163
+ fn();
4164
+ _unobserve();
4165
+ };
4166
+ try {
4167
+ if (receipt) {
4168
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
4169
+ return;
4170
+ done(() => emit.resolve(receipt));
4171
+ return;
4172
+ }
4173
+ transaction = await getTransaction(client, { hash: hash2 });
4174
+ receipt = await getTransactionReceipt(client, { hash: hash2 });
4175
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
4176
+ return;
4177
+ done(() => emit.resolve(receipt));
4178
+ } catch (err) {
4179
+ if (transaction && (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError)) {
4180
+ replacedTransaction = transaction;
4181
+ const block = await getBlock(client, {
4182
+ blockNumber,
4183
+ includeTransactions: true
4184
+ });
4185
+ const replacementTransaction = block.transactions.find(
4186
+ ({ from, nonce }) => from === replacedTransaction.from && nonce === replacedTransaction.nonce
4187
+ );
4188
+ if (!replacementTransaction)
4189
+ return;
4190
+ receipt = await getTransactionReceipt(client, {
4191
+ hash: replacementTransaction.hash
4192
+ });
4193
+ if (blockNumber - receipt.blockNumber + 1n < confirmations)
4194
+ return;
4195
+ let reason = "replaced";
4196
+ if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value) {
4197
+ reason = "repriced";
4198
+ } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) {
4199
+ reason = "cancelled";
4200
+ }
4201
+ done(() => {
4202
+ emit.onReplaced?.({
4203
+ reason,
4204
+ replacedTransaction,
4205
+ transaction: replacementTransaction,
4206
+ transactionReceipt: receipt
4207
+ });
4208
+ emit.resolve(receipt);
4209
+ });
4210
+ } else {
4211
+ done(() => emit.reject(err));
4212
+ }
4213
+ }
4214
+ }
4215
+ });
4216
+ return unwatch;
4217
+ }
4218
+ );
4219
+ });
4220
+ }
4221
+
4222
+ // src/utils/poll.ts
4223
+ function poll(fn, { emitOnBegin, initialWaitTime, interval }) {
4224
+ let active = true;
4225
+ const unwatch = () => active = false;
4226
+ const watch = async () => {
4227
+ let data;
4228
+ if (emitOnBegin)
4229
+ data = await fn({ unpoll: unwatch });
4230
+ const initialWait = await initialWaitTime?.(data) ?? interval;
4231
+ await wait(initialWait);
4232
+ const poll2 = async () => {
4233
+ if (!active)
4234
+ return;
4235
+ await fn({ unpoll: unwatch });
4236
+ await wait(interval);
4237
+ poll2();
4238
+ };
4239
+ poll2();
4240
+ };
4241
+ watch();
4242
+ return unwatch;
4243
+ }
4244
+
4245
+ // src/actions/public/watchBlockNumber.ts
4246
+ function watchBlockNumber(client, {
4247
+ emitOnBegin = false,
4248
+ emitMissed = false,
4249
+ onBlockNumber,
4250
+ onError,
4251
+ pollingInterval = client.pollingInterval
4252
+ }) {
4253
+ const observerId = JSON.stringify([
4254
+ "watchBlockNumber",
4255
+ client.uid,
4256
+ emitOnBegin,
4257
+ emitMissed,
4258
+ pollingInterval
4259
+ ]);
4260
+ let prevBlockNumber;
4261
+ return observe(
4262
+ observerId,
4263
+ { onBlockNumber, onError },
4264
+ (emit) => poll(
4265
+ async () => {
4266
+ try {
4267
+ const blockNumber = await getBlockNumber(client, { maxAge: 0 });
4268
+ if (prevBlockNumber) {
4269
+ if (blockNumber === prevBlockNumber)
4270
+ return;
4271
+ if (blockNumber - prevBlockNumber > 1 && emitMissed) {
4272
+ for (let i = prevBlockNumber + 1n; i < blockNumber; i++) {
4273
+ emit.onBlockNumber(i, prevBlockNumber);
4274
+ prevBlockNumber = i;
4275
+ }
4276
+ }
4277
+ }
4278
+ prevBlockNumber = blockNumber;
4279
+ emit.onBlockNumber(blockNumber, prevBlockNumber);
4280
+ } catch (err) {
4281
+ emit.onError?.(err);
4282
+ }
4283
+ },
4284
+ {
4285
+ emitOnBegin,
4286
+ interval: pollingInterval
4287
+ }
4288
+ )
4289
+ );
4290
+ }
4291
+
4292
+ // src/actions/public/watchBlocks.ts
4293
+ function watchBlocks(client, {
4294
+ blockTag = "latest",
4295
+ emitMissed = false,
4296
+ emitOnBegin = false,
4297
+ onBlock,
4298
+ onError,
4299
+ includeTransactions = false,
4300
+ pollingInterval = client.pollingInterval
4301
+ }) {
4302
+ const observerId = JSON.stringify([
4303
+ "watchBlocks",
4304
+ client.uid,
4305
+ emitMissed,
4306
+ emitOnBegin,
4307
+ includeTransactions,
4308
+ pollingInterval
4309
+ ]);
4310
+ let prevBlock;
4311
+ return observe(
4312
+ observerId,
4313
+ { onBlock, onError },
4314
+ (emit) => poll(
4315
+ async () => {
4316
+ try {
4317
+ const block = await getBlock(client, {
4318
+ blockTag,
4319
+ includeTransactions
4320
+ });
4321
+ if (block.number && prevBlock?.number) {
4322
+ if (block.number === prevBlock.number)
4323
+ return;
4324
+ if (block.number - prevBlock.number > 1 && emitMissed) {
4325
+ for (let i = prevBlock?.number + 1n; i < block.number; i++) {
4326
+ const block2 = await getBlock(client, {
4327
+ blockNumber: i,
4328
+ includeTransactions
4329
+ });
4330
+ emit.onBlock(block2, prevBlock);
4331
+ prevBlock = block2;
4332
+ }
4333
+ }
4334
+ }
4335
+ emit.onBlock(block, prevBlock);
4336
+ prevBlock = block;
4337
+ } catch (err) {
4338
+ emit.onError?.(err);
4339
+ }
4340
+ },
4341
+ {
4342
+ emitOnBegin,
4343
+ interval: pollingInterval
4344
+ }
4345
+ )
4346
+ );
4347
+ }
4348
+
4349
+ // src/actions/public/watchContractEvent.ts
4350
+ function watchContractEvent(client, {
4351
+ abi,
4352
+ address,
4353
+ args,
4354
+ batch = true,
4355
+ eventName,
4356
+ onError,
4357
+ onLogs,
4358
+ pollingInterval = client.pollingInterval
4359
+ }) {
4360
+ const observerId = JSON.stringify([
4361
+ "watchContractEvent",
4362
+ address,
4363
+ args,
4364
+ batch,
4365
+ client.uid,
4366
+ eventName,
4367
+ pollingInterval
4368
+ ]);
4369
+ return observe(observerId, { onLogs, onError }, (emit) => {
4370
+ let currentBlockNumber;
4371
+ let filter;
4372
+ let initialized = false;
4373
+ const unwatch = poll(
4374
+ async () => {
4375
+ if (!initialized) {
4376
+ try {
4377
+ filter = await createContractEventFilter(client, {
4378
+ abi,
4379
+ address,
4380
+ args,
4381
+ eventName
4382
+ });
4383
+ } catch {
4384
+ }
4385
+ initialized = true;
4386
+ return;
4387
+ }
4388
+ try {
4389
+ let logs;
4390
+ if (filter) {
4391
+ logs = await getFilterChanges(client, { filter });
4392
+ } else {
4393
+ const blockNumber = await getBlockNumber(client);
4394
+ if (currentBlockNumber && currentBlockNumber !== blockNumber) {
4395
+ logs = await getLogs(client, {
4396
+ address,
4397
+ args,
4398
+ fromBlock: blockNumber,
4399
+ toBlock: blockNumber,
4400
+ event: getAbiItem({
4401
+ abi,
4402
+ name: eventName
4403
+ })
4404
+ });
4405
+ } else {
4406
+ logs = [];
4407
+ }
4408
+ currentBlockNumber = blockNumber;
4409
+ }
4410
+ if (logs.length === 0)
4411
+ return;
4412
+ if (batch)
4413
+ emit.onLogs(logs);
4414
+ else
4415
+ logs.forEach((log) => emit.onLogs([log]));
4416
+ } catch (err) {
4417
+ emit.onError?.(err);
4418
+ }
4419
+ },
4420
+ {
4421
+ emitOnBegin: true,
4422
+ interval: pollingInterval
4423
+ }
4424
+ );
4425
+ return async () => {
4426
+ if (filter)
4427
+ await uninstallFilter(client, { filter });
4428
+ unwatch();
4429
+ };
4430
+ });
4431
+ }
4432
+
4433
+ // src/actions/public/watchEvent.ts
4434
+ function watchEvent(client, {
4435
+ address,
4436
+ args,
4437
+ batch = true,
4438
+ event,
4439
+ onError,
4440
+ onLogs,
4441
+ pollingInterval = client.pollingInterval
4442
+ }) {
4443
+ const observerId = JSON.stringify([
4444
+ "watchEvent",
4445
+ address,
4446
+ args,
4447
+ batch,
4448
+ client.uid,
4449
+ event,
4450
+ pollingInterval
4451
+ ]);
4452
+ return observe(observerId, { onLogs, onError }, (emit) => {
4453
+ let currentBlockNumber;
4454
+ let filter;
4455
+ let initialized = false;
4456
+ const unwatch = poll(
4457
+ async () => {
4458
+ if (!initialized) {
4459
+ try {
4460
+ filter = await createEventFilter(client, {
4461
+ address,
4462
+ args,
4463
+ event
4464
+ });
4465
+ } catch {
4466
+ }
4467
+ initialized = true;
4468
+ return;
4469
+ }
4470
+ try {
4471
+ let logs;
4472
+ if (filter) {
4473
+ logs = await getFilterChanges(client, { filter });
4474
+ } else {
4475
+ const blockNumber = await getBlockNumber(client);
4476
+ if (currentBlockNumber && currentBlockNumber !== blockNumber) {
4477
+ logs = await getLogs(client, {
4478
+ address,
4479
+ args,
4480
+ fromBlock: blockNumber,
4481
+ toBlock: blockNumber,
4482
+ event
4483
+ });
4484
+ } else {
4485
+ logs = [];
4486
+ }
4487
+ currentBlockNumber = blockNumber;
4488
+ }
4489
+ if (logs.length === 0)
4490
+ return;
4491
+ if (batch)
4492
+ emit.onLogs(logs);
4493
+ else
4494
+ logs.forEach((log) => emit.onLogs([log]));
4495
+ } catch (err) {
4496
+ emit.onError?.(err);
4497
+ }
4498
+ },
4499
+ {
4500
+ emitOnBegin: true,
4501
+ interval: pollingInterval
4502
+ }
4503
+ );
4504
+ return async () => {
4505
+ if (filter)
4506
+ await uninstallFilter(client, { filter });
4507
+ unwatch();
4508
+ };
4509
+ });
4510
+ }
4511
+
4512
+ // src/actions/public/watchPendingTransactions.ts
4513
+ function watchPendingTransactions(client, {
4514
+ batch = true,
4515
+ onError,
4516
+ onTransactions,
4517
+ pollingInterval = client.pollingInterval
4518
+ }) {
4519
+ const observerId = JSON.stringify([
4520
+ "watchPendingTransactions",
4521
+ client.uid,
4522
+ batch,
4523
+ pollingInterval
4524
+ ]);
4525
+ return observe(observerId, { onTransactions, onError }, (emit) => {
4526
+ let filter;
4527
+ const unwatch = poll(
4528
+ async () => {
4529
+ try {
4530
+ if (!filter) {
4531
+ try {
4532
+ filter = await createPendingTransactionFilter(client);
4533
+ return;
4534
+ } catch (err) {
4535
+ unwatch();
4536
+ throw err;
4537
+ }
4538
+ }
4539
+ const hashes = await getFilterChanges(client, { filter });
4540
+ if (hashes.length === 0)
4541
+ return;
4542
+ if (batch)
4543
+ emit.onTransactions(hashes);
4544
+ else
4545
+ hashes.forEach((hash2) => emit.onTransactions([hash2]));
4546
+ } catch (err) {
4547
+ emit.onError?.(err);
4548
+ }
4549
+ },
4550
+ {
4551
+ emitOnBegin: true,
4552
+ interval: pollingInterval
4553
+ }
4554
+ );
4555
+ return async () => {
4556
+ if (filter)
4557
+ await uninstallFilter(client, { filter });
4558
+ unwatch();
4559
+ };
4560
+ });
4561
+ }
4562
+
4563
+ // src/actions/test/dropTransaction.ts
4564
+ async function dropTransaction(client, { hash: hash2 }) {
4565
+ return await client.request({
4566
+ method: `${client.mode}_dropTransaction`,
4567
+ params: [hash2]
4568
+ });
4569
+ }
4570
+
4571
+ // src/actions/test/getAutomine.ts
4572
+ async function getAutomine(client) {
4573
+ return await client.request({
4574
+ method: `${client.mode}_getAutomine`
4575
+ });
4576
+ }
4577
+
4578
+ // src/actions/test/getTxpoolContent.ts
4579
+ async function getTxpoolContent(client) {
4580
+ return await client.request({
4581
+ method: "txpool_content"
4582
+ });
4583
+ }
4584
+
4585
+ // src/actions/test/getTxpoolStatus.ts
4586
+ async function getTxpoolStatus(client) {
4587
+ const { pending, queued } = await client.request({
4588
+ method: "txpool_status"
4589
+ });
4590
+ return {
4591
+ pending: hexToNumber(pending),
4592
+ queued: hexToNumber(queued)
4593
+ };
4594
+ }
4595
+
4596
+ // src/actions/test/impersonateAccount.ts
4597
+ async function impersonateAccount(client, { address }) {
4598
+ return await client.request({
4599
+ method: `${client.mode}_impersonateAccount`,
4600
+ params: [address]
4601
+ });
4602
+ }
2815
4603
 
2816
- // src/utils/unit/formatUnit.ts
2817
- function formatUnit(value, decimals) {
2818
- let display = value.toString();
2819
- const negative = display.startsWith("-");
2820
- if (negative)
2821
- display = display.slice(1);
2822
- let [integer, fraction] = [
2823
- display.slice(0, display.length - decimals),
2824
- display.slice(display.length - decimals)
2825
- ];
2826
- fraction = fraction.padStart(decimals, "0");
2827
- fraction = fraction.replace(/(0+)$/, "");
2828
- return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
4604
+ // src/actions/test/increaseTime.ts
4605
+ async function increaseTime(client, { seconds }) {
4606
+ return await client.request({
4607
+ method: "evm_increaseTime",
4608
+ params: [numberToHex(seconds)]
4609
+ });
2829
4610
  }
2830
4611
 
2831
- // src/utils/unit/formatEther.ts
2832
- function formatEther(wei, unit = "wei") {
2833
- return formatUnit(wei, etherUnits[unit]);
4612
+ // src/actions/test/inspectTxpool.ts
4613
+ async function inspectTxpool(client) {
4614
+ return await client.request({
4615
+ method: "txpool_inspect"
4616
+ });
2834
4617
  }
2835
4618
 
2836
- // src/utils/unit/formatGwei.ts
2837
- function formatGwei(wei, unit = "wei") {
2838
- return formatUnit(wei, gweiUnits[unit]);
4619
+ // src/actions/test/mine.ts
4620
+ async function mine(client, { blocks, interval }) {
4621
+ return await client.request({
4622
+ method: `${client.mode}_mine`,
4623
+ params: [numberToHex(blocks), numberToHex(interval || 0)]
4624
+ });
4625
+ }
4626
+
4627
+ // src/actions/test/removeBlockTimestampInterval.ts
4628
+ async function removeBlockTimestampInterval(client) {
4629
+ return await client.request({
4630
+ method: `${client.mode}_removeBlockTimestampInterval`
4631
+ });
4632
+ }
4633
+
4634
+ // src/actions/test/reset.ts
4635
+ async function reset(client, { blockNumber, jsonRpcUrl } = {}) {
4636
+ return await client.request({
4637
+ method: `${client.mode}_reset`,
4638
+ params: [{ forking: { blockNumber: Number(blockNumber), jsonRpcUrl } }]
4639
+ });
4640
+ }
4641
+
4642
+ // src/actions/test/revert.ts
4643
+ async function revert(client, { id: id2 }) {
4644
+ return await client.request({
4645
+ method: "evm_revert",
4646
+ params: [id2]
4647
+ });
4648
+ }
4649
+
4650
+ // src/actions/test/sendUnsignedTransaction.ts
4651
+ async function sendUnsignedTransaction(client, request) {
4652
+ const request_ = formatTransactionRequest(request);
4653
+ const hash2 = await client.request({
4654
+ method: "eth_sendUnsignedTransaction",
4655
+ params: [request_]
4656
+ });
4657
+ return hash2;
4658
+ }
4659
+
4660
+ // src/actions/test/setAutomine.ts
4661
+ async function setAutomine(client, enabled) {
4662
+ return await client.request({
4663
+ method: "evm_setAutomine",
4664
+ params: [enabled]
4665
+ });
4666
+ }
4667
+
4668
+ // src/actions/test/setBalance.ts
4669
+ async function setBalance(client, { address, value }) {
4670
+ return await client.request({
4671
+ method: `${client.mode}_setBalance`,
4672
+ params: [address, numberToHex(value)]
4673
+ });
4674
+ }
4675
+
4676
+ // src/actions/test/setBlockGasLimit.ts
4677
+ async function setBlockGasLimit(client, { gasLimit }) {
4678
+ return await client.request({
4679
+ method: "evm_setBlockGasLimit",
4680
+ params: [numberToHex(gasLimit)]
4681
+ });
4682
+ }
4683
+
4684
+ // src/actions/test/setBlockTimestampInterval.ts
4685
+ async function setBlockTimestampInterval(client, { interval }) {
4686
+ return await client.request({
4687
+ method: `${client.mode}_setBlockTimestampInterval`,
4688
+ params: [interval]
4689
+ });
4690
+ }
4691
+
4692
+ // src/actions/test/setCode.ts
4693
+ async function setCode(client, { address, bytecode }) {
4694
+ return await client.request({
4695
+ method: `${client.mode}_setCode`,
4696
+ params: [address, bytecode]
4697
+ });
4698
+ }
4699
+
4700
+ // src/actions/test/setCoinbase.ts
4701
+ async function setCoinbase(client, { address }) {
4702
+ return await client.request({
4703
+ method: `${client.mode}_setCoinbase`,
4704
+ params: [address]
4705
+ });
4706
+ }
4707
+
4708
+ // src/actions/test/setIntervalMining.ts
4709
+ async function setIntervalMining(client, { interval }) {
4710
+ return await client.request({
4711
+ method: "evm_setIntervalMining",
4712
+ params: [interval]
4713
+ });
4714
+ }
4715
+
4716
+ // src/actions/test/setLoggingEnabled.ts
4717
+ async function setLoggingEnabled(client, enabled) {
4718
+ return await client.request({
4719
+ method: `${client.mode}_setLoggingEnabled`,
4720
+ params: [enabled]
4721
+ });
4722
+ }
4723
+
4724
+ // src/actions/test/setMinGasPrice.ts
4725
+ async function setMinGasPrice(client, { gasPrice }) {
4726
+ return await client.request({
4727
+ method: `${client.mode}_setMinGasPrice`,
4728
+ params: [numberToHex(gasPrice)]
4729
+ });
4730
+ }
4731
+
4732
+ // src/actions/test/setNextBlockBaseFeePerGas.ts
4733
+ async function setNextBlockBaseFeePerGas(client, { baseFeePerGas }) {
4734
+ return await client.request({
4735
+ method: `${client.mode}_setNextBlockBaseFeePerGas`,
4736
+ params: [numberToHex(baseFeePerGas)]
4737
+ });
4738
+ }
4739
+
4740
+ // src/actions/test/setNextBlockTimestamp.ts
4741
+ async function setNextBlockTimestamp(client, { timestamp }) {
4742
+ return await client.request({
4743
+ method: "evm_setNextBlockTimestamp",
4744
+ params: [numberToHex(timestamp)]
4745
+ });
4746
+ }
4747
+
4748
+ // src/actions/test/setNonce.ts
4749
+ async function setNonce(client, { address, nonce }) {
4750
+ return await client.request({
4751
+ method: `${client.mode}_setNonce`,
4752
+ params: [address, numberToHex(nonce)]
4753
+ });
4754
+ }
4755
+
4756
+ // src/actions/test/setRpcUrl.ts
4757
+ async function setRpcUrl(client, jsonRpcUrl) {
4758
+ return await client.request({
4759
+ method: `${client.mode}_setRpcUrl`,
4760
+ params: [jsonRpcUrl]
4761
+ });
4762
+ }
4763
+
4764
+ // src/actions/test/setStorageAt.ts
4765
+ async function setStorageAt(client, { address, index, value }) {
4766
+ return await client.request({
4767
+ method: `${client.mode}_setStorageAt`,
4768
+ params: [
4769
+ address,
4770
+ typeof index === "number" ? numberToHex(index) : index,
4771
+ value
4772
+ ]
4773
+ });
4774
+ }
4775
+
4776
+ // src/actions/test/snapshot.ts
4777
+ async function snapshot(client) {
4778
+ return await client.request({
4779
+ method: "evm_snapshot"
4780
+ });
4781
+ }
4782
+
4783
+ // src/actions/test/stopImpersonatingAccount.ts
4784
+ async function stopImpersonatingAccount(client, { address }) {
4785
+ return await client.request({
4786
+ method: `${client.mode}_stopImpersonatingAccount`,
4787
+ params: [address]
4788
+ });
4789
+ }
4790
+
4791
+ // src/actions/wallet/addChain.ts
4792
+ async function addChain(client, { chain }) {
4793
+ const { id: id2, name, nativeCurrency, rpcUrls, blockExplorers } = chain;
4794
+ await client.request({
4795
+ method: "wallet_addEthereumChain",
4796
+ params: [
4797
+ {
4798
+ chainId: numberToHex(id2),
4799
+ chainName: name,
4800
+ nativeCurrency,
4801
+ rpcUrls: rpcUrls.default.http,
4802
+ blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : void 0
4803
+ }
4804
+ ]
4805
+ });
4806
+ }
4807
+
4808
+ // src/actions/wallet/deployContract.ts
4809
+ function deployContract(walletClient, { abi, args, bytecode, ...request }) {
4810
+ const calldata = encodeDeployData({
4811
+ abi,
4812
+ args,
4813
+ bytecode
4814
+ });
4815
+ return sendTransaction(walletClient, {
4816
+ ...request,
4817
+ data: calldata
4818
+ });
4819
+ }
4820
+
4821
+ // src/actions/wallet/getAddresses.ts
4822
+ async function getAddresses(client) {
4823
+ const addresses = await client.request({ method: "eth_accounts" });
4824
+ return addresses.map((address) => checksumAddress(address));
4825
+ }
4826
+
4827
+ // src/actions/wallet/getPermissions.ts
4828
+ async function getPermissions(client) {
4829
+ const permissions = await client.request({ method: "wallet_getPermissions" });
4830
+ return permissions;
4831
+ }
4832
+
4833
+ // src/actions/wallet/requestAddresses.ts
4834
+ async function requestAddresses(client) {
4835
+ const addresses = await client.request({ method: "eth_requestAccounts" });
4836
+ return addresses.map((address) => getAddress(address));
4837
+ }
4838
+
4839
+ // src/actions/wallet/requestPermissions.ts
4840
+ async function requestPermissions(client, permissions) {
4841
+ return client.request({
4842
+ method: "wallet_requestPermissions",
4843
+ params: [permissions]
4844
+ });
4845
+ }
4846
+
4847
+ // src/actions/wallet/sendTransaction.ts
4848
+ async function sendTransaction(client, args) {
4849
+ const {
4850
+ account,
4851
+ chain,
4852
+ accessList,
4853
+ assertChain = true,
4854
+ data,
4855
+ gas,
4856
+ gasPrice,
4857
+ maxFeePerGas,
4858
+ maxPriorityFeePerGas,
4859
+ nonce,
4860
+ to,
4861
+ value,
4862
+ ...rest
4863
+ } = args;
4864
+ try {
4865
+ assertRequest(args);
4866
+ const currentChainId = await getChainId(client);
4867
+ if (assertChain && chain && currentChainId !== chain?.id)
4868
+ throw new ChainMismatchError({ chain, currentChainId });
4869
+ if (account.type === "local") {
4870
+ const chainId = chain?.id ?? currentChainId;
4871
+ const request2 = await prepareRequest(client, {
4872
+ account,
4873
+ accessList,
4874
+ chain,
4875
+ data,
4876
+ gas,
4877
+ gasPrice,
4878
+ maxFeePerGas,
4879
+ maxPriorityFeePerGas,
4880
+ nonce,
4881
+ to,
4882
+ value,
4883
+ ...rest
4884
+ });
4885
+ const signedRequest = await account.signTransaction({
4886
+ chainId,
4887
+ ...request2
4888
+ });
4889
+ return await client.request({
4890
+ method: "eth_sendRawTransaction",
4891
+ params: [signedRequest]
4892
+ });
4893
+ }
4894
+ const formatter = chain?.formatters?.transactionRequest;
4895
+ const request = format3(
4896
+ {
4897
+ accessList,
4898
+ data,
4899
+ from: account.address,
4900
+ gas,
4901
+ gasPrice,
4902
+ maxFeePerGas,
4903
+ maxPriorityFeePerGas,
4904
+ nonce,
4905
+ to,
4906
+ value,
4907
+ // Pick out extra data that might exist on the chain's transaction request type.
4908
+ ...extract(rest, { formatter })
4909
+ },
4910
+ {
4911
+ formatter: formatter || formatTransactionRequest
4912
+ }
4913
+ );
4914
+ return await client.request({
4915
+ method: "eth_sendTransaction",
4916
+ params: [request]
4917
+ });
4918
+ } catch (err) {
4919
+ throw getTransactionError(err, args);
4920
+ }
4921
+ }
4922
+
4923
+ // src/actions/wallet/signMessage.ts
4924
+ async function signMessage(client, { account, data }) {
4925
+ if (account.type === "local")
4926
+ return account.signMessage(data);
4927
+ return client.request({
4928
+ method: "personal_sign",
4929
+ params: [toHex(data), account.address]
4930
+ });
4931
+ }
4932
+
4933
+ // src/actions/wallet/switchChain.ts
4934
+ async function switchChain(client, { id: id2 }) {
4935
+ await client.request({
4936
+ method: "wallet_switchEthereumChain",
4937
+ params: [
4938
+ {
4939
+ chainId: numberToHex(id2)
4940
+ }
4941
+ ]
4942
+ });
4943
+ }
4944
+
4945
+ // src/actions/wallet/watchAsset.ts
4946
+ async function watchAsset(client, params) {
4947
+ const added = await client.request({
4948
+ method: "wallet_watchAsset",
4949
+ params: [params]
4950
+ });
4951
+ return added;
4952
+ }
4953
+
4954
+ // src/actions/wallet/writeContract.ts
4955
+ async function writeContract(client, {
4956
+ abi,
4957
+ address,
4958
+ args,
4959
+ functionName,
4960
+ ...request
4961
+ }) {
4962
+ const data = encodeFunctionData({
4963
+ abi,
4964
+ args,
4965
+ functionName
4966
+ });
4967
+ const hash2 = await sendTransaction(client, {
4968
+ data,
4969
+ to: address,
4970
+ ...request
4971
+ });
4972
+ return hash2;
2839
4973
  }
2840
4974
 
2841
- // src/utils/unit/parseUnit.ts
2842
- function parseUnit(value, decimals) {
4975
+ // src/utils/unit/parseUnits.ts
4976
+ function parseUnits(value, decimals) {
2843
4977
  let [integer, fraction = "0"] = value.split(".");
2844
4978
  const negative = integer.startsWith("-");
2845
4979
  if (negative)
@@ -2860,14 +4994,79 @@ function parseUnit(value, decimals) {
2860
4994
  return BigInt(`${negative ? "-" : ""}${integer}${fraction}`);
2861
4995
  }
2862
4996
 
2863
- // src/utils/unit/parseEther.ts
2864
- function parseEther(ether, unit = "wei") {
2865
- return parseUnit(ether, etherUnits[unit]);
2866
- }
2867
-
2868
4997
  // src/utils/unit/parseGwei.ts
2869
4998
  function parseGwei(ether, unit = "wei") {
2870
- return parseUnit(ether, gweiUnits[unit]);
4999
+ return parseUnits(ether, gweiUnits[unit]);
5000
+ }
5001
+
5002
+ // src/utils/transaction/prepareRequest.ts
5003
+ var defaultTip = parseGwei("1.5");
5004
+ async function prepareRequest(client, args) {
5005
+ const { account, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce } = args;
5006
+ const block = await getBlock(client, { blockTag: "latest" });
5007
+ const request = { ...args, from: account.address };
5008
+ if (typeof nonce === "undefined")
5009
+ request.nonce = await getTransactionCount(client, {
5010
+ address: account.address,
5011
+ blockTag: "pending"
5012
+ });
5013
+ if (block.baseFeePerGas) {
5014
+ if (typeof gasPrice !== "undefined")
5015
+ throw new BaseError("Chain does not support legacy `gasPrice`.");
5016
+ if (typeof maxFeePerGas === "undefined") {
5017
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas ?? defaultTip;
5018
+ request.maxFeePerGas = block.baseFeePerGas * 120n / 100n + request.maxPriorityFeePerGas;
5019
+ } else {
5020
+ if (typeof maxPriorityFeePerGas === "undefined" && maxFeePerGas < defaultTip)
5021
+ throw new BaseError(
5022
+ "`maxFeePerGas` cannot be less than the default `maxPriorityFeePerGas` (1.5 gwei)."
5023
+ );
5024
+ request.maxFeePerGas = maxFeePerGas;
5025
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas ?? defaultTip;
5026
+ }
5027
+ } else {
5028
+ if (typeof maxFeePerGas !== "undefined" || typeof maxPriorityFeePerGas !== "undefined")
5029
+ throw new BaseError("Chain does not support EIP-1559 fees.");
5030
+ if (typeof gasPrice === "undefined")
5031
+ request.gasPrice = await getGasPrice(client) * 120n / 100n;
5032
+ }
5033
+ if (typeof gas === "undefined")
5034
+ request.gas = await estimateGas(client, {
5035
+ ...request,
5036
+ account: { address: account.address, type: "json-rpc" }
5037
+ });
5038
+ assertRequest(request);
5039
+ return request;
5040
+ }
5041
+
5042
+ // src/utils/unit/formatUnits.ts
5043
+ function formatUnits(value, decimals) {
5044
+ let display = value.toString();
5045
+ const negative = display.startsWith("-");
5046
+ if (negative)
5047
+ display = display.slice(1);
5048
+ display = display.padStart(decimals, "0");
5049
+ let [integer, fraction] = [
5050
+ display.slice(0, display.length - decimals),
5051
+ display.slice(display.length - decimals)
5052
+ ];
5053
+ fraction = fraction.replace(/(0+)$/, "");
5054
+ return `${negative ? "-" : ""}${integer || "0"}${fraction ? `.${fraction}` : ""}`;
5055
+ }
5056
+
5057
+ // src/utils/unit/formatEther.ts
5058
+ function formatEther(wei, unit = "wei") {
5059
+ return formatUnits(wei, etherUnits[unit]);
5060
+ }
5061
+
5062
+ // src/utils/unit/formatGwei.ts
5063
+ function formatGwei(wei, unit = "wei") {
5064
+ return formatUnits(wei, gweiUnits[unit]);
5065
+ }
5066
+
5067
+ // src/utils/unit/parseEther.ts
5068
+ function parseEther(ether, unit = "wei") {
5069
+ return parseUnits(ether, etherUnits[unit]);
2871
5070
  }
2872
5071
 
2873
5072
  export {
@@ -2881,6 +5080,7 @@ export {
2881
5080
  AbiErrorInputsNotFoundError,
2882
5081
  AbiErrorNotFoundError,
2883
5082
  AbiErrorSignatureNotFoundError,
5083
+ AbiEventSignatureNotFoundError,
2884
5084
  AbiEventNotFoundError,
2885
5085
  AbiFunctionNotFoundError,
2886
5086
  AbiFunctionOutputsNotFoundError,
@@ -2894,6 +5094,61 @@ export {
2894
5094
  ChainDoesNotSupportContract,
2895
5095
  multicall3Abi,
2896
5096
  panicReasons,
5097
+ etherUnits,
5098
+ gweiUnits,
5099
+ weiUnits,
5100
+ TransactionExecutionError,
5101
+ TransactionNotFoundError,
5102
+ TransactionReceiptNotFoundError,
5103
+ WaitForTransactionReceiptTimeoutError,
5104
+ CallExecutionError,
5105
+ ContractFunctionExecutionError,
5106
+ ContractFunctionRevertedError,
5107
+ ContractFunctionZeroDataError,
5108
+ RawContractError,
5109
+ SizeExceedsPaddingSizeError,
5110
+ DataLengthTooLongError,
5111
+ DataLengthTooShortError,
5112
+ InvalidBytesBooleanError,
5113
+ InvalidHexBooleanError,
5114
+ InvalidHexValueError,
5115
+ OffsetOutOfBoundsError,
5116
+ EstimateGasExecutionError,
5117
+ FilterTypeNotSupportedError,
5118
+ ExecutionRevertedError,
5119
+ FeeCapTooHighError,
5120
+ FeeCapTooLowError,
5121
+ NonceTooHighError,
5122
+ NonceTooLowError,
5123
+ NonceMaxValueError,
5124
+ InsufficientFundsError,
5125
+ IntrinsicGasTooHighError,
5126
+ IntrinsicGasTooLowError,
5127
+ TransactionTypeNotSupportedError,
5128
+ TipAboveFeeCapError,
5129
+ UnknownNodeError,
5130
+ RequestError,
5131
+ RpcRequestError,
5132
+ ParseRpcError,
5133
+ InvalidRequestRpcError,
5134
+ MethodNotFoundRpcError,
5135
+ InvalidParamsRpcError,
5136
+ InternalRpcError,
5137
+ InvalidInputRpcError,
5138
+ ResourceNotFoundRpcError,
5139
+ ResourceUnavailableRpcError,
5140
+ TransactionRejectedRpcError,
5141
+ MethodNotSupportedRpcError,
5142
+ LimitExceededRpcError,
5143
+ JsonRpcVersionUnsupportedError,
5144
+ UserRejectedRequestError,
5145
+ SwitchChainError,
5146
+ UnknownRpcError,
5147
+ HttpRequestError,
5148
+ WebSocketRequestError,
5149
+ RpcError,
5150
+ TimeoutError,
5151
+ UrlRequiredError,
2897
5152
  concat,
2898
5153
  isBytes,
2899
5154
  isHex,
@@ -2907,43 +5162,41 @@ export {
2907
5162
  sliceHex,
2908
5163
  boolToHex,
2909
5164
  bytesToHex,
2910
- encodeHex,
5165
+ toHex,
2911
5166
  numberToHex,
2912
5167
  stringToHex,
5168
+ toBytes,
2913
5169
  boolToBytes,
2914
- encodeBytes,
2915
5170
  hexToBytes,
2916
5171
  numberToBytes,
2917
5172
  stringToBytes,
2918
- encodeRlp,
2919
- decodeHex,
5173
+ toRlp,
5174
+ fromHex,
2920
5175
  hexToBigInt,
2921
5176
  hexToBool,
2922
5177
  hexToNumber,
2923
5178
  hexToString,
2924
- decodeBytes,
5179
+ fromBytes,
2925
5180
  bytesToBigint,
2926
5181
  bytesToBool,
2927
5182
  bytesToNumber,
2928
5183
  bytesToString,
2929
- decodeRlp,
5184
+ fromRlp,
2930
5185
  extractFunctionParts,
2931
5186
  extractFunctionName,
2932
5187
  extractFunctionParams,
2933
5188
  extractFunctionType,
2934
- getContractError,
2935
5189
  keccak256,
2936
- getEventSignature,
2937
- getFunctionSignature,
2938
- checksumAddress,
5190
+ getEventSelector,
5191
+ getFunctionSelector,
5192
+ isAddress,
2939
5193
  getAddress,
2940
- getContractAddress,
5194
+ getContractAddress2 as getContractAddress,
2941
5195
  getCreateAddress,
2942
5196
  getCreate2Address,
2943
- isAddress,
2944
5197
  isAddressEqual,
2945
- encodeAbi,
2946
- decodeAbi,
5198
+ encodeAbiParameters,
5199
+ decodeAbiParameters,
2947
5200
  formatAbiItem,
2948
5201
  decodeErrorResult,
2949
5202
  decodeEventLog,
@@ -2955,11 +5208,17 @@ export {
2955
5208
  encodeEventTopics,
2956
5209
  encodeFunctionData,
2957
5210
  encodeFunctionResult,
5211
+ arrayRegex,
5212
+ bytesRegex,
5213
+ integerRegex,
5214
+ encodePacked,
2958
5215
  formatAbiItemWithArgs,
2959
- getCache,
2960
- withCache,
2961
- wait,
2962
- isNonDeterministicError,
5216
+ parseAbi,
5217
+ parseAbiItem,
5218
+ parseAbiParameter,
5219
+ parseAbiParameters,
5220
+ getAccount,
5221
+ isDeterministicError,
2963
5222
  buildRequest,
2964
5223
  defineChain,
2965
5224
  format3 as format,
@@ -2970,59 +5229,98 @@ export {
2970
5229
  formatBlock,
2971
5230
  defineBlock,
2972
5231
  extract,
2973
- formatFeeHistory,
2974
- formatLog,
2975
- formatTransactionReceipt,
2976
5232
  defineTransactionReceipt,
2977
5233
  formatTransactionRequest,
2978
5234
  defineTransactionRequest,
5235
+ containsNodeError,
5236
+ getNodeError,
5237
+ getCallError,
5238
+ getContractError,
5239
+ getEstimateGasError,
5240
+ getTransactionError,
2979
5241
  stringify,
2980
5242
  getSocket,
2981
5243
  rpc,
2982
- etherUnits,
2983
- gweiUnits,
2984
- weiUnits,
2985
- formatUnit,
5244
+ assertRequest,
5245
+ call,
5246
+ simulateContract,
5247
+ createPendingTransactionFilter,
5248
+ createBlockFilter,
5249
+ createEventFilter,
5250
+ createContractEventFilter,
5251
+ estimateGas,
5252
+ estimateContractGas,
5253
+ getBalance,
5254
+ getBlock,
5255
+ getBlockNumberCache,
5256
+ getBlockNumber,
5257
+ getBlockTransactionCount,
5258
+ getBytecode,
5259
+ getChainId,
5260
+ getFeeHistory,
5261
+ getFilterChanges,
5262
+ getFilterLogs,
5263
+ getGasPrice,
5264
+ getLogs,
5265
+ getStorageAt,
5266
+ getTransaction,
5267
+ getTransactionConfirmations,
5268
+ getTransactionCount,
5269
+ getTransactionReceipt,
5270
+ readContract,
5271
+ multicall,
5272
+ uninstallFilter,
5273
+ waitForTransactionReceipt,
5274
+ watchBlockNumber,
5275
+ watchBlocks,
5276
+ watchContractEvent,
5277
+ watchEvent,
5278
+ watchPendingTransactions,
5279
+ dropTransaction,
5280
+ getAutomine,
5281
+ getTxpoolContent,
5282
+ getTxpoolStatus,
5283
+ impersonateAccount,
5284
+ increaseTime,
5285
+ inspectTxpool,
5286
+ mine,
5287
+ removeBlockTimestampInterval,
5288
+ reset,
5289
+ revert,
5290
+ sendUnsignedTransaction,
5291
+ setAutomine,
5292
+ setBalance,
5293
+ setBlockGasLimit,
5294
+ setBlockTimestampInterval,
5295
+ setCode,
5296
+ setCoinbase,
5297
+ setIntervalMining,
5298
+ setLoggingEnabled,
5299
+ setMinGasPrice,
5300
+ setNextBlockBaseFeePerGas,
5301
+ setNextBlockTimestamp,
5302
+ setNonce,
5303
+ setRpcUrl,
5304
+ setStorageAt,
5305
+ snapshot,
5306
+ stopImpersonatingAccount,
5307
+ addChain,
5308
+ deployContract,
5309
+ getAddresses,
5310
+ getPermissions,
5311
+ requestAddresses,
5312
+ requestPermissions,
5313
+ sendTransaction,
5314
+ signMessage,
5315
+ switchChain,
5316
+ watchAsset,
5317
+ writeContract,
5318
+ parseUnits,
5319
+ parseGwei,
5320
+ prepareRequest,
5321
+ formatUnits,
2986
5322
  formatEther,
2987
5323
  formatGwei,
2988
- parseUnit,
2989
- parseEther,
2990
- parseGwei,
2991
- ContractFunctionExecutionError,
2992
- ContractFunctionRevertedError,
2993
- ContractFunctionZeroDataError,
2994
- RawContractError,
2995
- SizeExceedsPaddingSizeError,
2996
- DataLengthTooLongError,
2997
- DataLengthTooShortError,
2998
- InvalidBytesBooleanError,
2999
- InvalidHexBooleanError,
3000
- InvalidHexValueError,
3001
- OffsetOutOfBoundsError,
3002
- FilterTypeNotSupportedError,
3003
- RequestError,
3004
- RpcRequestError,
3005
- ParseRpcError,
3006
- InvalidRequestRpcError,
3007
- MethodNotFoundRpcError,
3008
- InvalidParamsRpcError,
3009
- InternalRpcError,
3010
- InvalidInputRpcError,
3011
- ResourceNotFoundRpcError,
3012
- ResourceUnavailableRpcError,
3013
- TransactionRejectedRpcError,
3014
- MethodNotSupportedRpcError,
3015
- LimitExceededRpcError,
3016
- JsonRpcVersionUnsupportedError,
3017
- UnknownRpcError,
3018
- HttpRequestError,
3019
- WebSocketRequestError,
3020
- RpcError,
3021
- TimeoutError,
3022
- InvalidGasArgumentsError,
3023
- TransactionNotFoundError,
3024
- TransactionReceiptNotFoundError,
3025
- WaitForTransactionReceiptTimeoutError,
3026
- UrlRequiredError
5324
+ parseEther
3027
5325
  };
3028
- //# sourceMappingURL=chunk-RPR4ZSAP.mjs.map
5326
+ //# sourceMappingURL=chunk-HDZRBHNX.mjs.map