web3.service.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. import { Inject, Injectable, InternalServerErrorException, Logger } from '@nestjs/common'
  2. import { ethers } from 'ethers'
  3. import { Wallet, Provider, utils } from 'zksync-web3'
  4. import { ConfigType } from '@nestjs/config'
  5. import { AccountsService } from '../accounts/accounts.service'
  6. import erc20 from './erc20.json'
  7. import { web3Config } from './web3config'
  8. import {
  9. ChainId,
  10. initialChainTable,
  11. getGasToken,
  12. point2PriceDecimal,
  13. priceDecimal2Point,
  14. pointDeltaRoundingDown,
  15. pointDeltaRoundingUp,
  16. amount2Decimal,
  17. PriceRoundingType,
  18. fetchToken,
  19. getErc20TokenContract
  20. } from 'iziswap-sdk/lib/base'
  21. import Web3 from 'web3'
  22. import { BigNumber } from 'bignumber.js'
  23. import {} from 'iziswap-sdk/lib/quoter'
  24. import {} from 'iziswap-sdk/lib/swap'
  25. import {
  26. calciZiLiquidityAmountDesired,
  27. getMintCall,
  28. getLiquidityManagerContract,
  29. getPoolAddress,
  30. fetchLiquiditiesOfAccount,
  31. getDecLiquidityCall,
  32. DecLiquidityParam,
  33. getWithdrawLiquidityValue
  34. } from 'iziswap-sdk/lib/liquidityManager'
  35. import { getPoolContract, getPoolState, getPointDelta } from 'iziswap-sdk/lib/pool'
  36. import {
  37. getQuoterContract,
  38. quoterSwapChainWithExactOutput,
  39. quoterSwapChainWithExactInput
  40. } from 'iziswap-sdk/lib/quoter'
  41. import { getSwapContract, getSwapChainWithExactOutputCall, getSwapChainWithExactInputCall } from 'iziswap-sdk/lib/swap'
  42. import mintSquareAbi from './mintSquareAbi.json'
  43. import { Network } from './network.enum'
  44. import { Cron } from '@nestjs/schedule'
  45. import { Web3Result } from './model/web3-result'
  46. import { FileService } from 'src/file/file.service'
  47. import axios from 'axios'
  48. import * as randomString from 'randomstring'
  49. @Injectable()
  50. export class Web3Service {
  51. constructor(private readonly accountService: AccountsService, private readonly fileService: FileService) {}
  52. async zkDeposit(accountId, amount) {
  53. const account = await this.accountService.findById(accountId)
  54. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  55. const ethProvider = new ethers.providers.InfuraProvider(
  56. web3Config[account.network].ethereumNetwork,
  57. web3Config[account.network].infuraApiKey
  58. )
  59. const wallet = new Wallet(account.privateKey, provider, ethProvider)
  60. const deposit = await wallet.deposit({
  61. token: utils.ETH_ADDRESS,
  62. amount: ethers.utils.parseEther(amount)
  63. })
  64. Logger.log('Deposit sent. Awaiting confirmation...')
  65. return new Web3Result(account.address, deposit.hash, web3Config[account.network], false)
  66. // // Await processing of the deposit on L1
  67. // const ethereumTxReceipt = await deposit.waitL1Commit()
  68. // Logger.log('L1 deposit confirmed! Waiting for zkSync...')
  69. // // Await processing the deposit on zkSync
  70. // const depositReceipt = await deposit.wait()
  71. // Logger.log('zkSync deposit committed.')
  72. // Logger.log('Checking zkSync account balance')
  73. // // Retrieving the current (committed) zkSync ETH balance of an account
  74. // const committedEthBalance = await wallet.getBalance()
  75. // Logger.log('committedEthBalance', ethers.utils.formatEther(committedEthBalance))
  76. // // Retrieving the ETH balance of an account in the last finalized zkSync block.
  77. // const finalizedEthBalance = await wallet.getBalance(utils.ETH_ADDRESS, 'finalized')
  78. // Logger.log('finalizedEthBalance', ethers.utils.formatEther(finalizedEthBalance))
  79. }
  80. async zkWithdraw(accountId, amount) {
  81. const account = await this.accountService.findById(accountId)
  82. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  83. const ethProvider = new ethers.providers.InfuraProvider(
  84. web3Config[account.network].ethereumNetwork,
  85. web3Config[account.network].infuraApiKey
  86. )
  87. const wallet = new Wallet(account.privateKey, provider, ethProvider)
  88. const withdrawL2 = await wallet.withdraw({
  89. token: utils.ETH_ADDRESS,
  90. amount: ethers.utils.parseEther(amount)
  91. })
  92. Logger.log(`Widthdraw sent. ${web3Config[account.network].zksyncExplorer}/tx/${withdrawL2.hash}`)
  93. return new Web3Result(account.address, withdrawL2.hash, web3Config[account.network], true)
  94. // // Await processing of the deposit on L1
  95. // const ethereumTxReceipt = await deposit.waitL1Commit()
  96. // Logger.log('L1 deposit confirmed! Waiting for zkSync...')
  97. // // Await processing the deposit on zkSync
  98. // const depositReceipt = await deposit.wait()
  99. // Logger.log('zkSync deposit committed.')
  100. // Logger.log('Checking zkSync account balance')
  101. // // Retrieving the current (committed) zkSync ETH balance of an account
  102. // const committedEthBalance = await wallet.getBalance()
  103. // Logger.log('committedEthBalance', ethers.utils.formatEther(committedEthBalance))
  104. // // Retrieving the ETH balance of an account in the last finalized zkSync block.
  105. // const finalizedEthBalance = await wallet.getBalance(utils.ETH_ADDRESS, 'finalized')
  106. // Logger.log('finalizedEthBalance', ethers.utils.formatEther(finalizedEthBalance))
  107. }
  108. async orbiterDeposit(accountId, amount) {
  109. const account = await this.accountService.findById(accountId)
  110. const provider = new ethers.providers.InfuraProvider(
  111. web3Config[account.network].ethereumNetwork,
  112. web3Config[account.network].infuraApiKey
  113. )
  114. const wallet = new ethers.Wallet(account.privateKey, provider)
  115. const tx = await wallet.sendTransaction({
  116. from: wallet.address,
  117. to: web3Config[account.network].orbiterEthAddress,
  118. value: ethers.utils.parseEther(amount).add(web3Config[account.network].orbiterIdCodeZk)
  119. })
  120. return new Web3Result(account.address, tx.hash, web3Config[account.network], false)
  121. }
  122. async orbiterWithdraw(accountId, amount) {
  123. const account = await this.accountService.findById(accountId)
  124. const provider = new ethers.providers.InfuraProvider(
  125. web3Config[account.network].ethereumNetwork,
  126. web3Config[account.network].infuraApiKey
  127. )
  128. const wallet = new ethers.Wallet(account.privateKey, provider)
  129. const tx = await wallet.sendTransaction({
  130. from: wallet.address,
  131. to: web3Config[account.network].orbiterZkAddress,
  132. value: ethers.utils.parseEther(amount).add(web3Config[account.network].orbiterIdCodeEth)
  133. })
  134. return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
  135. }
  136. async addLiquidity(accountId, amount) {
  137. const account = await this.accountService.findById(accountId)
  138. const chainId =
  139. web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
  140. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  141. const zkWallet = new Wallet(account.privateKey).connect(provider)
  142. const chain = initialChainTable[chainId]
  143. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
  144. console.log('address: ', zkWallet.address)
  145. const liquidityManagerContract = getLiquidityManagerContract(
  146. web3Config[account.network].liquidityManagerAddress,
  147. web3 as any
  148. )
  149. console.log('liquidity manager address: ', web3Config[account.network].liquidityManagerAddress)
  150. const tokenA = getGasToken(chainId)
  151. console.log('tokenA: ', tokenA)
  152. const tokenB = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
  153. console.log('tokenB: ', tokenB)
  154. await this.approve(
  155. tokenB.address,
  156. web3Config[account.network].liquidityManagerAddress,
  157. zkWallet,
  158. account.network
  159. )
  160. const fee = 2000 // 2000 means 0.2%
  161. const poolAddress = await getPoolAddress(liquidityManagerContract, tokenA, tokenB, fee)
  162. console.log('pool address: ', poolAddress)
  163. const poolContract = getPoolContract(poolAddress, web3 as any)
  164. const state = await getPoolState(poolContract)
  165. const currentPrice = point2PriceDecimal(tokenA, tokenB, state.currentPoint)
  166. Logger.log(`current price: 1${tokenA.symbol}=${currentPrice}${tokenB.symbol}`, 'addLiquidity')
  167. const point1 = priceDecimal2Point(tokenA, tokenB, currentPrice * 0.98, PriceRoundingType.PRICE_ROUNDING_NEAREST)
  168. const point2 = priceDecimal2Point(tokenA, tokenB, currentPrice * 1.02, PriceRoundingType.PRICE_ROUNDING_NEAREST)
  169. console.log('point range', point1, point2)
  170. let leftPoint = Math.min(point1, point2)
  171. let rightPoint = Math.max(point1, point2)
  172. const pointDelta = await getPointDelta(poolContract)
  173. console.log('point delta: ', pointDelta)
  174. leftPoint = pointDeltaRoundingDown(leftPoint, pointDelta)
  175. rightPoint = pointDeltaRoundingUp(rightPoint, pointDelta)
  176. const maxTestA = new BigNumber(amount).times(10 ** tokenA.decimal)
  177. const maxTestB = calciZiLiquidityAmountDesired(
  178. leftPoint,
  179. rightPoint,
  180. state.currentPoint,
  181. maxTestA,
  182. true,
  183. tokenA,
  184. tokenB
  185. )
  186. const mintParams = {
  187. tokenA: tokenA,
  188. tokenB: tokenB,
  189. fee,
  190. leftPoint,
  191. rightPoint,
  192. maxAmountA: maxTestA.toFixed(0),
  193. maxAmountB: maxTestB.toFixed(0),
  194. minAmountA: maxTestA.times(0.985).toFixed(0),
  195. minAmountB: maxTestB.times(0.985).toFixed(0)
  196. }
  197. console.log(JSON.stringify(mintParams, null, 4))
  198. console.log(amount2Decimal(new BigNumber(maxTestB), tokenB))
  199. const gasPrice = await web3.eth.getGasPrice()
  200. const { mintCalling, options } = getMintCall(
  201. liquidityManagerContract,
  202. zkWallet.address,
  203. chain,
  204. mintParams,
  205. gasPrice.toString()
  206. )
  207. let calling = mintCalling
  208. if (calling instanceof Array) {
  209. calling = liquidityManagerContract.methods.multicall(mintCalling)
  210. }
  211. console.log({ ...options, from: zkWallet.address })
  212. const gasLimit = await calling.estimateGas({ from: zkWallet.address })
  213. console.log('gas limit: ', gasLimit)
  214. // sign transaction
  215. const tx = await zkWallet.sendTransaction({
  216. from: options.from,
  217. value: Web3.utils.numberToHex(options.value),
  218. to: web3Config[account.network].liquidityManagerAddress,
  219. data: calling.encodeABI(),
  220. gasLimit
  221. })
  222. console.log('tx: ', tx)
  223. return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
  224. }
  225. async removeLiquidity(accountId) {
  226. const account = await this.accountService.findById(accountId)
  227. const chainId =
  228. web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
  229. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  230. const wallet = new Wallet(account.privateKey).connect(provider)
  231. const chain = initialChainTable[chainId]
  232. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
  233. const liquidityManagerContract = getLiquidityManagerContract(
  234. web3Config[account.network].liquidityManagerAddress,
  235. web3 as any
  236. )
  237. Logger.log('liquidity manager address: ', web3Config[account.network].liquidityManagerAddress)
  238. const tokenA = getGasToken(chainId)
  239. const tokenB = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
  240. Logger.log(`tokenA: ${tokenA.symbol} tokenB: ${tokenB.symbol}`, 'FetchLiquidities')
  241. const liquidities = await fetchLiquiditiesOfAccount(
  242. chain,
  243. web3 as any,
  244. liquidityManagerContract,
  245. account.address,
  246. [tokenA, tokenB]
  247. )
  248. Logger.log(`${liquidities.length} liquidities fetched`, 'FetchLiquidities')
  249. if (liquidities.length <= 0) {
  250. throw new InternalServerErrorException('No liquidity found')
  251. }
  252. const liquidity0 = liquidities.filter((i) => Number(i.liquidity) > 0)[0]
  253. if (!liquidity0) {
  254. throw new InternalServerErrorException('all liquidities are removed')
  255. }
  256. const decRate = 1
  257. const originLiquidity = new BigNumber(liquidity0.liquidity)
  258. const decLiquidity = originLiquidity.times(decRate)
  259. const { amountX, amountY } = getWithdrawLiquidityValue(liquidity0, liquidity0.state, decLiquidity)
  260. // here the slippery is 1.5%
  261. const minAmountX = amountX.times(0.985).toFixed(0)
  262. const minAmountY = amountY.times(0.985).toFixed(0)
  263. const gasPrice = await web3.eth.getGasPrice()
  264. const { decLiquidityCalling, options } = getDecLiquidityCall(
  265. liquidityManagerContract,
  266. account.address,
  267. chain,
  268. {
  269. tokenId: liquidity0.tokenId,
  270. liquidDelta: decLiquidity.toFixed(0),
  271. minAmountX,
  272. minAmountY
  273. } as DecLiquidityParam,
  274. gasPrice.toString()
  275. )
  276. const gasLimit = await decLiquidityCalling.estimateGas(options)
  277. console.log('gas limit: ', gasLimit)
  278. const tx0 = await wallet.sendTransaction({
  279. from: wallet.address,
  280. to: web3Config[account.network].liquidityManagerAddress,
  281. data: decLiquidityCalling.encodeABI(),
  282. gasLimit
  283. })
  284. console.log('decLiquidityCalling tx: ', JSON.stringify(tx0, null, 4))
  285. return new Web3Result(account.address, tx0.hash, web3Config[account.network], true)
  286. }
  287. async allowance(tokenAddress, spender, wallet: Wallet, network: Network): Promise<number> {
  288. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[network].zksyncRpcUrl))
  289. const tokenAContract = new web3.eth.Contract(erc20, tokenAddress)
  290. // @ts-ignore
  291. const allowanceCalling = tokenAContract.methods.allowance(wallet.address, spender)
  292. const out = await allowanceCalling.call()
  293. Logger.log(`allowance: ${out} hex: ${Web3.utils.numberToHex(out + '')}`, 'GetAllowance')
  294. return out as unknown as number
  295. }
  296. async approve(tokenAddress, spender, wallet: Wallet, network: Network) {
  297. const allowance = await this.allowance(tokenAddress, spender, wallet, network)
  298. if (allowance > 0) {
  299. return
  300. }
  301. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[network].zksyncRpcUrl))
  302. const tokenAContract = new web3.eth.Contract(erc20, tokenAddress)
  303. // @ts-ignore
  304. const approveCalling = tokenAContract.methods.approve(spender, '0xffffffffffffffffffffffffffffffff')
  305. let gasLimit = await approveCalling.estimateGas({ from: wallet.address })
  306. console.log('approve gas limit: ', gasLimit)
  307. const tx0 = await wallet.sendTransaction({
  308. from: wallet.address,
  309. to: tokenAddress,
  310. data: approveCalling.encodeABI(),
  311. gasLimit
  312. })
  313. console.log('approve tx: ', JSON.stringify(tx0, null, 4))
  314. }
  315. async swapWithExactOutput(accountId, amount) {
  316. const account = await this.accountService.findById(accountId)
  317. const chainId =
  318. web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
  319. const chain = initialChainTable[chainId]
  320. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  321. const wallet = new Wallet(account.privateKey).connect(provider)
  322. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
  323. console.log('address: ', wallet.address)
  324. const balance = await web3.eth.getBalance(wallet.address)
  325. console.log('ethBalance: ' + Web3.utils.fromWei(balance, 'ether'))
  326. const fromToken = getGasToken(chainId)
  327. console.log('fromToken: ', fromToken)
  328. const toToken = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
  329. console.log('toToken: ', toToken)
  330. const fee = 2000 // 2000 means 0.2%
  331. const toTokenContract = getErc20TokenContract(toToken.address, web3 as any)
  332. const toTokenBalance = await toTokenContract.methods.balanceOf(wallet.address).call()
  333. console.log(toToken.symbol + ' balance: ' + amount2Decimal(new BigNumber(toTokenBalance), toToken))
  334. const quoterContract = getQuoterContract(web3Config[account.network].quoterAddress, web3 as any)
  335. const receiveAmount = new BigNumber(amount).times(10 ** toToken.decimal)
  336. const params = {
  337. // pay testA to buy testB
  338. tokenChain: [fromToken, toToken],
  339. feeChain: [fee],
  340. outputAmount: receiveAmount.toFixed(0)
  341. }
  342. const { inputAmount } = await quoterSwapChainWithExactOutput(quoterContract, params)
  343. const payAmount = inputAmount
  344. const payAmountDecimal = amount2Decimal(new BigNumber(payAmount), fromToken)
  345. console.log(toToken.symbol + ' to desired: ', amount)
  346. console.log(fromToken.symbol + ' to pay: ', payAmountDecimal)
  347. const swapContract = getSwapContract(web3Config[account.network].swapAddress, web3 as any)
  348. const swapParams = {
  349. ...params,
  350. // slippery is 1.5%
  351. maxInputAmount: new BigNumber(payAmount).times(1.015).toFixed(0),
  352. strictERC20Token: false
  353. }
  354. const gasPrice = await web3.eth.getGasPrice()
  355. const { swapCalling, options } = getSwapChainWithExactOutputCall(
  356. swapContract,
  357. wallet.address,
  358. chain,
  359. swapParams,
  360. gasPrice.toString()
  361. )
  362. console.log(JSON.stringify({ swapCalling, options }, null, 4))
  363. const gasLimit = await swapCalling.estimateGas(options)
  364. console.log('gas limit: ', gasLimit)
  365. const tx = await wallet.sendTransaction({
  366. value: Web3.utils.numberToHex(options.value),
  367. data: swapCalling.encodeABI(),
  368. to: web3Config[account.network].swapAddress,
  369. gasLimit
  370. })
  371. console.log(tx)
  372. return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
  373. }
  374. async swapWithExactInput(accountId, amount) {
  375. const account = await this.accountService.findById(accountId)
  376. const chainId =
  377. web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
  378. const chain = initialChainTable[chainId]
  379. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  380. const wallet = new Wallet(account.privateKey).connect(provider)
  381. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
  382. console.log('address: ', wallet.address)
  383. const fromToken = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
  384. console.log('fromToken: ', fromToken)
  385. const toToken = getGasToken(chainId)
  386. console.log('toToken: ', toToken)
  387. await this.approve(fromToken.address, web3Config[account.network].swapAddress, wallet, account.network)
  388. const quoterContract = getQuoterContract(web3Config[account.network].quoterAddress, web3 as any)
  389. const payAmount = new BigNumber(amount).times(10 ** fromToken.decimal)
  390. const fee = 2000 // 2000 means 0.2%
  391. const params = {
  392. // pay testA to buy testB
  393. tokenChain: [fromToken, toToken],
  394. feeChain: [fee],
  395. inputAmount: payAmount.toFixed(0)
  396. }
  397. const { outputAmount } = await quoterSwapChainWithExactInput(quoterContract, params)
  398. const receiveAmount = outputAmount
  399. const receiveAmountDecimal = amount2Decimal(new BigNumber(receiveAmount), toToken)
  400. console.log(fromToken.symbol + ' to pay: ', amount)
  401. console.log(toToken.symbol + ' to acquire: ', receiveAmountDecimal)
  402. const swapContract = getSwapContract(web3Config[account.network].swapAddress, web3 as any)
  403. const swapParams = {
  404. ...params,
  405. // slippery is 1.5%
  406. minOutputAmount: new BigNumber(receiveAmount).times(0.985).toFixed(0),
  407. strictERC20Token: false
  408. }
  409. const gasPrice = await web3.eth.getGasPrice()
  410. const { swapCalling, options } = getSwapChainWithExactInputCall(
  411. swapContract,
  412. account.address,
  413. chain,
  414. swapParams,
  415. gasPrice.toString()
  416. )
  417. const gasLimit = await swapCalling.estimateGas(options)
  418. console.log('gas limit: ', gasLimit)
  419. const tx = await wallet.sendTransaction({
  420. value: Web3.utils.numberToHex(options.value),
  421. data: swapCalling.encodeABI(),
  422. to: web3Config[account.network].swapAddress,
  423. gasLimit
  424. })
  425. console.log(JSON.stringify(tx, null, 4))
  426. return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
  427. }
  428. async mint(accountId) {
  429. // const { data: buffer } = await axios.get('https://cataas.com/cat', {
  430. // responseType: 'arraybuffer'
  431. // })
  432. // const f = new FormData()
  433. // f.append('file', new Blob([buffer], { type: 'image/jpeg' }), 'cat.jpg')
  434. // const { data: image } = await axios.post('https://api.mintsquare.io/files/upload/', f)
  435. const f1 = new FormData()
  436. f1.append(
  437. 'file',
  438. new Blob([
  439. JSON.stringify({
  440. name: randomString.generate({ length: 8, charset: 'alphanumeric' }),
  441. attributes: [],
  442. image: 'https://mintsquare.sfo3.cdn.digitaloceanspaces.com/mintsquare/mintsquare/RJRohgvdN6xwSBvFefo8z6_1687229689762946549.jpg'
  443. })
  444. ])
  445. )
  446. const { data: res } = await axios.post('https://ipfs.infura.io:5001/api/v0/add', f1, {
  447. auth: {
  448. username: '2RrUoAzIHbABPzXlH4M7Rnc3Fir',
  449. password: 'aaa4218c6944d2b9ad706275e5f1d6f1'
  450. }
  451. })
  452. Logger.log(res)
  453. const account = await this.accountService.findById(accountId)
  454. const chainId =
  455. web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
  456. const chain = initialChainTable[chainId]
  457. const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
  458. const wallet = new Wallet(account.privateKey).connect(provider)
  459. const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
  460. console.log('address: ', wallet.address)
  461. const contract = new web3.eth.Contract(mintSquareAbi, web3Config[account.network].mintAddress, web3 as any)
  462. // @ts-ignore
  463. const mintCall = await contract.methods.mint(`ipfs://${res.Hash}`)
  464. Logger.log(`ipfs://${res.Hash}`, 'mint')
  465. const gasLimit = await mintCall.estimateGas({ from: wallet.address })
  466. console.log('gas limit: ', gasLimit)
  467. const tx = await wallet.sendTransaction({
  468. from: wallet.address,
  469. to: web3Config[account.network].mintAddress,
  470. data: mintCall.encodeABI(),
  471. gasLimit
  472. })
  473. console.log(tx)
  474. return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
  475. }
  476. }