dequanto 0.0.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 (477) hide show
  1. package/.vscode/settings.json +11 -0
  2. package/actions/gen.act.ts +38 -0
  3. package/actions/tokens.act.ts +12 -0
  4. package/configs/dequanto.yml +51 -0
  5. package/contracts/abi/erc20.abi.json +222 -0
  6. package/contracts/gen/amm/AmmFactoryV2ContractBase.ts +66 -0
  7. package/contracts/gen/amm/AmmMasterChefV2ContractBase.ts +158 -0
  8. package/contracts/gen/amm/AmmPairContractV2Base.ts +158 -0
  9. package/contracts/gen/amm/AmmPairContractV3Base.ts +125 -0
  10. package/contracts/gen/amm/AmmRouterV2ContractBase.ts +124 -0
  11. package/contracts/gen/amm/AmmVaultV2ContractBase.ts +214 -0
  12. package/contracts/gen/base/ERC20Base.ts +90 -0
  13. package/contracts/gen/bsc/OneInchRouterV3Base.ts +57 -0
  14. package/contracts/gen/eth/WETHBase/WETHBase.sol +756 -0
  15. package/contracts/gen/eth/WETHBase.ts +136 -0
  16. package/contracts/gen/polygon/ERC20PolygonBase.ts +305 -0
  17. package/contracts/gen/polygon/WormholeBridgeContractBase/Address.sol +216 -0
  18. package/contracts/gen/polygon/WormholeBridgeContractBase/BeaconProxy.sol +61 -0
  19. package/contracts/gen/polygon/WormholeBridgeContractBase/Bridge.sol +437 -0
  20. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeGetters.sol +70 -0
  21. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeGovernance.sol +142 -0
  22. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeImplementation.sol +34 -0
  23. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeSetters.sol +57 -0
  24. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeState.sol +52 -0
  25. package/contracts/gen/polygon/WormholeBridgeContractBase/BridgeStructs.sol +66 -0
  26. package/contracts/gen/polygon/WormholeBridgeContractBase/BytesLib.sol +510 -0
  27. package/contracts/gen/polygon/WormholeBridgeContractBase/Context.sol +23 -0
  28. package/contracts/gen/polygon/WormholeBridgeContractBase/ERC1967Proxy.sol +32 -0
  29. package/contracts/gen/polygon/WormholeBridgeContractBase/ERC1967Upgrade.sol +193 -0
  30. package/contracts/gen/polygon/WormholeBridgeContractBase/IBeacon.sol +15 -0
  31. package/contracts/gen/polygon/WormholeBridgeContractBase/IERC20.sol +81 -0
  32. package/contracts/gen/polygon/WormholeBridgeContractBase/IWormhole.sol +42 -0
  33. package/contracts/gen/polygon/WormholeBridgeContractBase/Ownable.sol +71 -0
  34. package/contracts/gen/polygon/WormholeBridgeContractBase/Proxy.sol +85 -0
  35. package/contracts/gen/polygon/WormholeBridgeContractBase/SafeERC20.sol +98 -0
  36. package/contracts/gen/polygon/WormholeBridgeContractBase/StorageSlot.sol +83 -0
  37. package/contracts/gen/polygon/WormholeBridgeContractBase/Structs.sol +40 -0
  38. package/contracts/gen/polygon/WormholeBridgeContractBase/Token.sol +12 -0
  39. package/contracts/gen/polygon/WormholeBridgeContractBase/TokenBridge.sol +15 -0
  40. package/contracts/gen/polygon/WormholeBridgeContractBase/TokenImplementation.sol +177 -0
  41. package/contracts/gen/polygon/WormholeBridgeContractBase/TokenState.sol +31 -0
  42. package/contracts/gen/polygon/WormholeBridgeContractBase.ts +231 -0
  43. package/contracts/gen/xdai/WXDaiTokenContractBase.ts +136 -0
  44. package/data/cex/eth.csv +356 -0
  45. package/data/tokens/1inch.json +16557 -0
  46. package/data/tokens/arbitrum.json +1 -0
  47. package/data/tokens/sushi.json +56388 -0
  48. package/dist/contracts/gen/amm/AmmFactoryV2ContractBase.js +53 -0
  49. package/dist/contracts/gen/amm/AmmMasterChefV2ContractBase.js +122 -0
  50. package/dist/contracts/gen/amm/AmmPairContractV2Base.js +122 -0
  51. package/dist/contracts/gen/amm/AmmPairContractV3Base.js +98 -0
  52. package/dist/contracts/gen/amm/AmmRouterV2ContractBase.js +95 -0
  53. package/dist/contracts/gen/amm/AmmVaultV2ContractBase.js +164 -0
  54. package/dist/contracts/gen/base/ERC20Base.js +64 -0
  55. package/dist/contracts/gen/bsc/OneInchRouterV3Base.js +47 -0
  56. package/dist/contracts/gen/eth/WETHBase.js +96 -0
  57. package/dist/contracts/gen/polygon/ERC20PolygonBase.js +233 -0
  58. package/dist/contracts/gen/polygon/WormholeBridgeContractBase.js +172 -0
  59. package/dist/contracts/gen/xdai/WXDaiTokenContractBase.js +96 -0
  60. package/dist/src/BlockchainExplorer/BlockChainExplorerFactory.js +227 -0
  61. package/dist/src/BlockchainExplorer/BlockChainExplorerProvider.js +32 -0
  62. package/dist/src/BlockchainExplorer/BlockNumberCache.js +33 -0
  63. package/dist/src/BlockchainExplorer/Bscscan.js +27 -0
  64. package/dist/src/BlockchainExplorer/Etherscan.js +27 -0
  65. package/dist/src/BlockchainExplorer/IAbiProvider.js +2 -0
  66. package/dist/src/BlockchainExplorer/IBlockChainExplorer.js +2 -0
  67. package/dist/src/BlockchainExplorer/Polyscan.js +27 -0
  68. package/dist/src/ChainAccounts.js +69 -0
  69. package/dist/src/ChainAccountsService.js +75 -0
  70. package/dist/src/Config.js +7 -0
  71. package/dist/src/blocks/BlockDateResolver.js +125 -0
  72. package/dist/src/bridges/BridgeFactory.js +19 -0
  73. package/dist/src/bridges/hop/HopAddresses.js +520 -0
  74. package/dist/src/bridges/hop/HopBridge.js +327 -0
  75. package/dist/src/bridges/hop/contracts/gen.act.js +43 -0
  76. package/dist/src/bridges/hop/contracts/polygon/Dai_l2AmmWrapperContract.js +52 -0
  77. package/dist/src/bridges/hop/contracts/polygon/Dai_l2BridgeContract.js +319 -0
  78. package/dist/src/bridges/hop/contracts/polygon/Dai_l2SaddleSwapContract.js +178 -0
  79. package/dist/src/bridges/hop/contracts/polygon/Eth_l2AmmWrapperContract.js +52 -0
  80. package/dist/src/bridges/hop/contracts/polygon/Eth_l2BridgeContract.js +319 -0
  81. package/dist/src/bridges/hop/contracts/polygon/Eth_l2SaddleSwapContract.js +178 -0
  82. package/dist/src/bridges/hop/contracts/polygon/Matic_l2AmmWrapperContract.js +52 -0
  83. package/dist/src/bridges/hop/contracts/polygon/Matic_l2BridgeContract.js +319 -0
  84. package/dist/src/bridges/hop/contracts/polygon/Matic_l2SaddleSwapContract.js +178 -0
  85. package/dist/src/bridges/hop/contracts/polygon/Usdc_l2AmmWrapperContract.js +52 -0
  86. package/dist/src/bridges/hop/contracts/polygon/Usdc_l2BridgeContract.js +319 -0
  87. package/dist/src/bridges/hop/contracts/polygon/Usdc_l2SaddleSwapContract.js +178 -0
  88. package/dist/src/bridges/hop/contracts/polygon/Usdt_l2AmmWrapperContract.js +52 -0
  89. package/dist/src/bridges/hop/contracts/polygon/Usdt_l2BridgeContract.js +319 -0
  90. package/dist/src/bridges/hop/contracts/polygon/Usdt_l2SaddleSwapContract.js +178 -0
  91. package/dist/src/bridges/hop/contracts/polygon/Wbtc_l2AmmWrapperContract.js +52 -0
  92. package/dist/src/bridges/hop/contracts/polygon/Wbtc_l2BridgeContract.js +319 -0
  93. package/dist/src/bridges/hop/contracts/polygon/Wbtc_l2SaddleSwapContract.js +178 -0
  94. package/dist/src/bridges/models/IBridge.js +2 -0
  95. package/dist/src/bridges/wormhole/contracts/WormholeBridgeContract.js +15 -0
  96. package/dist/src/chains/PlatformFactory.js +42 -0
  97. package/dist/src/chains/arbitrum/ArbTokenProvider.js +40 -0
  98. package/dist/src/chains/arbitrum/ArbWeb3Client.js +39 -0
  99. package/dist/src/chains/arbitrum/Arbiscan.js +27 -0
  100. package/dist/src/chains/boba/BobaWeb3Client.js +47 -0
  101. package/dist/src/chains/boba/Bobascan.js +28 -0
  102. package/dist/src/chains/xdai/XDaiWeb3Client.js +87 -0
  103. package/dist/src/chains/xdai/XDaiscan.js +27 -0
  104. package/dist/src/chains/xdai/tokens/WXDaiTokenContract.js +15 -0
  105. package/dist/src/clients/BscWeb3Client.js +38 -0
  106. package/dist/src/clients/ClientEventsStream.js +34 -0
  107. package/dist/src/clients/ClientPool.js +560 -0
  108. package/dist/src/clients/ClientPoolStats.js +52 -0
  109. package/dist/src/clients/EthWeb3Client.js +35 -0
  110. package/dist/src/clients/HardhatWeb3Client.js +56 -0
  111. package/dist/src/clients/PolyWeb3Client.js +77 -0
  112. package/dist/src/clients/Web3Client.js +186 -0
  113. package/dist/src/clients/Web3ClientFactory.js +32 -0
  114. package/dist/src/clients/interfaces/IWeb3Client.js +2 -0
  115. package/dist/src/clients/interfaces/IWeb3ClientStatus.js +2 -0
  116. package/dist/src/clients/interfaces/IWeb3EndpointOptions.js +2 -0
  117. package/dist/src/clients/model/ClientStatus.js +9 -0
  118. package/dist/src/clients/model/PromiEventWrap.js +52 -0
  119. package/dist/src/clients/model/SubscriptionWrap.js +42 -0
  120. package/dist/src/clients/utils/ClientEndpoints.js +27 -0
  121. package/dist/src/clients/utils/ClientErrorUtil.js +30 -0
  122. package/dist/src/clients/utils/TxFactory.js +14 -0
  123. package/dist/src/contracts/BscContract.js +30 -0
  124. package/dist/src/contracts/Contract.js +90 -0
  125. package/dist/src/contracts/ContractBase.js +139 -0
  126. package/dist/src/contracts/ContractFactory.js +17 -0
  127. package/dist/src/contracts/ContractProvider.js +40 -0
  128. package/dist/src/contracts/ContractReader.js +76 -0
  129. package/dist/src/contracts/ContractStream.js +20 -0
  130. package/dist/src/contracts/ContractWriter.js +62 -0
  131. package/dist/src/contracts/EthContract.js +31 -0
  132. package/dist/src/contracts/TxContract.js +37 -0
  133. package/dist/src/contracts/common/ERC20.js +14 -0
  134. package/dist/src/contracts/common/ERC20Polygon.js +14 -0
  135. package/dist/src/contracts/common/PoolPair.js +23 -0
  136. package/dist/src/contracts/utils/AbiDeserializer.js +89 -0
  137. package/dist/src/contracts/utils/ConvertUtils.js +21 -0
  138. package/dist/src/contracts/utils/InputDataUtils.js +87 -0
  139. package/dist/src/contracts/utils/TypeUtils.js +24 -0
  140. package/dist/src/defi/OneInch/OneInchRouter.js +14 -0
  141. package/dist/src/env/BigIntSerializer.js +19 -0
  142. package/dist/src/gen/Ast.js +12 -0
  143. package/dist/src/gen/ContractTemplate.js +27 -0
  144. package/dist/src/gen/Generator.js +180 -0
  145. package/dist/src/gen/GeneratorFromAbi.js +361 -0
  146. package/dist/src/handlers/TokenHandler.js +69 -0
  147. package/dist/src/indexer/BlocksTxIndexer.js +52 -0
  148. package/dist/src/indexer/PendingTxIndexer.js +96 -0
  149. package/dist/src/indexer/handlers/BlocksWalker.js +306 -0
  150. package/dist/src/indexer/handlers/TxQueueLoader.js +117 -0
  151. package/dist/src/json/JsonArrayStore.js +296 -0
  152. package/dist/src/json/JsonObjectStore.js +214 -0
  153. package/dist/src/json/JsonStore.spec.js +83 -0
  154. package/dist/src/loggers/ILogger.js +2 -0
  155. package/dist/src/loggers/LoggerService.js +34 -0
  156. package/dist/src/loggers/TxLoggerService.js +122 -0
  157. package/dist/src/models/IContractDetails.js +2 -0
  158. package/dist/src/models/IToken.js +2 -0
  159. package/dist/src/models/ITokenGlob.js +6 -0
  160. package/dist/src/models/ITransactionDetails.js +2 -0
  161. package/dist/src/models/TAddress.js +2 -0
  162. package/dist/src/models/TBufferLike.js +2 -0
  163. package/dist/src/models/THex.js +2 -0
  164. package/dist/src/models/TPlatform.js +2 -0
  165. package/dist/src/models/TResult.js +2 -0
  166. package/dist/src/ns/NameService.js +19 -0
  167. package/dist/src/ns/providers/EnsProvider.js +41 -0
  168. package/dist/src/ns/providers/INsProvider.js +2 -0
  169. package/dist/src/ns/providers/UDProvider.js +39 -0
  170. package/dist/src/ns/utils/$ns.js +17 -0
  171. package/dist/src/structs/PackedRanges.js +186 -0
  172. package/dist/src/structs/PackedRanges.spec.js +30 -0
  173. package/dist/src/tokens/TokenExchangeService.js +110 -0
  174. package/dist/src/tokens/TokenExchanges/AmmBase/AmmUtilts.js +17 -0
  175. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmFactoryV2Contract.js +15 -0
  176. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmMasterChefV2Contract.js +15 -0
  177. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmPairV2Contract.js +16 -0
  178. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmPairV2Service.js +144 -0
  179. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmRouterV2Contract.js +15 -0
  180. package/dist/src/tokens/TokenExchanges/AmmBase/V2/AmmVaultV2Contract.js +15 -0
  181. package/dist/src/tokens/TokenExchanges/AmmBase/V3/AmmPairV3Contract.js +22 -0
  182. package/dist/src/tokens/TokenExchanges/AmmV2ExchangeBase.js +194 -0
  183. package/dist/src/tokens/TokenExchanges/OneInchExchange.js +92 -0
  184. package/dist/src/tokens/TokenExchanges/PancakeswapExchange.js +28 -0
  185. package/dist/src/tokens/TokenExchanges/SushiswapPolygonExchange.js +28 -0
  186. package/dist/src/tokens/TokenExchanges/UniswapExchange.js +28 -0
  187. package/dist/src/tokens/TokenOracles/AmmPriceV2Oracle.js +319 -0
  188. package/dist/src/tokens/TokenOracles/TokenPriceStore.js +108 -0
  189. package/dist/src/tokens/TokenPriceService.js +196 -0
  190. package/dist/src/tokens/TokenPriceServiceProvider.js +31 -0
  191. package/dist/src/tokens/TokenProviders/ATokenProvider.js +38 -0
  192. package/dist/src/tokens/TokenProviders/ITokenProvider.js +2 -0
  193. package/dist/src/tokens/TokenProviders/TPChain.js +35 -0
  194. package/dist/src/tokens/TokenProviders/TPCoinmarketcap.js +63 -0
  195. package/dist/src/tokens/TokenProviders/TPOneInch.js +65 -0
  196. package/dist/src/tokens/TokenProviders/TPSushiswap.js +89 -0
  197. package/dist/src/tokens/TokenProviders/TPUniswap.js +84 -0
  198. package/dist/src/tokens/TokenService.js +115 -0
  199. package/dist/src/tokens/TokenSwapService.js +37 -0
  200. package/dist/src/tokens/TokenTransferService.js +189 -0
  201. package/dist/src/tokens/TokensService.js +236 -0
  202. package/dist/src/tokens/TokensServiceBsc.js +18 -0
  203. package/dist/src/tokens/TokensServiceEth.js +15 -0
  204. package/dist/src/tokens/TokensServiceFactory.js +29 -0
  205. package/dist/src/tokens/TokensServicePolygon.js +18 -0
  206. package/dist/src/tokens/TokensServiceXDai.js +24 -0
  207. package/dist/src/tokens/defi/ISwapService.js +2 -0
  208. package/dist/src/tokens/defi/paraswap/Paraswap.js +135 -0
  209. package/dist/src/tokens/erc20/eth/WETH.js +14 -0
  210. package/dist/src/tokens/utils/TokenUtils.js +66 -0
  211. package/dist/src/txs/ITxConfig.js +2 -0
  212. package/dist/src/txs/TxDataBuilder.js +159 -0
  213. package/dist/src/txs/TxLogger.js +119 -0
  214. package/dist/src/txs/TxProvider.js +73 -0
  215. package/dist/src/txs/TxService.js +19 -0
  216. package/dist/src/txs/TxWriter.js +287 -0
  217. package/dist/src/txs/conditional/GasWatcherLogger.js +61 -0
  218. package/dist/src/txs/conditional/GasWatcherService.js +103 -0
  219. package/dist/src/txs/conditional/GasWatcherStore.js +25 -0
  220. package/dist/src/txs/conditional/GasWatcherTx.js +126 -0
  221. package/dist/src/txs/receipt/ITxLogItem.js +2 -0
  222. package/dist/src/txs/receipt/TxLogParser.js +27 -0
  223. package/dist/src/txs/receipt/TxLogsTransfer.js +50 -0
  224. package/dist/src/txs/receipt/TxTopicInMemoryProvider.js +41 -0
  225. package/dist/src/txs/receipt/TxTopicProvider.js +25 -0
  226. package/dist/src/utils/$abiParser.js +159 -0
  227. package/dist/src/utils/$abiType.js +77 -0
  228. package/dist/src/utils/$abiUtils.js +43 -0
  229. package/dist/src/utils/$address.js +41 -0
  230. package/dist/src/utils/$array.js +60 -0
  231. package/dist/src/utils/$bigint.js +130 -0
  232. package/dist/src/utils/$block.js +10 -0
  233. package/dist/src/utils/$class.js +13 -0
  234. package/dist/src/utils/$config.js +18 -0
  235. package/dist/src/utils/$contract.js +67 -0
  236. package/dist/src/utils/$csv.js +79 -0
  237. package/dist/src/utils/$date.js +496 -0
  238. package/dist/src/utils/$fn.js +117 -0
  239. package/dist/src/utils/$is.js +40 -0
  240. package/dist/src/utils/$logger.js +15 -0
  241. package/dist/src/utils/$number.js +95 -0
  242. package/dist/src/utils/$object.js +82 -0
  243. package/dist/src/utils/$path.js +33 -0
  244. package/dist/src/utils/$promise.js +13 -0
  245. package/dist/src/utils/$require.js +127 -0
  246. package/dist/src/utils/$sign.js +35 -0
  247. package/dist/src/utils/$signSerializer.js +264 -0
  248. package/dist/src/utils/$wallet.js +13 -0
  249. package/dist/src/utils/types.js +2 -0
  250. package/dist/src/wallets/Wallet.js +26 -0
  251. package/dist/src/wallets/WalletBsc.js +17 -0
  252. package/dist/src/wallets/WalletService.js +35 -0
  253. package/dist/src/www/utils/BlockChainExplorerFormatter.js +15 -0
  254. package/hardhat.config.js +6 -0
  255. package/package.json +52 -0
  256. package/readme.md +76 -0
  257. package/src/BlockchainExplorer/BlockChainExplorerFactory.ts +273 -0
  258. package/src/BlockchainExplorer/BlockChainExplorerProvider.ts +26 -0
  259. package/src/BlockchainExplorer/BlockNumberCache.ts +46 -0
  260. package/src/BlockchainExplorer/Bscscan.ts +23 -0
  261. package/src/BlockchainExplorer/Etherscan.ts +25 -0
  262. package/src/BlockchainExplorer/IAbiProvider.ts +5 -0
  263. package/src/BlockchainExplorer/IBlockChainExplorer.ts +37 -0
  264. package/src/BlockchainExplorer/Polyscan.ts +23 -0
  265. package/src/ChainAccounts.ts +72 -0
  266. package/src/ChainAccountsService.ts +74 -0
  267. package/src/Config.ts +34 -0
  268. package/src/blocks/BlockDateResolver.ts +149 -0
  269. package/src/bridges/BridgeFactory.ts +16 -0
  270. package/src/bridges/hop/HopAddresses.ts +518 -0
  271. package/src/bridges/hop/HopBridge.ts +430 -0
  272. package/src/bridges/hop/contracts/gen.act.ts +50 -0
  273. package/src/bridges/hop/contracts/polygon/Dai_l2AmmWrapperContract.ts +69 -0
  274. package/src/bridges/hop/contracts/polygon/Dai_l2BridgeContract.ts +453 -0
  275. package/src/bridges/hop/contracts/polygon/Dai_l2SaddleSwapContract.ts +264 -0
  276. package/src/bridges/hop/contracts/polygon/Eth_l2AmmWrapperContract.ts +69 -0
  277. package/src/bridges/hop/contracts/polygon/Eth_l2BridgeContract.ts +453 -0
  278. package/src/bridges/hop/contracts/polygon/Eth_l2SaddleSwapContract.ts +264 -0
  279. package/src/bridges/hop/contracts/polygon/Matic_l2AmmWrapperContract.ts +69 -0
  280. package/src/bridges/hop/contracts/polygon/Matic_l2BridgeContract.ts +453 -0
  281. package/src/bridges/hop/contracts/polygon/Matic_l2SaddleSwapContract.ts +264 -0
  282. package/src/bridges/hop/contracts/polygon/Usdc_l2AmmWrapperContract.ts +69 -0
  283. package/src/bridges/hop/contracts/polygon/Usdc_l2BridgeContract.ts +453 -0
  284. package/src/bridges/hop/contracts/polygon/Usdc_l2SaddleSwapContract.ts +264 -0
  285. package/src/bridges/hop/contracts/polygon/Usdt_l2AmmWrapperContract.ts +69 -0
  286. package/src/bridges/hop/contracts/polygon/Usdt_l2BridgeContract.ts +453 -0
  287. package/src/bridges/hop/contracts/polygon/Usdt_l2SaddleSwapContract.ts +264 -0
  288. package/src/bridges/hop/contracts/polygon/Wbtc_l2AmmWrapperContract.ts +69 -0
  289. package/src/bridges/hop/contracts/polygon/Wbtc_l2BridgeContract.ts +453 -0
  290. package/src/bridges/hop/contracts/polygon/Wbtc_l2SaddleSwapContract.ts +264 -0
  291. package/src/bridges/models/IBridge.ts +43 -0
  292. package/src/bridges/wormhole/contracts/WormholeBridgeContract.ts +14 -0
  293. package/src/chains/PlatformFactory.ts +45 -0
  294. package/src/chains/arbitrum/ArbTokenProvider.ts +39 -0
  295. package/src/chains/arbitrum/ArbWeb3Client.ts +39 -0
  296. package/src/chains/arbitrum/Arbiscan.ts +24 -0
  297. package/src/chains/boba/BobaWeb3Client.ts +49 -0
  298. package/src/chains/boba/Bobascan.ts +25 -0
  299. package/src/chains/xdai/XDaiWeb3Client.ts +82 -0
  300. package/src/chains/xdai/XDaiscan.ts +24 -0
  301. package/src/chains/xdai/tokens/WXDaiTokenContract.json +279 -0
  302. package/src/chains/xdai/tokens/WXDaiTokenContract.ts +14 -0
  303. package/src/clients/BscWeb3Client.ts +38 -0
  304. package/src/clients/ClientEventsStream.ts +33 -0
  305. package/src/clients/ClientPool.ts +673 -0
  306. package/src/clients/ClientPoolStats.ts +64 -0
  307. package/src/clients/EthWeb3Client.ts +36 -0
  308. package/src/clients/HardhatWeb3Client.ts +60 -0
  309. package/src/clients/PolyWeb3Client.ts +91 -0
  310. package/src/clients/Web3Client.ts +228 -0
  311. package/src/clients/Web3ClientFactory.ts +28 -0
  312. package/src/clients/interfaces/IWeb3Client.ts +14 -0
  313. package/src/clients/interfaces/IWeb3ClientStatus.ts +23 -0
  314. package/src/clients/interfaces/IWeb3EndpointOptions.ts +9 -0
  315. package/src/clients/model/ClientStatus.ts +5 -0
  316. package/src/clients/model/PromiEventWrap.ts +61 -0
  317. package/src/clients/model/SubscriptionWrap.ts +53 -0
  318. package/src/clients/utils/ClientEndpoints.ts +26 -0
  319. package/src/clients/utils/ClientErrorUtil.ts +26 -0
  320. package/src/clients/utils/TxFactory.ts +17 -0
  321. package/src/contracts/BscContract.ts +28 -0
  322. package/src/contracts/Contract.ts +126 -0
  323. package/src/contracts/ContractBase.ts +158 -0
  324. package/src/contracts/ContractFactory.ts +19 -0
  325. package/src/contracts/ContractProvider.ts +55 -0
  326. package/src/contracts/ContractReader.ts +87 -0
  327. package/src/contracts/ContractStream.ts +18 -0
  328. package/src/contracts/ContractWriter.ts +97 -0
  329. package/src/contracts/EthContract.ts +29 -0
  330. package/src/contracts/TxContract.ts +43 -0
  331. package/src/contracts/common/ERC20.ts +13 -0
  332. package/src/contracts/common/ERC20Polygon.ts +13 -0
  333. package/src/contracts/common/PoolPair.ts +22 -0
  334. package/src/contracts/utils/AbiDeserializer.ts +98 -0
  335. package/src/contracts/utils/ConvertUtils.ts +16 -0
  336. package/src/contracts/utils/InputDataUtils.ts +93 -0
  337. package/src/contracts/utils/TypeUtils.ts +21 -0
  338. package/src/defi/OneInch/OneInchRouter.ts +13 -0
  339. package/src/env/BigIntSerializer.ts +18 -0
  340. package/src/gen/Ast.ts +12 -0
  341. package/src/gen/ContractTemplate.ts +36 -0
  342. package/src/gen/Generator.ts +227 -0
  343. package/src/gen/GeneratorFromAbi.ts +402 -0
  344. package/src/handlers/TokenHandler.ts +78 -0
  345. package/src/indexer/BlocksTxIndexer.ts +69 -0
  346. package/src/indexer/PendingTxIndexer.ts +124 -0
  347. package/src/indexer/handlers/BlocksWalker.ts +390 -0
  348. package/src/indexer/handlers/TxQueueLoader.ts +143 -0
  349. package/src/json/JsonArrayStore.ts +310 -0
  350. package/src/json/JsonObjectStore.ts +239 -0
  351. package/src/json/JsonStore.spec.ts +98 -0
  352. package/src/loggers/ILogger.ts +3 -0
  353. package/src/loggers/LoggerService.ts +39 -0
  354. package/src/loggers/TxLoggerService.ts +146 -0
  355. package/src/models/IContractDetails.ts +8 -0
  356. package/src/models/IToken.ts +11 -0
  357. package/src/models/ITokenGlob.ts +14 -0
  358. package/src/models/ITransactionDetails.ts +11 -0
  359. package/src/models/TAddress.ts +1 -0
  360. package/src/models/TBufferLike.ts +2 -0
  361. package/src/models/THex.ts +1 -0
  362. package/src/models/TPlatform.ts +1 -0
  363. package/src/models/TResult.ts +6 -0
  364. package/src/ns/NameService.ts +21 -0
  365. package/src/ns/providers/EnsProvider.ts +45 -0
  366. package/src/ns/providers/INsProvider.ts +6 -0
  367. package/src/ns/providers/UDProvider.ts +49 -0
  368. package/src/ns/utils/$ns.ts +15 -0
  369. package/src/structs/PackedRanges.spec.ts +38 -0
  370. package/src/structs/PackedRanges.ts +207 -0
  371. package/src/tokens/TokenExchangeService.ts +126 -0
  372. package/src/tokens/TokenExchanges/AmmBase/AmmUtilts.ts +16 -0
  373. package/src/tokens/TokenExchanges/AmmBase/V2/AmmFactoryV2Contract.ts +15 -0
  374. package/src/tokens/TokenExchanges/AmmBase/V2/AmmMasterChefV2Contract.ts +15 -0
  375. package/src/tokens/TokenExchanges/AmmBase/V2/AmmPairV2Contract.ts +17 -0
  376. package/src/tokens/TokenExchanges/AmmBase/V2/AmmPairV2Service.ts +208 -0
  377. package/src/tokens/TokenExchanges/AmmBase/V2/AmmRouterV2Contract.ts +15 -0
  378. package/src/tokens/TokenExchanges/AmmBase/V2/AmmVaultV2Contract.ts +15 -0
  379. package/src/tokens/TokenExchanges/AmmBase/V3/AmmPairV3Contract.ts +24 -0
  380. package/src/tokens/TokenExchanges/AmmV2ExchangeBase.ts +242 -0
  381. package/src/tokens/TokenExchanges/OneInchExchange.ts +111 -0
  382. package/src/tokens/TokenExchanges/PancakeswapExchange.ts +30 -0
  383. package/src/tokens/TokenExchanges/SushiswapPolygonExchange.ts +30 -0
  384. package/src/tokens/TokenExchanges/UniswapExchange.ts +31 -0
  385. package/src/tokens/TokenOracles/AmmPriceV2Oracle.ts +440 -0
  386. package/src/tokens/TokenOracles/TokenPriceStore.ts +129 -0
  387. package/src/tokens/TokenPriceService.ts +276 -0
  388. package/src/tokens/TokenPriceServiceProvider.ts +36 -0
  389. package/src/tokens/TokenProviders/ATokenProvider.ts +42 -0
  390. package/src/tokens/TokenProviders/ITokenProvider.ts +9 -0
  391. package/src/tokens/TokenProviders/TPChain.ts +41 -0
  392. package/src/tokens/TokenProviders/TPCoinmarketcap.ts +82 -0
  393. package/src/tokens/TokenProviders/TPOneInch.ts +71 -0
  394. package/src/tokens/TokenProviders/TPSushiswap.ts +96 -0
  395. package/src/tokens/TokenProviders/TPUniswap.ts +85 -0
  396. package/src/tokens/TokenService.ts +128 -0
  397. package/src/tokens/TokenSwapService.ts +47 -0
  398. package/src/tokens/TokenTransferService.ts +216 -0
  399. package/src/tokens/TokensService.ts +252 -0
  400. package/src/tokens/TokensServiceBsc.ts +17 -0
  401. package/src/tokens/TokensServiceEth.ts +9 -0
  402. package/src/tokens/TokensServiceFactory.ts +24 -0
  403. package/src/tokens/TokensServicePolygon.ts +17 -0
  404. package/src/tokens/TokensServiceXDai.ts +26 -0
  405. package/src/tokens/defi/ISwapService.ts +12 -0
  406. package/src/tokens/defi/paraswap/Paraswap.ts +244 -0
  407. package/src/tokens/erc20/eth/WETH.ts +13 -0
  408. package/src/tokens/utils/TokenUtils.ts +63 -0
  409. package/src/txs/ITxConfig.ts +27 -0
  410. package/src/txs/TxDataBuilder.ts +207 -0
  411. package/src/txs/TxLogger.ts +121 -0
  412. package/src/txs/TxProvider.ts +68 -0
  413. package/src/txs/TxService.ts +19 -0
  414. package/src/txs/TxWriter.ts +370 -0
  415. package/src/txs/conditional/GasWatcherLogger.ts +57 -0
  416. package/src/txs/conditional/GasWatcherService.ts +117 -0
  417. package/src/txs/conditional/GasWatcherStore.ts +40 -0
  418. package/src/txs/conditional/GasWatcherTx.ts +143 -0
  419. package/src/txs/receipt/ITxLogItem.ts +25 -0
  420. package/src/txs/receipt/TxLogParser.ts +29 -0
  421. package/src/txs/receipt/TxLogsTransfer.ts +61 -0
  422. package/src/txs/receipt/TxTopicInMemoryProvider.ts +45 -0
  423. package/src/txs/receipt/TxTopicProvider.ts +29 -0
  424. package/src/utils/$abiParser.ts +179 -0
  425. package/src/utils/$abiType.ts +85 -0
  426. package/src/utils/$abiUtils.ts +38 -0
  427. package/src/utils/$address.ts +37 -0
  428. package/src/utils/$array.ts +57 -0
  429. package/src/utils/$bigint.ts +127 -0
  430. package/src/utils/$block.ts +7 -0
  431. package/src/utils/$class.ts +8 -0
  432. package/src/utils/$config.ts +17 -0
  433. package/src/utils/$contract.ts +67 -0
  434. package/src/utils/$csv.ts +54 -0
  435. package/src/utils/$date.ts +473 -0
  436. package/src/utils/$fn.ts +134 -0
  437. package/src/utils/$is.ts +37 -0
  438. package/src/utils/$logger.ts +10 -0
  439. package/src/utils/$number.ts +89 -0
  440. package/src/utils/$object.ts +95 -0
  441. package/src/utils/$path.ts +32 -0
  442. package/src/utils/$promise.ts +7 -0
  443. package/src/utils/$require.ts +118 -0
  444. package/src/utils/$sign.ts +36 -0
  445. package/src/utils/$signSerializer.ts +339 -0
  446. package/src/utils/$wallet.ts +10 -0
  447. package/src/utils/types.ts +29 -0
  448. package/src/wallets/Wallet.ts +33 -0
  449. package/src/wallets/WalletBsc.ts +13 -0
  450. package/src/wallets/WalletService.ts +43 -0
  451. package/src/www/utils/BlockChainExplorerFormatter.ts +13 -0
  452. package/test/ChainAccount.spec.ts +9 -0
  453. package/test/client.spec.ts +59 -0
  454. package/test/fixtures/DaiTokenContract.ts +13 -0
  455. package/test/fixtures/receipts/swap.json +94 -0
  456. package/test/generate/class.spec.ts +27 -0
  457. package/test/hardhat/TestNode.ts +61 -0
  458. package/test/ns.spec.ts +30 -0
  459. package/test/receipt.spec.ts +27 -0
  460. package/test/utils/abi-parser.spec.ts +117 -0
  461. package/test/utils/bigint.spec.ts +40 -0
  462. package/test/utils/date.spec.ts +8 -0
  463. package/test/utils/fn.spec.ts +39 -0
  464. package/test/utils/number.spec.ts +41 -0
  465. package/test/utils/sign.spec.ts +22 -0
  466. package/tsconfig-build.json +24 -0
  467. package/tsconfig-src.json +36 -0
  468. package/tsconfig.json +27 -0
  469. package/typings/globals/assertion/index.d.ts +159 -0
  470. package/typings/globals/assertion/typings.json +10 -0
  471. package/typings/globals/atma-utest/index.d.ts +53 -0
  472. package/typings/globals/atma-utest/typings.json +10 -0
  473. package/typings/globals/axios/index.d.ts +6 -0
  474. package/typings/globals/mask/index.d.ts +6 -0
  475. package/typings/globals/mask/typings.json +9 -0
  476. package/typings/index.d.ts +6 -0
  477. package/typings.json +6 -0
