@sabaaa1/common 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 (445) hide show
  1. package/.env.example +5 -0
  2. package/.eslintrc.json +18 -0
  3. package/README.md +164 -0
  4. package/copyPackageJson.js +81 -0
  5. package/handleCDNWorkers.js +92 -0
  6. package/jest.config.ts +10 -0
  7. package/package.json +101 -0
  8. package/polyfillWorker.ts +15 -0
  9. package/project.json +32 -0
  10. package/src/API/API.ts +203 -0
  11. package/src/API/admin-calls.ts +8 -0
  12. package/src/API/ai-calls.ts +48 -0
  13. package/src/API/brotherhoodCalls.ts +184 -0
  14. package/src/API/callLifiAPI.ts +41 -0
  15. package/src/API/callMonitor.ts +9 -0
  16. package/src/API/callOdosAPI.ts +89 -0
  17. package/src/API/callOneInchAPI.ts +47 -0
  18. package/src/API/callRelayer.ts +23 -0
  19. package/src/API/checkRisk.ts +7 -0
  20. package/src/API/duneAPI.ts +26 -0
  21. package/src/API/enclaveCalls.ts +23 -0
  22. package/src/API/fetchCommitmentsCache.ts +63 -0
  23. package/src/API/generate-trading-points.ts +77 -0
  24. package/src/API/get-token-data.ts +12 -0
  25. package/src/API/getBridgeProtocols.ts +16 -0
  26. package/src/API/getCoingeckoPrice.ts +59 -0
  27. package/src/API/getGasEstimates.ts +30 -0
  28. package/src/API/getLifiStatus.ts +35 -0
  29. package/src/API/getRelayerURL.ts +27 -0
  30. package/src/API/getServerURL.ts +116 -0
  31. package/src/API/getTokenPrice.ts +39 -0
  32. package/src/API/getWebsiteURL.ts +58 -0
  33. package/src/API/index.ts +19 -0
  34. package/src/API/is-tx-stateless.ts +32 -0
  35. package/src/API/kycCalls.ts +81 -0
  36. package/src/API/leaderboardCalls.ts +32 -0
  37. package/src/API/mysteryBoxesCalls.ts +141 -0
  38. package/src/API/passwordCalls.ts +34 -0
  39. package/src/API/proxyAccountsCalls.ts +40 -0
  40. package/src/API/referralsCalls.ts +52 -0
  41. package/src/API/relayCalls.ts +14 -0
  42. package/src/API/restoreSnapshots.ts +7 -0
  43. package/src/API/rewardsUserCalls.ts +124 -0
  44. package/src/API/send-telegram-callback.ts +17 -0
  45. package/src/API/simulate-batch-tx.ts +19 -0
  46. package/src/API/tenderly.api.ts +96 -0
  47. package/src/API/token-calls.ts +19 -0
  48. package/src/API/weeklyAnalyticCalls.ts +43 -0
  49. package/src/constants/activity.constants.ts +10 -0
  50. package/src/constants/addresses.constants.ts +74 -0
  51. package/src/constants/assets.constants.ts +15 -0
  52. package/src/constants/backend.constants.ts +16 -0
  53. package/src/constants/balance.constants.ts +1 -0
  54. package/src/constants/bridging.constants.ts +5 -0
  55. package/src/constants/chains.constants.ts +194 -0
  56. package/src/constants/coingecko.constants.ts +67 -0
  57. package/src/constants/contracts.constants.ts +106 -0
  58. package/src/constants/conversion.constants.ts +1 -0
  59. package/src/constants/deploy-data/deploy-data-arbMainnet.json +5685 -0
  60. package/src/constants/deploy-data/deploy-data-arcTestnet.json +6157 -0
  61. package/src/constants/deploy-data/deploy-data-avalanche.json +5921 -0
  62. package/src/constants/deploy-data/deploy-data-base.json +5695 -0
  63. package/src/constants/deploy-data/deploy-data-bnbMainnet.json +5921 -0
  64. package/src/constants/deploy-data/deploy-data-ethMainnet.json +5922 -0
  65. package/src/constants/deploy-data/deploy-data-localhost.json +5921 -0
  66. package/src/constants/deploy-data/deploy-data-optimism.json +5687 -0
  67. package/src/constants/deploy-data/deploy-data-polygon.json +5695 -0
  68. package/src/constants/deploy-data/index.ts +21 -0
  69. package/src/constants/events.constants.ts +10 -0
  70. package/src/constants/fees.constants.ts +4 -0
  71. package/src/constants/function-signatures.constants.ts +6 -0
  72. package/src/constants/index.ts +30 -0
  73. package/src/constants/kyc.constants.ts +202 -0
  74. package/src/constants/lifi.constants.ts +1 -0
  75. package/src/constants/mediaUrls.constants.ts +25 -0
  76. package/src/constants/mystery-boxes.constants.ts +402 -0
  77. package/src/constants/oauthUrls.constants.ts +7 -0
  78. package/src/constants/permit2.constants.ts +28 -0
  79. package/src/constants/presale.constants.ts +503 -0
  80. package/src/constants/protocol.constants.ts +65 -0
  81. package/src/constants/reorg-depths.constants.ts +13 -0
  82. package/src/constants/rewards.constants.ts +27 -0
  83. package/src/constants/save-depths.ts +13 -0
  84. package/src/constants/server.constants.ts +233 -0
  85. package/src/constants/tasks.constants.ts +205 -0
  86. package/src/constants/token-data/ERC20Registry.ts +90 -0
  87. package/src/constants/token-data/arbMainnetRegistry.json +1841 -0
  88. package/src/constants/token-data/arbMainnetRegistryFixed.json +1841 -0
  89. package/src/constants/token-data/arcTestnetRegistry.json +436 -0
  90. package/src/constants/token-data/avalancheRegistry.json +729 -0
  91. package/src/constants/token-data/avalancheRegistryFixed.json +729 -0
  92. package/src/constants/token-data/baseRegistry.json +1134 -0
  93. package/src/constants/token-data/baseRegistryFixed.json +1134 -0
  94. package/src/constants/token-data/bnbMainnetRegistry.json +900 -0
  95. package/src/constants/token-data/bnbMainnetRegistryFixed.json +900 -0
  96. package/src/constants/token-data/ethMainnetRegistry.json +4298 -0
  97. package/src/constants/token-data/ethMainnetRegistryFixed.json +4298 -0
  98. package/src/constants/token-data/index.ts +60 -0
  99. package/src/constants/token-data/localhostRegistry.json +2784 -0
  100. package/src/constants/token-data/optimismRegistry.json +701 -0
  101. package/src/constants/token-data/optimismRegistryFixed.json +701 -0
  102. package/src/constants/token-data/polygonRegistry.json +2309 -0
  103. package/src/constants/token-data/polygonRegistryFixed.json +2309 -0
  104. package/src/constants/token-data/popularTokens.constants.ts +11 -0
  105. package/src/constants/token-data/tokenPricing.consts.ts +2 -0
  106. package/src/constants/token.limits.constants.ts +31 -0
  107. package/src/constants/vite.constants.ts +74 -0
  108. package/src/constants/wallet.constants.ts +9 -0
  109. package/src/crypto/babyJub.ts +31 -0
  110. package/src/crypto/index.ts +3 -0
  111. package/src/crypto/poseidon.ts +36 -0
  112. package/src/crypto/preProcessing.ts +20 -0
  113. package/src/data-structures/ApprovalDBs/EventsPublicApprovalsDB.ts +288 -0
  114. package/src/data-structures/ApprovalDBs/index.ts +1 -0
  115. package/src/data-structures/Hinkal/Hinkal.ts +746 -0
  116. package/src/data-structures/Hinkal/IHinkal.ts +315 -0
  117. package/src/data-structures/Hinkal/handleAutoDepositBack.ts +138 -0
  118. package/src/data-structures/Hinkal/hinkalActionFundApproveAndTransact.ts +64 -0
  119. package/src/data-structures/Hinkal/hinkalActionReceive.ts +65 -0
  120. package/src/data-structures/Hinkal/hinkalActionStake.ts +152 -0
  121. package/src/data-structures/Hinkal/hinkalApprove.ts +170 -0
  122. package/src/data-structures/Hinkal/hinkalCheckTokenRegistry.ts +26 -0
  123. package/src/data-structures/Hinkal/hinkalDeposit.ts +199 -0
  124. package/src/data-structures/Hinkal/hinkalGetRecipientInfo.ts +12 -0
  125. package/src/data-structures/Hinkal/hinkalGetZkMeProvider.ts +31 -0
  126. package/src/data-structures/Hinkal/hinkalInsideTransact.ts +190 -0
  127. package/src/data-structures/Hinkal/hinkalMultiSend.ts +26 -0
  128. package/src/data-structures/Hinkal/hinkalPrivateWallet.ts +198 -0
  129. package/src/data-structures/Hinkal/hinkalProoflessDeposit.ts +91 -0
  130. package/src/data-structures/Hinkal/hinkalProxySwap.ts +91 -0
  131. package/src/data-structures/Hinkal/hinkalSignSubAccount.ts +28 -0
  132. package/src/data-structures/Hinkal/hinkalSwap.ts +157 -0
  133. package/src/data-structures/Hinkal/hinkalTransfer.ts +171 -0
  134. package/src/data-structures/Hinkal/hinkalWithdraw.ts +161 -0
  135. package/src/data-structures/Hinkal/index.ts +9 -0
  136. package/src/data-structures/Hinkal/resetMerkleTrees.ts +64 -0
  137. package/src/data-structures/IndexedDB/activity-db.ts +204 -0
  138. package/src/data-structures/IndexedDB/balances-db.ts +97 -0
  139. package/src/data-structures/IndexedDB/contact-db.ts +81 -0
  140. package/src/data-structures/IndexedDB/index.ts +6 -0
  141. package/src/data-structures/IndexedDB/prices-db.ts +89 -0
  142. package/src/data-structures/IndexedDB/private-balances-db.ts +31 -0
  143. package/src/data-structures/IndexedDB/signatures-db.ts +62 -0
  144. package/src/data-structures/MultiThreadedUtxoUtils/MultiThreadedUtxoUtils.ts +152 -0
  145. package/src/data-structures/TokenDBs/AlchemyPublicTokensDB.ts +224 -0
  146. package/src/data-structures/TokenDBs/ArcPublicTokensDB.ts +198 -0
  147. package/src/data-structures/TokenDBs/EventsPublicTokensDB.ts +216 -0
  148. package/src/data-structures/TokenDBs/IPublicTokensDB.ts +7 -0
  149. package/src/data-structures/TokenDBs/PrivateTokensDB.ts +96 -0
  150. package/src/data-structures/TokenDBs/PublicTokensDB.ts +49 -0
  151. package/src/data-structures/TokenDBs/index.ts +4 -0
  152. package/src/data-structures/TokenDBs/token-visibility-db.ts +154 -0
  153. package/src/data-structures/ValueCache/ValueCache.ts +29 -0
  154. package/src/data-structures/ValueCache/index.ts +1 -0
  155. package/src/data-structures/cacheDevices/AttachableMemoryCacheDevice.ts +33 -0
  156. package/src/data-structures/cacheDevices/BaseCacheDevice.ts +30 -0
  157. package/src/data-structures/cacheDevices/FileCacheDevice.ts +59 -0
  158. package/src/data-structures/cacheDevices/LocalStorageCacheDevice.ts +36 -0
  159. package/src/data-structures/cacheDevices/index.ts +2 -0
  160. package/src/data-structures/crypto-keys/decodeUTXO.ts +60 -0
  161. package/src/data-structures/crypto-keys/encryptDecryptUtxo.ts +74 -0
  162. package/src/data-structures/crypto-keys/index.ts +4 -0
  163. package/src/data-structures/crypto-keys/keyUtils.ts +8 -0
  164. package/src/data-structures/crypto-keys/keys.ts +203 -0
  165. package/src/data-structures/custom-token-registry/CustomTokenRegistry.ts +49 -0
  166. package/src/data-structures/event-service/AbstractAccessTokenSnapshotService.ts +142 -0
  167. package/src/data-structures/event-service/AbstractApprovalsSnapshotService.ts +152 -0
  168. package/src/data-structures/event-service/AbstractCommitmentsSnapshotService.ts +116 -0
  169. package/src/data-structures/event-service/AbstractEventService.ts +44 -0
  170. package/src/data-structures/event-service/AbstractNullifierSnapshotService.ts +76 -0
  171. package/src/data-structures/event-service/AbstractSnapshotService.ts +63 -0
  172. package/src/data-structures/event-service/BlockchainEventEmitter.ts +132 -0
  173. package/src/data-structures/event-service/index.ts +7 -0
  174. package/src/data-structures/index.ts +18 -0
  175. package/src/data-structures/merkle-tree/MerkleTree.test.ts +77 -0
  176. package/src/data-structures/merkle-tree/MerkleTree.ts +253 -0
  177. package/src/data-structures/merkle-tree/MerkleTreeIncompleteError.ts +6 -0
  178. package/src/data-structures/merkle-tree/getPatchedAccessTokenMerkleTree.ts +24 -0
  179. package/src/data-structures/merkle-tree/index.ts +3 -0
  180. package/src/data-structures/presale/PresaleContractWrapper.ts +80 -0
  181. package/src/data-structures/presale/index.ts +1 -0
  182. package/src/data-structures/provider-adapter/IProviderAdapter.ts +43 -0
  183. package/src/data-structures/snapshot/ClientAccessTokenSnapshotService.ts +41 -0
  184. package/src/data-structures/snapshot/ClientApprovalsSnapshotService.ts +36 -0
  185. package/src/data-structures/snapshot/ClientCommitmentsSnapshotService.ts +30 -0
  186. package/src/data-structures/snapshot/ClientNullifierSnapshotService.ts +28 -0
  187. package/src/data-structures/snapshot/SnapshotFetcherService.ts +68 -0
  188. package/src/data-structures/snapshot/index.ts +1 -0
  189. package/src/data-structures/token-price-fetcher/TokenChecker.ts +45 -0
  190. package/src/data-structures/token-price-fetcher/index.ts +1 -0
  191. package/src/data-structures/tor/HttpClient.ts +118 -0
  192. package/src/data-structures/tor/TorAdapter.ts +94 -0
  193. package/src/data-structures/tor/TorClient.ts +283 -0
  194. package/src/data-structures/tor/WebSocketDuplex.ts +32 -0
  195. package/src/data-structures/tor/index.ts +3 -0
  196. package/src/data-structures/transactions-manager/history/history.types.ts +14 -0
  197. package/src/data-structures/transactions-manager/index.ts +1 -0
  198. package/src/data-structures/utxo/Utxo.ts +189 -0
  199. package/src/error-handling/customErrors/ErrorWithAmount.ts +8 -0
  200. package/src/error-handling/customErrors/ErrorWithTx.ts +10 -0
  201. package/src/error-handling/customErrors/FeeOverTransactionValueError.ts +16 -0
  202. package/src/error-handling/customErrors/SimulationFailureError.ts +9 -0
  203. package/src/error-handling/customErrors/customErrors.helpers.ts +39 -0
  204. package/src/error-handling/customErrors/index.ts +5 -0
  205. package/src/error-handling/error-codes.constants.ts +214 -0
  206. package/src/error-handling/get-error.message.ts +149 -0
  207. package/src/error-handling/handleErrorRestore.ts +25 -0
  208. package/src/error-handling/index.ts +7 -0
  209. package/src/error-handling/logError.ts +8 -0
  210. package/src/error-handling/logger.ts +21 -0
  211. package/src/error-handling/types.ts +10 -0
  212. package/src/externalABIs/BUSD.ts +516 -0
  213. package/src/externalABIs/BabPassport.json +24 -0
  214. package/src/externalABIs/DAI.ts +331 -0
  215. package/src/externalABIs/ERC1155.json +316 -0
  216. package/src/externalABIs/ERC20.json +297 -0
  217. package/src/externalABIs/ERC20.ts +1 -0
  218. package/src/externalABIs/ERC721.json +205 -0
  219. package/src/externalABIs/GalxePassport.json +23 -0
  220. package/src/externalABIs/IQuoterV2.json +211 -0
  221. package/src/externalABIs/ISwapRouter.json +568 -0
  222. package/src/externalABIs/IUniswapV3Factory.json +207 -0
  223. package/src/externalABIs/IUniswapV3Pool.json +999 -0
  224. package/src/externalABIs/NodeInterfaceABI.json +1 -0
  225. package/src/externalABIs/OptimismGasPriceOracle.json +1 -0
  226. package/src/externalABIs/PoLidoNftAbi.json +307 -0
  227. package/src/externalABIs/SanctionsList.ts +86 -0
  228. package/src/externalABIs/USDC.ts +718 -0
  229. package/src/externalABIs/USDR.ts +343 -0
  230. package/src/externalABIs/USDR3CRV.ts +539 -0
  231. package/src/externalABIs/USDT.ts +390 -0
  232. package/src/externalABIs/UniswapV2PoolAbi.json +66 -0
  233. package/src/externalABIs/WETH.ts +153 -0
  234. package/src/externalABIs/amToken.ts +347 -0
  235. package/src/externalABIs/index.ts +53 -0
  236. package/src/externalABIs/swapAbi.ts +442 -0
  237. package/src/externalABIs/transactionsProver.json +45 -0
  238. package/src/functions/index.ts +16 -0
  239. package/src/functions/kyc/aiPriseHelper.ts +0 -0
  240. package/src/functions/kyc/authentoHelper.ts +44 -0
  241. package/src/functions/kyc/index.ts +3 -0
  242. package/src/functions/kyc/openDefaultPassportWindow.ts +9 -0
  243. package/src/functions/kyc/passportHelper.ts +13 -0
  244. package/src/functions/kyc/zkMeHelper.ts +69 -0
  245. package/src/functions/pre-transaction/constructAdminData.ts +21 -0
  246. package/src/functions/pre-transaction/getExternalSwapAddress.ts +30 -0
  247. package/src/functions/pre-transaction/getFeeStructure.ts +44 -0
  248. package/src/functions/pre-transaction/getFlatFees.ts +88 -0
  249. package/src/functions/pre-transaction/getSignatureDataForTransact.ts +16 -0
  250. package/src/functions/pre-transaction/getVolatileTransferAmount.ts +56 -0
  251. package/src/functions/pre-transaction/index.ts +7 -0
  252. package/src/functions/pre-transaction/interaction-to-action.ts +17 -0
  253. package/src/functions/pre-transaction/merge-with-fee-structure-emporium.ts +50 -0
  254. package/src/functions/pre-transaction/merge-with-fee-structure.ts +35 -0
  255. package/src/functions/pre-transaction/outputApprovalDataProcessing.ts +95 -0
  256. package/src/functions/pre-transaction/outputUtxoProcessing.ts +52 -0
  257. package/src/functions/pre-transaction/process-gas-estimates.ts +36 -0
  258. package/src/functions/pre-transaction/shouldPatchAccessTokenMerkleTree.ts +15 -0
  259. package/src/functions/private-wallet/emporium.helpers.ts +296 -0
  260. package/src/functions/private-wallet/emporium.swap.helpers.ts +284 -0
  261. package/src/functions/private-wallet/index.ts +3 -0
  262. package/src/functions/private-wallet/opProducer.ts +33 -0
  263. package/src/functions/snarkjs/common.snarkjs.ts +377 -0
  264. package/src/functions/snarkjs/constant.ts +490 -0
  265. package/src/functions/snarkjs/constructEmporiumProof.ts +301 -0
  266. package/src/functions/snarkjs/constructGeneralZkProof.ts +281 -0
  267. package/src/functions/snarkjs/generateCircomData.ts +81 -0
  268. package/src/functions/snarkjs/generateZkProof.ts +21 -0
  269. package/src/functions/snarkjs/generateZkProofEnclave.ts +45 -0
  270. package/src/functions/snarkjs/generateZkProofSelf.ts +29 -0
  271. package/src/functions/snarkjs/getOriginalSender.ts +4 -0
  272. package/src/functions/snarkjs/getZKFiles.ts +29 -0
  273. package/src/functions/snarkjs/index.ts +4 -0
  274. package/src/functions/staking/index.ts +78 -0
  275. package/src/functions/utils/addresses.ts +37 -0
  276. package/src/functions/utils/amounts.utils.test.ts +91 -0
  277. package/src/functions/utils/amounts.utils.ts +119 -0
  278. package/src/functions/utils/arraysMatch.ts +4 -0
  279. package/src/functions/utils/cacheDevice.utils.ts +21 -0
  280. package/src/functions/utils/cacheFunctions.ts +154 -0
  281. package/src/functions/utils/caseInsensitive.utils.ts +10 -0
  282. package/src/functions/utils/convertEmporiumOpToCallInfo.ts +19 -0
  283. package/src/functions/utils/convertIntegrationProviderToExternalActionId.ts +14 -0
  284. package/src/functions/utils/create-provider.ts +11 -0
  285. package/src/functions/utils/encodeTokenWithId.ts +4 -0
  286. package/src/functions/utils/encryptInputForEnclave.ts +119 -0
  287. package/src/functions/utils/enum.utils.ts +30 -0
  288. package/src/functions/utils/erc20tokenFunctions.ts +110 -0
  289. package/src/functions/utils/ethers-formatter.utils.ts +32 -0
  290. package/src/functions/utils/evmNetworkFunctions.ts +9 -0
  291. package/src/functions/utils/external-action.utils.ts +15 -0
  292. package/src/functions/utils/fees.utils.ts +26 -0
  293. package/src/functions/utils/get-hinkal-approvals.ts +36 -0
  294. package/src/functions/utils/get-signature-header.ts +5 -0
  295. package/src/functions/utils/getBlockExplorerUrl.ts +14 -0
  296. package/src/functions/utils/getDataFromTransaction.ts +79 -0
  297. package/src/functions/utils/getRecipientInfoFromUserKeys.ts +28 -0
  298. package/src/functions/utils/inLogicMetadata.ts +9 -0
  299. package/src/functions/utils/index.ts +43 -0
  300. package/src/functions/utils/involves-permit2-op.ts +17 -0
  301. package/src/functions/utils/ipfs.ts +74 -0
  302. package/src/functions/utils/is-valid-url.ts +5 -0
  303. package/src/functions/utils/lifi.utils.ts +3 -0
  304. package/src/functions/utils/memoize.utils.ts +23 -0
  305. package/src/functions/utils/merkleTree.utils.ts +27 -0
  306. package/src/functions/utils/mutexes.utils.ts +3 -0
  307. package/src/functions/utils/mystery-box-auction.utils.ts +61 -0
  308. package/src/functions/utils/networks.utils.ts +6 -0
  309. package/src/functions/utils/nftTokenFunctions.ts +25 -0
  310. package/src/functions/utils/nickname.utils.ts +4 -0
  311. package/src/functions/utils/postToOffscreen.ts +6 -0
  312. package/src/functions/utils/prepareHinkal.ts +78 -0
  313. package/src/functions/utils/process.utils.ts +23 -0
  314. package/src/functions/utils/processUseApprovalUtxoData.ts +26 -0
  315. package/src/functions/utils/publicBalance.utils.ts +131 -0
  316. package/src/functions/utils/reloadPage.ts +1 -0
  317. package/src/functions/utils/replaceAddressInCalldata.ts +6 -0
  318. package/src/functions/utils/requireEnv.ts +10 -0
  319. package/src/functions/utils/resolve-sync.utils.ts +40 -0
  320. package/src/functions/utils/rpc-int-encode.ts +7 -0
  321. package/src/functions/utils/serialize.utils.ts +12 -0
  322. package/src/functions/utils/string.utils.ts +92 -0
  323. package/src/functions/utils/time.utils.ts +80 -0
  324. package/src/functions/utils/token-check.utils.ts +12 -0
  325. package/src/functions/utils/trimFieldValues.ts +24 -0
  326. package/src/functions/utils/upToDateState.ts +12 -0
  327. package/src/functions/utils/userAgent.ts +26 -0
  328. package/src/functions/utils/walletBalances.utils.ts +117 -0
  329. package/src/functions/web3/EIP-712.test.ts +302 -0
  330. package/src/functions/web3/EIP-712.ts +243 -0
  331. package/src/functions/web3/etherFunctions.test.ts +129 -0
  332. package/src/functions/web3/etherFunctions.ts +84 -0
  333. package/src/functions/web3/events/balanceChangedCustomHandler.ts +13 -0
  334. package/src/functions/web3/events/balanceChangedHandler.ts +10 -0
  335. package/src/functions/web3/events/getApprovedBalance.ts +154 -0
  336. package/src/functions/web3/events/getInputUtxoAndBalance.ts +305 -0
  337. package/src/functions/web3/events/getInputUtxosEnclave.ts +40 -0
  338. package/src/functions/web3/events/getShieldedBalance.ts +163 -0
  339. package/src/functions/web3/events/getTransactionLogEvents.ts +55 -0
  340. package/src/functions/web3/events/index.ts +7 -0
  341. package/src/functions/web3/events/web3RetrieveEvents.ts +33 -0
  342. package/src/functions/web3/functionCalls/accessTokenCalls.ts +27 -0
  343. package/src/functions/web3/functionCalls/approveToken.ts +180 -0
  344. package/src/functions/web3/functionCalls/approveTokensToHinkal.ts +21 -0
  345. package/src/functions/web3/functionCalls/estimateGasRelayer.ts +40 -0
  346. package/src/functions/web3/functionCalls/getRootHash.ts +7 -0
  347. package/src/functions/web3/functionCalls/inHinkalApprovalCalls.ts +60 -0
  348. package/src/functions/web3/functionCalls/relayFunctions.ts +12 -0
  349. package/src/functions/web3/functionCalls/transactCallDirect.ts +71 -0
  350. package/src/functions/web3/functionCalls/transactCallRelayer.ts +57 -0
  351. package/src/functions/web3/getContractMetadata.ts +43 -0
  352. package/src/functions/web3/getPublicAddressBalance.ts +17 -0
  353. package/src/functions/web3/getTokenHolder.ts +53 -0
  354. package/src/functions/web3/index.ts +9 -0
  355. package/src/functions/web3/lifiAPI.ts +41 -0
  356. package/src/functions/web3/odosAPI.ts +50 -0
  357. package/src/functions/web3/oneInchAPI.ts +47 -0
  358. package/src/functions/web3/runContractFunction.ts +116 -0
  359. package/src/functions/web3/uniswapAPI.ts +156 -0
  360. package/src/index.ts +9 -0
  361. package/src/mutexes/index.ts +1 -0
  362. package/src/mutexes/mutex.ts +3 -0
  363. package/src/providers/EthersProviderAdapter.ts +230 -0
  364. package/src/providers/TorExternalProvider.ts +36 -0
  365. package/src/providers/WagmiProviderAdapter.ts +311 -0
  366. package/src/providers/exportProviers.ts +11 -0
  367. package/src/providers/prepareEthersHinkal.ts +18 -0
  368. package/src/providers/prepareWagmiHinkal.ts +16 -0
  369. package/src/types/API.types.ts +23 -0
  370. package/src/types/ICacheDevice.ts +5 -0
  371. package/src/types/IMultiThreadedUtxoUtils.ts +16 -0
  372. package/src/types/RewardUserEnums.ts +12 -0
  373. package/src/types/TransactionSimulator.types.ts +30 -0
  374. package/src/types/WeeklyAnalytics.types.ts +44 -0
  375. package/src/types/activities.types.ts +90 -0
  376. package/src/types/admin.types.ts +30 -0
  377. package/src/types/all-points.types.ts +8 -0
  378. package/src/types/approvals.types.ts +45 -0
  379. package/src/types/balances.types.ts +20 -0
  380. package/src/types/big-intable.types.ts +3 -0
  381. package/src/types/bridging.types.ts +30 -0
  382. package/src/types/brotherhood-user.types.ts +13 -0
  383. package/src/types/cache.types.ts +42 -0
  384. package/src/types/circom-data.types.ts +120 -0
  385. package/src/types/coingecko.types.ts +216 -0
  386. package/src/types/commitments.types.ts +39 -0
  387. package/src/types/confirmation-request.types.ts +10 -0
  388. package/src/types/contacts.types.ts +6 -0
  389. package/src/types/crypto.types.ts +8 -0
  390. package/src/types/duneAPI.types.ts +9 -0
  391. package/src/types/eip5792.types.ts +31 -0
  392. package/src/types/ethereum-network.types.ts +70 -0
  393. package/src/types/external-action.types.ts +19 -0
  394. package/src/types/fee.types.ts +11 -0
  395. package/src/types/generatePoints.ts +14 -0
  396. package/src/types/hinkal.stake.types.ts +12 -0
  397. package/src/types/hinkal.types.ts +150 -0
  398. package/src/types/index.ts +50 -0
  399. package/src/types/kyc.types.ts +49 -0
  400. package/src/types/merch-order.types.ts +18 -0
  401. package/src/types/message.types.ts +6 -0
  402. package/src/types/mystery-boxes.types.ts +50 -0
  403. package/src/types/new-rewards.type.ts +181 -0
  404. package/src/types/offscreen.types.ts +8 -0
  405. package/src/types/presaleReferral.types.ts +4 -0
  406. package/src/types/proxy.types.ts +11 -0
  407. package/src/types/referral.types.ts +13 -0
  408. package/src/types/relayer.types.ts +16 -0
  409. package/src/types/remote-proof.types.ts +18 -0
  410. package/src/types/rewards.types.ts +53 -0
  411. package/src/types/routing.types.ts +7 -0
  412. package/src/types/sandbox.types.ts +246 -0
  413. package/src/types/session.types.ts +12 -0
  414. package/src/types/signature.types.ts +11 -0
  415. package/src/types/slippage.types.ts +3 -0
  416. package/src/types/snark.types.ts +43 -0
  417. package/src/types/tenderly.api.types.ts +200 -0
  418. package/src/types/token-prices.types.ts +8 -0
  419. package/src/types/token-with-id.types.ts +4 -0
  420. package/src/types/token.types.ts +86 -0
  421. package/src/types/transactions.types.ts +120 -0
  422. package/src/types/wc.types.ts +83 -0
  423. package/src/types/with-id.types.ts +1 -0
  424. package/src/webworker/performTaskWithWorker.ts +50 -0
  425. package/src/webworker/snarkjsWorker/snarkjs.d.ts +2 -0
  426. package/src/webworker/snarkjsWorker/snarkjsWorker.types.ts +18 -0
  427. package/src/webworker/snarkjsWorker/snarkjsWorkerLauncher.ts +19 -0
  428. package/src/webworker/snarkjsWorker/snarkjsWorkerLogic.ts +90 -0
  429. package/src/webworker/utxoWorker/utxoWorker.types.ts +41 -0
  430. package/src/webworker/utxoWorker/utxoWorkerLauncher.ts +19 -0
  431. package/src/webworker/utxoWorker/utxoWorkerLogic.ts +107 -0
  432. package/src/webworker/viteWorkerURL.constant.ts +25 -0
  433. package/src/webworker/worker.registry.ts +11 -0
  434. package/src/webworker/worker.types.ts +35 -0
  435. package/src/webworker/workerErrorHandler.ts +10 -0
  436. package/src/webworker/workerFactory.ts +47 -0
  437. package/src/webworker/workerProxy.ts +88 -0
  438. package/src/webworker/zkProofWorker/zkProofWorker.types.ts +52 -0
  439. package/src/webworker/zkProofWorker/zkProofWorkerLauncher.ts +19 -0
  440. package/src/webworker/zkProofWorker/zkProofWorkerLogic.ts +84 -0
  441. package/tsconfig.json +23 -0
  442. package/tsconfig.lib.json +10 -0
  443. package/tsconfig.spec.json +15 -0
  444. package/vite.config.ts +97 -0
  445. package/vite.config.workers.ts +51 -0