@@ -0,0 +1,85 @@
1
+ import axios from 'axios'
2
+ import { JsonArrayStore } from '@dequanto/json/JsonArrayStore';
3
+ import { ITokenProvider } from './ITokenProvider';
4
+ import { ATokenProvider } from './ATokenProvider';
5
+ import { ITokenGlob } from '@dequanto/models/ITokenGlob';
6
+ import { $path } from '@dequanto/utils/$path';
7
+
8
+
9
+ const TheGraphUrl = 'https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v2';
10
+
11
+ export class TPUniswap extends ATokenProvider implements ITokenProvider {
12
+ store = new JsonArrayStore<ITokenGlob> ({
13
+ path: $path.resolve('/data/tokens/uni.json'),
14
+ key: x => x.symbol
15
+ });
16
+
17
+ getTokens(): Promise<ITokenGlob[]> {
18
+ return this.store.getAll();
19
+ }
20
+
21
+ /** Finds remote */
22
+ async find (address: string) {
23
+ let body = {
24
+ query: `
25
+ {
26
+ tokens (where: {id: "${address}"}) {
27
+ id
28
+ symbol
29
+ name
30
+ decimals
31
+ }
32
+ }
33
+ `
34
+ };
35
+ let resp = await axios.post(TheGraphUrl, body);
36
+ return resp.data.data?.tokens[0];
37
+ }
38
+
39
+ async redownloadTokens () {
40
+ let skip = 0;
41
+ let take = 1000;
42
+ let out = [] as ITokenGlob[];
43
+ while (true) {
44
+ let body = {
45
+ query: `
46
+ {
47
+ tokens (skip: ${skip} first:${take}) {
48
+ id
49
+ symbol
50
+ name
51
+ decimals
52
+ }
53
+ }
54
+ `
55
+ };
56
+
57
+ let resp = await axios.post(TheGraphUrl, body);
58
+ console.log(resp);
59
+ let tokens = resp.data.data?.tokens ?? [];
60
+
61
+ let arr = tokens.map(uniT => {
62
+ return <ITokenGlob> {
63
+ symbol: uniT.symbol,
64
+ name: uniT.name,
65
+ decimals: Number(uniT.decimals) || 18,
66
+ platforms: [
67
+ {
68
+ platform: 'eth',
69
+ address: uniT.id,
70
+ decimals: uniT.decimals,
71
+ }
72
+ ]
73
+ };
74
+ })
75
+ out = out.concat(...arr);
76
+ if (tokens.length < take) {
77
+ break;
78
+ }
79
+ skip += take;
80
+ }
81
+
82
+ await this.store.saveAll(out);
83
+ return out;
84
+ }
85
+ }
@@ -0,0 +1,128 @@
1
+ import di from 'a-di';
2
+ import { ChainAccount } from '@dequanto/ChainAccounts';
3
+ import { WXDaiTokenContract } from '@dequanto/chains/xdai/tokens/WXDaiTokenContract';
4
+ import { Web3Client } from '@dequanto/clients/Web3Client';
5
+ import { IToken } from '@dequanto/models/IToken';
6
+ import { TAddress } from '@dequanto/models/TAddress';
7
+ import { TxWriter } from '@dequanto/txs/TxWriter';
8
+ import { $bigint } from '@dequanto/utils/$bigint';
9
+ import { TokensServiceFactory } from './TokensServiceFactory';
10
+ import { $require } from '@dequanto/utils/$require';
11
+
12
+
13
+ export class TokenService {
14
+
15
+ private tokensProvider = TokensServiceFactory.get(this.client.platform);
16
+
17
+ constructor(public client: Web3Client) {
18
+
19
+ }
20
+
21
+ async balanceOf(address: TAddress, token: string | IToken): Promise<bigint> {
22
+ token = await this.getToken(token);
23
+ let isNative = this.tokensProvider.isNative(token.address);
24
+ if (isNative) {
25
+ return this.client.getBalance(address);
26
+ }
27
+ let erc20 = await this.tokensProvider.erc20(token);
28
+ let balance = await erc20.balanceOf(address);
29
+ return balance;
30
+ }
31
+ async hasToken(address: TAddress, token: string | IToken, amount: number): Promise<boolean> {
32
+ let t = await this.getToken(token);
33
+ let balance = await this.balanceOf(address, t);
34
+ let wei = $bigint.toWei(amount, t.decimals);
35
+ return wei <= balance;
36
+ }
37
+
38
+ async ensureApproved (account: ChainAccount, tokenMix: string | IToken, spender: TAddress, amount: bigint | number): Promise<TxWriter | null> {
39
+ let token = await this.getToken(tokenMix);
40
+ let erc20 = await this.tokensProvider.erc20(token.address);
41
+ let approved = await erc20.allowance(account.address, spender);
42
+
43
+ let desiredApproval = typeof amount === 'bigint'
44
+ ? amount
45
+ : $bigint.toWei(amount, token.decimals);
46
+
47
+ if (true || approved < desiredApproval) {
48
+ return await erc20
49
+ .$config({
50
+ gasEstimation: true,
51
+ type: 2,
52
+ }, {
53
+ retries: 0
54
+ })
55
+ .approve(account, spender, desiredApproval * 2n);
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * @param amount Can be negative (wraps all with rest)
62
+ */
63
+ async wrapNativeToERC20 (account: ChainAccount, amount: number): Promise<TxWriter> {
64
+ let amountWei = $bigint.toWei(amount, 18);
65
+ if (amountWei < 0n) {
66
+ let balance = await this.client.getBalance(account.address);
67
+ amountWei = balance + amountWei;
68
+ }
69
+ $require.gt(amountWei, 0n);
70
+
71
+ let depositor: { deposit: WXDaiTokenContract['deposit'] };
72
+ switch (this.client.platform) {
73
+ case 'xdai':
74
+ depositor = di.resolve(WXDaiTokenContract);
75
+ break;
76
+ }
77
+ if (depositor == null) {
78
+ throw new Error(`Wrapping depositor not found for platform ${this.client?.platform}`);
79
+ }
80
+ return await depositor.deposit({
81
+ ...account,
82
+ value: amountWei
83
+ });
84
+ }
85
+ /**
86
+ *
87
+ */
88
+ async unwrapNative (account: ChainAccount, amount?: number | bigint): Promise<TxWriter> {
89
+ let depositor: { balanceOf: WXDaiTokenContract['balanceOf'], withdraw: WXDaiTokenContract['withdraw'] };
90
+ switch (this.client.platform) {
91
+ case 'xdai':
92
+ depositor = di.resolve(WXDaiTokenContract);
93
+ break;
94
+ }
95
+ if (depositor == null) {
96
+ throw new Error(`Wrapping depositor not found for platform ${this.client?.platform}`);
97
+ }
98
+ if (amount == null || amount === Infinity) {
99
+ amount = await depositor.balanceOf(account.address);
100
+ }
101
+ let amountWei = typeof amount === 'number'
102
+ ? $bigint.toWei(amount, 18)
103
+ : amount;
104
+
105
+ console.log(amount, amountWei);
106
+ $require.gt(amountWei, 0n);
107
+
108
+ return await depositor.withdraw(account, amountWei);
109
+ }
110
+
111
+ protected async getToken(mix: string | IToken): Promise<IToken> {
112
+ let token = typeof mix === 'string'
113
+ ? await this.tokensProvider.getKnownToken(mix)
114
+ : mix;
115
+
116
+ if (this.tokensProvider.isNative(token.address)) {
117
+ token = {
118
+ ...token,
119
+ address: '0x0000000000000000000000000000000000000000',
120
+ }
121
+ }
122
+
123
+ if (token == null || token.address == null) {
124
+ throw new Error(`Address undefined: ${token}`);
125
+ }
126
+ return token;
127
+ }
128
+ }
@@ -0,0 +1,47 @@
1
+ import { ChainAccount } from '@dequanto/ChainAccounts';
2
+ import { ChainAccountsService } from '@dequanto/ChainAccountsService';
3
+ import { Web3Client } from '@dequanto/clients/Web3Client';
4
+ import { TxLoggerService } from '@dequanto/loggers/TxLoggerService';
5
+ import { IToken } from '@dequanto/models/IToken';
6
+ import di from 'a-di';
7
+ import { ISwapService } from './defi/ISwapService';
8
+ import { Paraswap } from './defi/paraswap/Paraswap';
9
+
10
+
11
+ export class TokenSwapService {
12
+
13
+ constructor(
14
+ public client: Web3Client,
15
+ public provider: ISwapService = di.resolve(Paraswap, client.platform, client)
16
+ ) {
17
+
18
+ }
19
+
20
+ async swap (account: string | ChainAccount, params: {
21
+ from: string | IToken
22
+ to: string | IToken
23
+ amount: number | bigint
24
+ }) {
25
+ if (typeof account === 'string') {
26
+ let accountsService = di.resolve(ChainAccountsService);
27
+ let acc = await accountsService.get(account, this.client.platform);
28
+ if (acc == null) {
29
+ throw new Error(`Account ${account} not found`);
30
+ }
31
+ account = acc;
32
+ }
33
+ // let transfer = di.resolve(TokenTransferService, this.client);
34
+ // let balance = await transfer.getBalance(account, params.from);
35
+ // let token = await transfer.getToken(TOKEN_FROM);
36
+ // let amount = balance - $bigint.toWei(24, token.decimals);
37
+
38
+ let { from, to, amount } = params;
39
+
40
+ let tx = await this.provider.swap(account, {
41
+ from: from,
42
+ to: to,
43
+ fromAmount: amount,
44
+ });
45
+ return tx;
46
+ }
47
+ }
@@ -0,0 +1,216 @@
1
+ import di from 'a-di';
2
+ import { ChainAccount } from '@dequanto/ChainAccounts';
3
+ import { Web3Client } from '@dequanto/clients/Web3Client';
4
+ import { IToken } from '@dequanto/models/IToken';
5
+ import { TAddress } from '@dequanto/models/TAddress';
6
+ import { TxDataBuilder } from '@dequanto/txs/TxDataBuilder';
7
+ import { TxWriter } from '@dequanto/txs/TxWriter';
8
+ import { $bigint } from '@dequanto/utils/$bigint';
9
+ import { $is } from '@dequanto/utils/$is';
10
+ import { TokensService } from './TokensService';
11
+ import { TransactionReceipt } from 'web3-core';
12
+ import { $address } from '@dequanto/utils/$address';
13
+ import { ITxConfig } from '@dequanto/txs/ITxConfig';
14
+ import { $promise } from '@dequanto/utils/$promise';
15
+ import { LoggerService } from '@dequanto/loggers/LoggerService';
16
+ import { $logger } from '@dequanto/utils/$logger';
17
+
18
+
19
+ export class TokenTransferService {
20
+
21
+ private gasPriorityFee?: number
22
+ private txConfig: ITxConfig
23
+ private tokenService = di.resolve(TokensService, this.client.platform)
24
+
25
+ constructor (public client: Web3Client, private logger = di.resolve(LoggerService)) {
26
+
27
+ }
28
+
29
+ $config (txConfig: ITxConfig): this {
30
+ this.txConfig = txConfig;
31
+ return this;
32
+ }
33
+
34
+
35
+ async getBalance(address: TAddress, token: string | IToken): Promise<bigint> {
36
+ token = await this.getToken(token);
37
+ let isNative = this.tokenService.isNative(token.address);
38
+ if (isNative) {
39
+ return this.client.getBalance(address);
40
+ }
41
+
42
+ let erc20 = await TokensService.erc20(token, this.client.platform);
43
+ let balance = await erc20.balanceOf(address);
44
+ return balance;
45
+ }
46
+ async getReceived(receipt: TransactionReceipt): Promise<bigint> {
47
+ let receiver = receipt.from;
48
+ let ANYTOKEN = 'USDC';
49
+ let erc20 = await TokensService.erc20(ANYTOKEN, this.client.platform);
50
+ let transfers = erc20.extractLogsTransfer(receipt)
51
+ let transfer = transfers.find(x => $address.eq(x.to, receiver));
52
+ return transfer?.value ?? 0n;
53
+ }
54
+
55
+ /** Returns NULL for transaction, if no balance to transfer */
56
+ async transferAll (from: ChainAccount, to: TAddress, token: string | IToken) : Promise<TxWriter> {
57
+ token = await this.getToken(token);
58
+
59
+ let isNative = this.tokenService.isNative(token.address);
60
+ if (isNative) {
61
+ return this.transferNativeAll(from, to);
62
+ }
63
+ return this.transferErc20All(from, to, token);
64
+ }
65
+ async transferAllWithRemainder (from: ChainAccount, to: TAddress, token: string | IToken, remainder: number | bigint) : Promise<TxWriter> {
66
+ token = await this.getToken(token);
67
+
68
+ let isNative = this.tokenService.isNative(token.address);
69
+ if (isNative) {
70
+ return this.transferNativeAll(from, to, { remainder });
71
+ }
72
+ return this.transferErc20All(from, to, token, { remainder });
73
+ }
74
+ async transfer (from: ChainAccount, to: TAddress, token: string | IToken, amount: number | bigint) : Promise<TxWriter> {
75
+ token = await this.getToken(token);
76
+ amount = this.getAmount(amount, token);
77
+
78
+ let isNative = this.tokenService.isNative(token.address);
79
+ if (isNative) {
80
+ return this.transferNative(from, to, amount);
81
+ }
82
+ return this.transferErc20(from, to, token, amount);
83
+ }
84
+
85
+ async getToken (token: string | IToken): Promise<IToken> {
86
+ if (typeof token === 'string') {
87
+ token = await this.tokenService.getKnownToken(token);
88
+ }
89
+ $is.notNull(token, 'Token is undefined to transfer');
90
+ return token;
91
+ }
92
+ isNativeToken (token: string | IToken): boolean {
93
+ return this.tokenService.isNative(typeof token === 'string' ? token : token.address);
94
+ }
95
+
96
+ private async transferNativeAll (from: ChainAccount, to: TAddress, opts?: { remainder: number | bigint }): Promise<TxWriter> {
97
+ let buildTxRetries = 1;
98
+
99
+ const buildTx = async () => {
100
+ let GAS = 21000;
101
+ let GAS_RATIO = 1.05;
102
+ let [ balance, gasPrice] = await Promise.all([
103
+ this.client.getBalance(from.address),
104
+ this.client.getGasPrice()
105
+ ]);
106
+ if (opts?.remainder != null) {
107
+ let remainder = this.getAmount(opts.remainder, 18);
108
+ balance -= remainder;
109
+ }
110
+
111
+ let $gasPrice = $bigint.multWithFloat(gasPrice.price, GAS_RATIO);
112
+ console.log('$gasPrice', $bigint.toGweiFromWei($gasPrice));
113
+
114
+ let gasConsumed = BigInt(GAS) * $gasPrice;
115
+ let transferValue = balance - gasConsumed;
116
+ if (transferValue <= 0) {
117
+ if (--buildTxRetries > -1) {
118
+ $logger.log(`No balance to transfer retry in 5s`);
119
+ await $promise.wait(5000);
120
+ return buildTx();
121
+ }
122
+ // No balance to transfer
123
+ $logger.log(`No balance to transfer in ${from.address}. ${ opts?.remainder ? ("Remainder: " + opts?.remainder) : ""}`);
124
+ return null;
125
+ }
126
+
127
+ let txBuilder = new TxDataBuilder(this.client, from, {
128
+ to: to,
129
+ value: $bigint.toHex(transferValue)
130
+ });
131
+
132
+ txBuilder.data.gasPrice = $bigint.toHex($gasPrice);
133
+
134
+ // txBuilder.data.maxFeePerGas = $bigint.toHex($gasPrice - 20n**9n);
135
+ // txBuilder.data.maxPriorityFeePerGas = $bigint.toHex(20n**9n);
136
+ txBuilder.data.gasLimit = GAS;
137
+ txBuilder.data.type = 1;
138
+
139
+ txBuilder.setConfig(this.txConfig);
140
+
141
+ await Promise.all([
142
+ txBuilder.setNonce({ overriding: true }),
143
+ ]);
144
+
145
+ $logger.log(`TransferNative ALL. Balance ${balance}; GasConsumed ${gasConsumed}; TransferValue ${transferValue}; Nonce: ${txBuilder.data.nonce}`);
146
+ return txBuilder;
147
+ }
148
+ let txBuilder = await buildTx();
149
+ return TxWriter.write(this.client, txBuilder, from, {
150
+ retries: 3,
151
+ async onErrorRebuild (tx, error, errCount) {
152
+ // In case we got `balance` value, but that one was outdated, then all our calculations where wrong.
153
+ // Retry the calculation and transfer once again.
154
+ if (/insufficient funds/.test(error.message)) {
155
+ const ms = 6000 * errCount;
156
+ $logger.log(`TokenTransfer Failed: insufficient funds. Waiting ${ms}ms to retry`);
157
+ await $promise.wait(ms);
158
+ return buildTx();
159
+ }
160
+ return null;
161
+ }
162
+ });
163
+ }
164
+ private async transferNative (from: ChainAccount, to: TAddress, amount: bigint): Promise<TxWriter> {
165
+ let txBuilder = new TxDataBuilder(this.client, from, {
166
+ to: to,
167
+ value: $bigint.toHex(amount)
168
+ });
169
+
170
+ let GAS = 21000;
171
+ await Promise.all([
172
+ txBuilder.setGas({ priceRatio: this.gasPriorityFee, gasLimit: GAS }),
173
+ txBuilder.setNonce(),
174
+ ]);
175
+ txBuilder.setConfig(this.txConfig);
176
+ return TxWriter.write(this.client, txBuilder, from);
177
+ }
178
+
179
+ private async transferErc20All (from: ChainAccount, to: TAddress, token: IToken, opts?: { remainder?: number | bigint, retryCount?: number }): Promise<TxWriter> {
180
+ let erc20 = await TokensService.erc20(token, this.client.platform);
181
+ let balance = await erc20.balanceOf(from.address);
182
+ if (opts?.remainder != null) {
183
+ let remainder = this.getAmount(opts.remainder, 18);
184
+ balance -= remainder;
185
+ }
186
+ if (balance <= 0n) {
187
+ if (opts?.retryCount == null || opts?.retryCount !== 0) {
188
+ // re-read
189
+ this.logger.warn(`TransferErc20All has no balance to transfer: ${token.address}. Balance re-fetch scheduled.`);
190
+ await $promise.wait(4000);
191
+ return this.transferErc20All(from, to, token, {
192
+ ...(opts ?? {}),
193
+ retryCount: 0
194
+ });
195
+ }
196
+ return null;
197
+ }
198
+ return erc20
199
+ .$config(this.txConfig)
200
+ .transfer(from, to, balance);
201
+ }
202
+ private async transferErc20 (from: ChainAccount, to: TAddress, token: IToken, amount: bigint): Promise<TxWriter> {
203
+ let erc20 = await TokensService.erc20(token, this.client.platform);
204
+ return erc20
205
+ .$config(this.txConfig)
206
+ .transfer(from, to, amount);
207
+ }
208
+ private getAmount (amount: number | bigint, token: IToken): bigint
209
+ private getAmount (amount: number | bigint, decimals: number): bigint
210
+ private getAmount (amount: number | bigint, mix: number | IToken): bigint {
211
+ if (typeof amount === 'number') {
212
+ amount = $bigint.toWei(amount, typeof mix === 'number' ? mix : mix.decimals);
213
+ }
214
+ return amount;
215
+ }
216
+ }