@@ -0,0 +1,36 @@
1
+ import { getGasEstimates } from '../../API/getGasEstimates';
2
+ import { logError } from '../../error-handling/logError';
3
+ import { CallInfo, ERC20Token, ExternalActionId } from '../../types';
4
+ import { getValueFirstNDigit } from '../utils/amounts.utils';
5
+ import { getAmountInWei } from '../web3/etherFunctions';
6
+
7
+ export const processGasEstimates = async (
8
+ chainId: number,
9
+ tokenForGasFee: ERC20Token,
10
+ externalActionId: ExternalActionId,
11
+ erc20TokenAddressLength: number,
12
+ gasAmount?: number,
13
+ calls: CallInfo<bigint>[] = [],
14
+ ) => {
15
+ let priceOfTransactionInUSD;
16
+ let priceOfTransactionInTokenEstimate;
17
+
18
+ try {
19
+ ({ priceOfTransactionInUSD, priceOfTransactionInToken: priceOfTransactionInTokenEstimate } = await getGasEstimates(
20
+ chainId,
21
+ tokenForGasFee.erc20TokenAddress,
22
+ externalActionId,
23
+ erc20TokenAddressLength,
24
+ calls.map(({ from, to, calldata, value }) => ({ from, to, calldata, value: `${value}` })),
25
+ gasAmount,
26
+ ));
27
+ } catch (error: unknown) {
28
+ logError('processGasEstimates error:', error);
29
+ }
30
+
31
+ const priceOfTransactionInToken = priceOfTransactionInTokenEstimate
32
+ ? getAmountInWei(tokenForGasFee, getValueFirstNDigit(priceOfTransactionInTokenEstimate, tokenForGasFee.decimals))
33
+ : undefined; // in wei
34
+
35
+ return { priceOfTransactionInUSD, priceOfTransactionInToken };
36
+ };
@@ -0,0 +1,15 @@
1
+ import { IHinkal } from '../../data-structures/Hinkal/IHinkal';
2
+
3
+ export const shouldPatchAccessTokenMerkleTree = async (
4
+ hinkal: IHinkal,
5
+ erc20Addresses: string[],
6
+ amountChanges: bigint[],
7
+ ) => {
8
+ const kycRequired = await hinkal.checkTokenRegistry(erc20Addresses, amountChanges);
9
+
10
+ const hasAccessToken = await hinkal.checkAccessToken();
11
+
12
+ // Note: we return hasAccessToken and kycRequired here as performance optimization
13
+ // so we don't have to fetch it again later and waste a network request
14
+ return { patchAccessTokenMerkleTree: kycRequired && !hasAccessToken, hasAccessToken, kycRequired };
15
+ };
@@ -0,0 +1,296 @@
1
+ import { BigNumber, Contract, ContractTransaction, ethers, utils } from 'ethers';
2
+ import { zeroAddress } from '../../constants/protocol.constants';
3
+ import { IHinkal } from '../../data-structures/Hinkal/IHinkal';
4
+ import { ContractType } from '../../types/ethereum-network.types';
5
+ import { caseInsensitiveEqual, createTorRpcProvider, replaceAllInstances } from '../utils';
6
+ import { replaceAddressesInCalldata } from '../utils/replaceAddressInCalldata';
7
+ import { UserKeys } from '../../data-structures/crypto-keys/keys';
8
+ import { Logger } from '../../error-handling/logger';
9
+ import { type AuthorizationData } from '../../types/hinkal.types';
10
+ import { chainIds, networkRegistry } from '../../constants/chains.constants';
11
+ import { ethers as ethersV6 } from 'ethers-v6h';
12
+
13
+ export const emporiumOp = <
14
+ ContractInstance extends Contract,
15
+ ContractFunctions extends ContractInstance['functions'],
16
+ ExactFunction extends {
17
+ [K in keyof ContractFunctions]: ReturnType<ContractFunctions[K]> extends Promise<ContractTransaction> ? K : never;
18
+ }[keyof ContractFunctions],
19
+ FunctionArguments extends Parameters<ContractFunctions[ExactFunction]>,
20
+ >({
21
+ contract,
22
+ func,
23
+ args,
24
+ callDataString,
25
+ invokeWallet,
26
+ value,
27
+ }: {
28
+ contract: ContractInstance | string;
29
+ func?: ExactFunction;
30
+ args?: FunctionArguments extends [] ? [] : FunctionArguments;
31
+ callDataString?: string;
32
+ invokeWallet?: boolean;
33
+ value?: bigint;
34
+ }): string => {
35
+ let endpointBytes: Uint8Array = new Uint8Array();
36
+ let callDataBytes = callDataString ? utils.arrayify(callDataString) : new Uint8Array();
37
+
38
+ if (typeof contract === 'object' && 'address' in contract) {
39
+ endpointBytes = utils.arrayify(contract.address);
40
+
41
+ if (callDataString?.length && callDataString?.length > 0) {
42
+ throw Error('If function and args are providedm no calldata is needed');
43
+ }
44
+ if (func && args && !callDataString) {
45
+ callDataBytes = utils.arrayify(contract.interface.encodeFunctionData(func as string, args));
46
+ }
47
+ } else {
48
+ endpointBytes = utils.arrayify(contract);
49
+ }
50
+ const invokeWalletByte = utils.arrayify([invokeWallet ? 1 : 0]);
51
+ const valueBytes = utils.zeroPad(utils.arrayify(BigNumber.from(value ?? 0n)), 16);
52
+
53
+ const dataBytes = utils.concat([endpointBytes, invokeWalletByte, valueBytes, callDataBytes]);
54
+ return utils.hexlify(dataBytes);
55
+ };
56
+
57
+ export const encodeEmporiumMetadata = async (
58
+ chainId: number,
59
+ emporiumAddress: string,
60
+ privateKey: string | undefined,
61
+ ops: string[],
62
+ message?: bigint,
63
+ signerAddress?: string,
64
+ ) => {
65
+ const signature = privateKey
66
+ ? await UserKeys.signTypedDataFromPrivateKey(
67
+ privateKey,
68
+ { name: 'Emporium', version: '1.0.0', chainId, verifyingContract: emporiumAddress },
69
+ { EmporiumSignature: [{ name: 'message', type: 'uint256' }] },
70
+ { message },
71
+ )
72
+ : undefined;
73
+
74
+ const { v, r, s } = signature ? utils.splitSignature(signature) : { v: 0, r: '0x', s: '0x' };
75
+
76
+ return utils.defaultAbiCoder.encode(
77
+ ['tuple(uint8 v,bytes32 r, bytes32 s, uint256 message, address signerAddress, bytes[] ops)'],
78
+ [
79
+ {
80
+ v,
81
+ r,
82
+ s,
83
+ message: message ?? 0n,
84
+ signerAddress: signerAddress ?? zeroAddress,
85
+ ops,
86
+ },
87
+ ],
88
+ );
89
+ };
90
+
91
+ export const createTransferToEmporiumOp = (
92
+ tokenContract: ethers.Contract | undefined,
93
+ to: string,
94
+ amount: bigint,
95
+ invokeWallet: boolean,
96
+ ) => {
97
+ if (!tokenContract) {
98
+ return emporiumOp({ contract: to, value: amount, invokeWallet });
99
+ }
100
+ return emporiumOp({
101
+ contract: tokenContract,
102
+ func: 'transfer',
103
+ args: [to, amount],
104
+ invokeWallet,
105
+ });
106
+ };
107
+
108
+ export const createTransaferEmporiumOpsBatch = (
109
+ hinkal: IHinkal,
110
+ erc20TokenAddresses: string[],
111
+ amounts: bigint[],
112
+ to?: string,
113
+ ) => {
114
+ const hinkalContract = hinkal.getContractWithFetcher(ContractType.HinkalContract);
115
+
116
+ return erc20TokenAddresses.map((erc20Address, index) => {
117
+ const tokenContract = caseInsensitiveEqual(erc20Address, zeroAddress)
118
+ ? undefined
119
+ : hinkal.getContractWithFetcher(ContractType.ERC20Contract, erc20Address);
120
+
121
+ return createTransferToEmporiumOp(tokenContract, to ?? hinkalContract.address, amounts[index], true);
122
+ });
123
+ };
124
+
125
+ export const createApproveEmporiumOp = (
126
+ tokenContract: ethers.Contract,
127
+ to: string,
128
+ amount: bigint,
129
+ invokeWallet: boolean,
130
+ ): string => {
131
+ return emporiumOp({
132
+ contract: tokenContract,
133
+ func: 'approve',
134
+ args: [to, amount],
135
+ invokeWallet,
136
+ });
137
+ };
138
+
139
+ export const modifyDataForProxy = (hinkal: IHinkal, userAddress: string, data: string) => {
140
+ const hinkalAddress = hinkal.getSelectedNetwork()?.contractData.hinkalAddress;
141
+ if (!hinkalAddress) {
142
+ throw Error('No Hinkal Address Provided to modifyDataForProxy');
143
+ }
144
+ return replaceAllInstances(data, hinkalAddress.slice(2), userAddress.slice(2));
145
+ };
146
+
147
+ export const modifyDataForProxyWithPrivateKey = (hinkal: IHinkal, privateKey: string | undefined, data: string) => {
148
+ if (!privateKey) {
149
+ throw Error('No private key provided to modifyDataForProxy');
150
+ }
151
+ const userAddress = UserKeys.getSignerAddressFromPrivateKey(privateKey);
152
+
153
+ return modifyDataForProxy(hinkal, userAddress, data);
154
+ };
155
+
156
+ export const generateFundAndApproveOps = (
157
+ hinkal: IHinkal,
158
+ erc20AddressesToFund: string[],
159
+ fundAmounts: bigint[],
160
+ approveTokenAddresses: string[],
161
+ approveAmounts: bigint[],
162
+ walletAddress: string,
163
+ spenderAddress: string | undefined,
164
+ ) => {
165
+ const emporiumOps = [];
166
+
167
+ for (let i = 0; i < erc20AddressesToFund.length; i += 1) {
168
+ const tokenAddress = erc20AddressesToFund[i];
169
+ const tokenContract = caseInsensitiveEqual(tokenAddress, zeroAddress)
170
+ ? undefined
171
+ : hinkal.getContractWithFetcher(ContractType.ERC20Contract, tokenAddress);
172
+
173
+ emporiumOps.push(createTransferToEmporiumOp(tokenContract, walletAddress, fundAmounts[i], false));
174
+ }
175
+
176
+ if (spenderAddress) {
177
+ for (let i = 0; i < approveTokenAddresses.length; i += 1) {
178
+ const tokenAddress = approveTokenAddresses[i];
179
+ if (!caseInsensitiveEqual(tokenAddress, zeroAddress)) {
180
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, tokenAddress);
181
+ emporiumOps.push(createApproveEmporiumOp(tokenContract, spenderAddress, approveAmounts[i], true));
182
+ }
183
+ }
184
+ }
185
+
186
+ return emporiumOps;
187
+ };
188
+
189
+ export const generateFundApproveAndTransactOps = (
190
+ hinkal: IHinkal,
191
+ erc20AddressesToFund: string[],
192
+ fundAmounts: bigint[],
193
+ approveTokenAddresses: string[],
194
+ approveAmounts: bigint[],
195
+ walletAddress: string,
196
+ spenderAddress: string | undefined,
197
+ to?: string,
198
+ callDataString?: string,
199
+ value?: bigint,
200
+ ) => {
201
+ const emporiumOps = generateFundAndApproveOps(
202
+ hinkal,
203
+ erc20AddressesToFund,
204
+ fundAmounts,
205
+ approveTokenAddresses,
206
+ approveAmounts,
207
+ walletAddress,
208
+ spenderAddress,
209
+ );
210
+
211
+ const isWithTransact = !!to && !!callDataString;
212
+
213
+ if (isWithTransact) {
214
+ const hinkalContract = hinkal.getContractWithFetcher(ContractType.HinkalContract);
215
+
216
+ emporiumOps.push(
217
+ emporiumOp({
218
+ contract: to,
219
+ callDataString: replaceAddressesInCalldata(callDataString, hinkalContract.address, walletAddress),
220
+ value,
221
+ invokeWallet: true,
222
+ }),
223
+ );
224
+ }
225
+
226
+ return emporiumOps;
227
+ };
228
+
229
+ // EIP-7702 delegation marker - the bytecode starts with this prefix
230
+ const EIP_7702_MAGIC = '0xef0100'; // EF01 (magic) + 00 (version)
231
+
232
+ export const checkEOAWithDelegation = async (chainId: number, eoaAddress: string) => {
233
+ try {
234
+ const { fetchRpcUrl } = networkRegistry[chainId];
235
+ if (!fetchRpcUrl) throw new Error('RPC URL not found for the specified chain ID');
236
+
237
+ const provider = createTorRpcProvider(fetchRpcUrl);
238
+ const code: string | undefined = await provider.getCode(eoaAddress);
239
+
240
+ // No code = no designation
241
+ if (code === '0x' || !code) return { delegated: false, implementation: undefined, nonce: undefined };
242
+
243
+ // 7702 stub is exactly 23 bytes (0xef0100 + 20-byte address)
244
+ if (code.toLowerCase().startsWith(EIP_7702_MAGIC) && code.length === 2 + 46) {
245
+ const impl = `0x${code.slice(8)}`; // drop 0x ef0100
246
+ const nonce = await provider.getTransactionCount(eoaAddress);
247
+ return { delegated: true, implementation: utils.getAddress(impl), nonce };
248
+ } else {
249
+ throw Error('checkEOAWithDelegation: It is a contract');
250
+ }
251
+ } catch (error) {
252
+ Logger.error('checkEOAWithDelegation error', { error });
253
+ throw error;
254
+ }
255
+ };
256
+
257
+ const getHinkalWalletImplementation = (chainId: number) => {
258
+ const { hinkalWalletAddress } = networkRegistry[chainId].contractData;
259
+ if (!hinkalWalletAddress || caseInsensitiveEqual(hinkalWalletAddress, zeroAddress)) {
260
+ throw Error('Hinkal Wallet Address is not set');
261
+ }
262
+
263
+ return hinkalWalletAddress;
264
+ };
265
+
266
+ export const getAuthorizationDataIfNeeded = async (chainId: number, privateKey: string | undefined) => {
267
+ // useful for tests, hardhat network doesn't support EIP7702
268
+ // in tests we use setCode to emulate EIP7702 behaviour
269
+ if (chainId === chainIds.localhost) return undefined;
270
+ if (!privateKey) return undefined;
271
+ const eoaAddress = UserKeys.getSignerAddressFromPrivateKey(privateKey);
272
+ const { delegated, implementation: oldImplementation } = await checkEOAWithDelegation(chainId, eoaAddress);
273
+ const implementation = getHinkalWalletImplementation(chainId);
274
+ if (!delegated || !caseInsensitiveEqual(oldImplementation, implementation)) {
275
+ const auth = await UserKeys.authorizeDelegationFromPrivateKey(privateKey, chainId, implementation);
276
+ const authData: AuthorizationData = {
277
+ v: auth.signature.v.toString(),
278
+ r: auth.signature.r,
279
+ s: auth.signature.s,
280
+ nonce: auth.nonce.toString(),
281
+ address: implementation,
282
+ chainId: String(chainId),
283
+ };
284
+ return authData;
285
+ }
286
+ return undefined;
287
+ };
288
+
289
+ export const recoverAuthorizationData = (
290
+ authorizationData: AuthorizationData | undefined,
291
+ ): ethersV6.Authorization | undefined => {
292
+ if (!authorizationData) return undefined;
293
+ const { v, r, s, nonce, chainId, address } = authorizationData;
294
+ const signature = ethersV6.Signature.from({ v, r, s });
295
+ return { signature, nonce: BigInt(nonce), chainId: BigInt(chainId), address };
296
+ };
@@ -0,0 +1,284 @@
1
+ import { BigNumber, ethers } from 'ethers';
2
+ import { createApproveEmporiumOp, emporiumOp } from './emporium.helpers';
3
+ import {
4
+ NATIVE_TOKEN_WRAPPER_ADDRESSES,
5
+ SWAP_FEE_TAKER_ADDRESSES,
6
+ WRAPPER_TOKEN_EXCHANGE_ADDRESSES,
7
+ } from '../../constants/addresses.constants';
8
+ import { IHinkal } from '../../data-structures/Hinkal/IHinkal';
9
+ import { ExternalActionId } from '../../types/external-action.types';
10
+ import { ContractType } from '../../types/ethereum-network.types';
11
+ import { getExternalSwapAddress } from '../pre-transaction/getExternalSwapAddress';
12
+ import { replaceAllInstances } from '../utils/string.utils';
13
+ import { HINKAL_SWAP_VARIABLE_RATE, zeroAddress } from '../../constants/protocol.constants';
14
+ import { getERC20Registry } from '../../constants/token-data';
15
+ import { caseInsensitiveEqual } from '../utils/caseInsensitive.utils';
16
+ import { Logger } from '../../error-handling/logger';
17
+
18
+ export const createSwapToEmporiumOpForUniswap = (
19
+ routerAddress: string,
20
+ inputTokenAddress: string,
21
+ positiveAmountInput: bigint,
22
+ outputTokenAddress: string,
23
+ recipient: string,
24
+ data: string,
25
+ invokeWallet = false,
26
+ ) => {
27
+ const fee = BigNumber.from(data).toBigInt();
28
+ const exactInputSingleParams = {
29
+ tokenIn: inputTokenAddress,
30
+ tokenOut: outputTokenAddress,
31
+ fee,
32
+ recipient,
33
+ amountIn: positiveAmountInput,
34
+ amountOutMinimum: 0,
35
+ sqrtPriceLimitX96: 0,
36
+ };
37
+
38
+ const routerAbi = [
39
+ 'function exactInputSingle(tuple(address tokenIn,address tokenOut,uint24 fee,address recipient,uint256 amountIn,uint256 amountOutMinimum,uint160 sqrtPriceLimitX96)) external payable returns (uint256 amountOut)',
40
+ ];
41
+
42
+ const uniswap = new ethers.Contract(routerAddress, routerAbi);
43
+ return emporiumOp({
44
+ contract: uniswap,
45
+ func: 'exactInputSingle',
46
+ args: [exactInputSingleParams],
47
+ invokeWallet,
48
+ });
49
+ };
50
+
51
+ export const createSwapToEmporiumOpFromData = (
52
+ hinkal: IHinkal,
53
+ externalActionId: ExternalActionId,
54
+ routerAddress: string,
55
+ data: string,
56
+ walletAddress: string,
57
+ value?: bigint,
58
+ invokeWallet = false,
59
+ ) => {
60
+ const externalAddress = getExternalSwapAddress(hinkal, externalActionId);
61
+ const modifiedData = replaceAllInstances(data, externalAddress.slice(2), walletAddress.slice(2));
62
+
63
+ return emporiumOp({
64
+ contract: routerAddress,
65
+ callDataString: modifiedData,
66
+ value,
67
+ invokeWallet,
68
+ });
69
+ };
70
+
71
+ export const nullifyApprovalBeforeSwap = async (
72
+ hinkal: IHinkal,
73
+ ops: string[],
74
+ tokenContract: ethers.Contract,
75
+ walletAddress: string,
76
+ routerAddress: string,
77
+ invokeWallet: boolean,
78
+ ) => {
79
+ const tokenAddress = tokenContract.address;
80
+ const tokenRegistry = getERC20Registry(hinkal.getCurrentChainId());
81
+ const usdtToken = tokenRegistry.find((token) => token.symbol === 'USDT');
82
+
83
+ if (!usdtToken) return;
84
+ if (caseInsensitiveEqual(tokenAddress, usdtToken.erc20TokenAddress)) {
85
+ try {
86
+ const allowance: BigNumber = await tokenContract['allowance'](walletAddress, routerAddress);
87
+ if (allowance.toBigInt() > 0n) {
88
+ ops.push(createApproveEmporiumOp(tokenContract, routerAddress, 0n, invokeWallet));
89
+ }
90
+ } catch (error) {
91
+ Logger.error('Error in nullifyApprovalBeforeSwap', error);
92
+ }
93
+ }
94
+ };
95
+
96
+ const takeSwapFee = async (
97
+ hinkal: IHinkal,
98
+ outputTokenAddress: string,
99
+ walletAddress: string,
100
+ relay: string,
101
+ ops: string[],
102
+ invokeWallet: boolean,
103
+ outputAmount: bigint,
104
+ ) => {
105
+ if (outputTokenAddress !== zeroAddress) {
106
+ // we want to apply some variable fee to the swap
107
+ const swapFeeTakerAddress = SWAP_FEE_TAKER_ADDRESSES[hinkal.getCurrentChainId()];
108
+ const outputTokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, outputTokenAddress);
109
+ const balanceOfOutputTokenBefore: BigNumber = await outputTokenContract['balanceOf'](walletAddress);
110
+
111
+ ops.push(createApproveEmporiumOp(outputTokenContract, swapFeeTakerAddress, 2n ** 256n - 1n, invokeWallet));
112
+
113
+ const swapFeeTakerAbi = [
114
+ 'function takeSwapFee(address token, uint256 beforeBalance, uint256 variableRate, address relay) external payable',
115
+ ];
116
+ const swapFeeTakerContract = new ethers.Contract(swapFeeTakerAddress, swapFeeTakerAbi);
117
+ const receiver = relay;
118
+ ops.push(
119
+ emporiumOp({
120
+ contract: swapFeeTakerContract,
121
+ func: 'takeSwapFee',
122
+ args: [outputTokenAddress, balanceOfOutputTokenBefore, HINKAL_SWAP_VARIABLE_RATE, receiver],
123
+ invokeWallet,
124
+ }),
125
+ );
126
+ } else {
127
+ // Here we want to transfer the swapped native ETH output to the relayer
128
+ const receiver = relay;
129
+ ops.push(
130
+ emporiumOp({
131
+ contract: receiver,
132
+ value: (outputAmount * HINKAL_SWAP_VARIABLE_RATE) / 10000n,
133
+ invokeWallet,
134
+ }),
135
+ );
136
+ }
137
+ };
138
+
139
+ // OneInch and Lifi can deal with native Eth
140
+ // Uniswap and Odos needs wrapping
141
+ export const createSwapToEmporiumOps = async (
142
+ hinkal: IHinkal,
143
+ externalActionId: ExternalActionId,
144
+ routerAddress: string,
145
+ data: string,
146
+ inputTokenAddress: string,
147
+ inputAmount: bigint,
148
+ outputAmount: bigint | undefined,
149
+ outputTokenAddress: string | undefined,
150
+ isTheSameChainSwap: boolean,
151
+ walletAddress: string,
152
+ relay: string,
153
+ invokeWallet = false,
154
+ ) => {
155
+ const positiveAmountInput = inputAmount < 0n ? -1n * inputAmount : inputAmount;
156
+ const chainId = hinkal.getCurrentChainId();
157
+
158
+ const ops: string[] = [];
159
+ const wrapperAddress = NATIVE_TOKEN_WRAPPER_ADDRESSES[chainId];
160
+ let shouldUnwrap = false;
161
+ let swapOp;
162
+
163
+ // OneInch and Lifi
164
+ if (externalActionId === ExternalActionId.OneInch || externalActionId === ExternalActionId.Lifi) {
165
+ if (inputTokenAddress !== zeroAddress) {
166
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, inputTokenAddress);
167
+ ops.push(createApproveEmporiumOp(tokenContract, routerAddress, positiveAmountInput, invokeWallet));
168
+ }
169
+
170
+ // During bridging, LiFi may request an additional native token amount stored in outputAmount.
171
+ // Any native token required on either side input or output is accumulated into value.
172
+ let value = 0n;
173
+
174
+ if (inputTokenAddress === zeroAddress) {
175
+ value += positiveAmountInput;
176
+ }
177
+
178
+ if (outputAmount && outputTokenAddress === zeroAddress && outputAmount < 0n) {
179
+ value += -1n * outputAmount;
180
+ }
181
+
182
+ const finalValue = value > 0n ? value : undefined;
183
+
184
+ swapOp = createSwapToEmporiumOpFromData(
185
+ hinkal,
186
+ externalActionId,
187
+ routerAddress,
188
+ data,
189
+ walletAddress,
190
+ finalValue,
191
+ invokeWallet,
192
+ );
193
+ ops.push(swapOp);
194
+
195
+ if (
196
+ (externalActionId === ExternalActionId.OneInch ||
197
+ (isTheSameChainSwap && externalActionId === ExternalActionId.Lifi)) &&
198
+ outputTokenAddress &&
199
+ outputAmount !== undefined
200
+ ) {
201
+ await takeSwapFee(hinkal, outputTokenAddress, walletAddress, relay, ops, invokeWallet, outputAmount);
202
+ }
203
+
204
+ return ops;
205
+ }
206
+
207
+ if (!outputTokenAddress || !outputAmount) throw Error('There should be output token for UniSwap and Odos');
208
+
209
+ // Uniswap and ODOS case
210
+ if (inputTokenAddress === zeroAddress) {
211
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, wrapperAddress);
212
+ ops.push(
213
+ emporiumOp({
214
+ contract: tokenContract,
215
+ func: 'deposit',
216
+ value: positiveAmountInput,
217
+ invokeWallet,
218
+ }),
219
+ );
220
+ inputTokenAddress = wrapperAddress;
221
+ }
222
+
223
+ let wrappedTokenBalanceBefore = 0n;
224
+
225
+ if (outputTokenAddress === zeroAddress) {
226
+ outputTokenAddress = wrapperAddress;
227
+ shouldUnwrap = true;
228
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, wrapperAddress);
229
+ wrappedTokenBalanceBefore = await tokenContract['balanceOf'](walletAddress);
230
+ }
231
+
232
+ if (inputTokenAddress !== zeroAddress) {
233
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, inputTokenAddress);
234
+ // USDT needs to set approval to 0, before you increase it. If you already have positive approval to Odos and then you try to increase it, it will fail
235
+ await nullifyApprovalBeforeSwap(hinkal, ops, tokenContract, walletAddress, routerAddress, invokeWallet);
236
+ ops.push(createApproveEmporiumOp(tokenContract, routerAddress, positiveAmountInput, invokeWallet));
237
+ }
238
+
239
+ if (externalActionId === ExternalActionId.Uniswap) {
240
+ swapOp = createSwapToEmporiumOpForUniswap(
241
+ routerAddress,
242
+ inputTokenAddress,
243
+ positiveAmountInput,
244
+ outputTokenAddress,
245
+ walletAddress,
246
+ data,
247
+ invokeWallet,
248
+ );
249
+ } else {
250
+ swapOp = createSwapToEmporiumOpFromData(
251
+ hinkal,
252
+ externalActionId,
253
+ routerAddress,
254
+ data,
255
+ walletAddress,
256
+ undefined,
257
+ invokeWallet,
258
+ );
259
+ }
260
+ ops.push(swapOp);
261
+
262
+ await takeSwapFee(hinkal, outputTokenAddress, walletAddress, relay, ops, invokeWallet, outputAmount);
263
+
264
+ // finally we unwrap the wrapped eth to native
265
+ if (shouldUnwrap) {
266
+ const wrapperExchangeContract = WRAPPER_TOKEN_EXCHANGE_ADDRESSES[chainId];
267
+
268
+ const tokenContract = hinkal.getContractWithFetcher(ContractType.ERC20Contract, wrapperAddress);
269
+ ops.push(createApproveEmporiumOp(tokenContract, wrapperExchangeContract, 2n ** 256n - 1n, invokeWallet));
270
+
271
+ const withdrawAbi = ['function withdrawBalanceDifference(uint256 beforeBalance) external'];
272
+ const withdrawContract = new ethers.Contract(wrapperExchangeContract, withdrawAbi);
273
+ ops.push(
274
+ emporiumOp({
275
+ contract: withdrawContract,
276
+ func: 'withdrawBalanceDifference',
277
+ args: [wrappedTokenBalanceBefore],
278
+ invokeWallet,
279
+ }),
280
+ );
281
+ }
282
+
283
+ return ops;
284
+ };
@@ -0,0 +1,3 @@
1
+ export * from './emporium.helpers';
2
+ export * from './opProducer';
3
+ export * from './emporium.swap.helpers';
@@ -0,0 +1,33 @@
1
+ import { ERC20ABI, ISwapRouterABI } from '../../externalABIs';
2
+ import { ethers } from 'ethers';
3
+ import { emporiumOp } from './emporium.helpers';
4
+
5
+ export enum OpType {
6
+ Erc20Token,
7
+ Uniswap,
8
+ }
9
+
10
+ export const produceOp = (
11
+ opType: OpType,
12
+ contractAddress: string,
13
+ func?: string,
14
+ args?: any[],
15
+ invokeWallet?: boolean,
16
+ value?: bigint,
17
+ ): string => {
18
+ let abi: ethers.ContractInterface = '';
19
+ switch (opType) {
20
+ case OpType.Erc20Token:
21
+ abi = ERC20ABI;
22
+ break;
23
+ case OpType.Uniswap:
24
+ abi = ISwapRouterABI;
25
+ break;
26
+ default:
27
+ break;
28
+ }
29
+ if (!abi) throw Error('No ABI match in produceOp');
30
+
31
+ const contract = new ethers.Contract(contractAddress, abi);
32
+ return emporiumOp({ contract, func, args, invokeWallet, value });
33
+ };