| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605 |
- import { Inject, Injectable, InternalServerErrorException, Logger } from '@nestjs/common'
- import { ethers } from 'ethers'
- import { Wallet, Provider, utils } from 'zksync-web3'
- import { ConfigType } from '@nestjs/config'
- import { AccountsService } from '../accounts/accounts.service'
- import erc20 from './erc20.json'
- import { web3Config } from './web3config'
- import {
- ChainId,
- initialChainTable,
- getGasToken,
- point2PriceDecimal,
- priceDecimal2Point,
- pointDeltaRoundingDown,
- pointDeltaRoundingUp,
- amount2Decimal,
- PriceRoundingType,
- fetchToken,
- getErc20TokenContract,
- TokenInfoFormatted
- } from 'iziswap-sdk/lib/base'
- import Web3 from 'web3'
- import { BigNumber } from 'bignumber.js'
- import {} from 'iziswap-sdk/lib/quoter'
- import {} from 'iziswap-sdk/lib/swap'
- import {
- calciZiLiquidityAmountDesired,
- getMintCall,
- getLiquidityManagerContract,
- getPoolAddress,
- fetchLiquiditiesOfAccount,
- getDecLiquidityCall,
- DecLiquidityParam,
- getWithdrawLiquidityValue
- } from 'iziswap-sdk/lib/liquidityManager'
- import { getPoolContract, getPoolState, getPointDelta } from 'iziswap-sdk/lib/pool'
- import {
- getQuoterContract,
- quoterSwapChainWithExactOutput,
- quoterSwapChainWithExactInput
- } from 'iziswap-sdk/lib/quoter'
- import { getSwapContract, getSwapChainWithExactOutputCall, getSwapChainWithExactInputCall } from 'iziswap-sdk/lib/swap'
- import mintSquareAbi from './mintSquareAbi.json'
- import { Network } from './network.enum'
- import { Cron } from '@nestjs/schedule'
- import { Web3Result } from './model/web3-result'
- import { FileService } from 'src/file/file.service'
- import axios from 'axios'
- import * as randomString from 'randomstring'
- import { Account } from '../accounts/entities/account.entity'
- @Injectable()
- export class Web3Service {
- constructor(private readonly accountService: AccountsService, private readonly fileService: FileService) {}
- async zkDeposit(accountId, amount) {
- const account = await this.accountService.findById(accountId)
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const ethProvider = new ethers.providers.InfuraProvider(
- web3Config[account.network].ethereumNetwork,
- web3Config[account.network].infuraApiKey
- )
- const wallet = new Wallet(account.privateKey, provider, ethProvider)
- const deposit = await wallet.deposit({
- token: utils.ETH_ADDRESS,
- amount: ethers.utils.parseEther(amount)
- })
- Logger.log('Deposit sent. Awaiting confirmation...')
- account.offBridgeNum = (account.offBridgeNum || 0) + 1
- account.lastOffBridge = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, deposit.hash, web3Config[account.network], false)
- // // Await processing of the deposit on L1
- // const ethereumTxReceipt = await deposit.waitL1Commit()
- // Logger.log('L1 deposit confirmed! Waiting for zkSync...')
- // // Await processing the deposit on zkSync
- // const depositReceipt = await deposit.wait()
- // Logger.log('zkSync deposit committed.')
- // Logger.log('Checking zkSync account balance')
- // // Retrieving the current (committed) zkSync ETH balance of an account
- // const committedEthBalance = await wallet.getBalance()
- // Logger.log('committedEthBalance', ethers.utils.formatEther(committedEthBalance))
- // // Retrieving the ETH balance of an account in the last finalized zkSync block.
- // const finalizedEthBalance = await wallet.getBalance(utils.ETH_ADDRESS, 'finalized')
- // Logger.log('finalizedEthBalance', ethers.utils.formatEther(finalizedEthBalance))
- }
- async zkWithdraw(accountId, amount) {
- const account = await this.accountService.findById(accountId)
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const ethProvider = new ethers.providers.InfuraProvider(
- web3Config[account.network].ethereumNetwork,
- web3Config[account.network].infuraApiKey
- )
- const wallet = new Wallet(account.privateKey, provider, ethProvider)
- const withdrawL2 = await wallet.withdraw({
- token: utils.ETH_ADDRESS,
- amount: ethers.utils.parseEther(amount)
- })
- Logger.log(`Widthdraw sent. ${web3Config[account.network].zksyncExplorer}/tx/${withdrawL2.hash}`)
- account.offBridgeNum = (account.offBridgeNum || 0) + 1
- account.lastOffBridge = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, withdrawL2.hash, web3Config[account.network], true)
- // // Await processing of the deposit on L1
- // const ethereumTxReceipt = await deposit.waitL1Commit()
- // Logger.log('L1 deposit confirmed! Waiting for zkSync...')
- // // Await processing the deposit on zkSync
- // const depositReceipt = await deposit.wait()
- // Logger.log('zkSync deposit committed.')
- // Logger.log('Checking zkSync account balance')
- // // Retrieving the current (committed) zkSync ETH balance of an account
- // const committedEthBalance = await wallet.getBalance()
- // Logger.log('committedEthBalance', ethers.utils.formatEther(committedEthBalance))
- // // Retrieving the ETH balance of an account in the last finalized zkSync block.
- // const finalizedEthBalance = await wallet.getBalance(utils.ETH_ADDRESS, 'finalized')
- // Logger.log('finalizedEthBalance', ethers.utils.formatEther(finalizedEthBalance))
- }
- async orbiterDeposit(accountId, amount) {
- const account = await this.accountService.findById(accountId)
- const provider = new ethers.providers.InfuraProvider(
- web3Config[account.network].ethereumNetwork,
- web3Config[account.network].infuraApiKey
- )
- const wallet = new ethers.Wallet(account.privateKey, provider)
- const tx = await wallet.sendTransaction({
- from: wallet.address,
- to: web3Config[account.network].orbiterEthAddress,
- value: ethers.utils.parseEther(amount).add(web3Config[account.network].orbiterIdCodeZk)
- })
- account.thirdBridgeNum = (account.thirdBridgeNum || 0) + 1
- account.lastThirdBridge = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], false)
- }
- async orbiterWithdraw(accountId, amount) {
- const account = await this.accountService.findById(accountId)
- const provider = new ethers.providers.InfuraProvider(
- web3Config[account.network].ethereumNetwork,
- web3Config[account.network].infuraApiKey
- )
- const wallet = new ethers.Wallet(account.privateKey, provider)
- const tx = await wallet.sendTransaction({
- from: wallet.address,
- to: web3Config[account.network].orbiterZkAddress,
- value: ethers.utils.parseEther(amount).add(web3Config[account.network].orbiterIdCodeEth)
- })
- account.thirdBridgeNum = (account.thirdBridgeNum || 0) + 1
- account.lastThirdBridge = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
- }
- async addLiquidity(accountId, amount) {
- const account = await this.accountService.findById(accountId)
- const chainId =
- web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const zkWallet = new Wallet(account.privateKey).connect(provider)
- const chain = initialChainTable[chainId]
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
- Logger.log(`address: ${zkWallet.address}`, 'addLiquidity')
- const liquidityManagerContract = getLiquidityManagerContract(
- web3Config[account.network].liquidityManagerAddress,
- web3 as any
- )
- const tokenA = getGasToken(chainId)
- Logger.log(`tokenA: ${JSON.stringify(tokenA, null, 4)}`, 'addLiquidity')
- const tokenB = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- Logger.log(`tokenB: ${JSON.stringify(tokenB, null, 4)}`, 'addLiquidity')
- await this.approve(
- tokenB.address,
- web3Config[account.network].liquidityManagerAddress,
- zkWallet,
- account.network
- )
- const fee = 2000 // 2000 means 0.2%
- const poolAddress = await getPoolAddress(liquidityManagerContract, tokenA, tokenB, fee)
- Logger.log(`poolAddress: ${poolAddress}`, 'addLiquidity')
- const poolContract = getPoolContract(poolAddress, web3 as any)
- const state = await getPoolState(poolContract)
- const currentPrice = point2PriceDecimal(tokenA, tokenB, state.currentPoint)
- Logger.log(`current point: ${state.currentPoint}`, 'addLiquidity')
- const point1 = priceDecimal2Point(tokenA, tokenB, currentPrice * 0.98, PriceRoundingType.PRICE_ROUNDING_NEAREST)
- const point2 = priceDecimal2Point(tokenA, tokenB, currentPrice * 1.02, PriceRoundingType.PRICE_ROUNDING_NEAREST)
- Logger.log(`point range: ${point1} - ${point2}`, 'addLiquidity')
- let leftPoint = Math.min(point1, point2)
- let rightPoint = Math.max(point1, point2)
- const pointDelta = await getPointDelta(poolContract)
- Logger.log(`point delta: ${pointDelta}`, 'addLiquidity')
- leftPoint = pointDeltaRoundingDown(leftPoint, pointDelta)
- rightPoint = pointDeltaRoundingUp(rightPoint, pointDelta)
- const maxTestA = new BigNumber(amount).times(10 ** tokenA.decimal)
- const maxTestB = calciZiLiquidityAmountDesired(
- leftPoint,
- rightPoint,
- state.currentPoint,
- maxTestA,
- true,
- tokenA,
- tokenB
- )
- const mintParams = {
- tokenA: tokenA,
- tokenB: tokenB,
- fee,
- leftPoint,
- rightPoint,
- maxAmountA: maxTestA.toFixed(0),
- maxAmountB: maxTestB.toFixed(0),
- minAmountA: maxTestA.times(0.985).toFixed(0),
- minAmountB: maxTestB.times(0.985).toFixed(0)
- }
- Logger.log(
- `tokenAtoPay: ${amount2Decimal(new BigNumber(maxTestA), tokenA)}, tokenBtoPay: ${amount2Decimal(
- new BigNumber(maxTestB),
- tokenB
- )}, price: ${point2PriceDecimal(tokenA, tokenB, state.currentPoint)}`,
- 'addLiquidity'
- )
- const balanceA = await zkWallet.getBalance()
- const balanceB = await zkWallet.getBalance(tokenB.address)
- if (new BigNumber(balanceA.toString()).lt(maxTestA)) {
- throw new InternalServerErrorException(
- `${tokenA.symbol}余额不足, 需要${ethers.utils.formatUnits(
- maxTestA.toString(),
- tokenA.decimal
- )}, 当前${ethers.utils.formatUnits(balanceA, tokenA.decimal)}`
- )
- }
- if (new BigNumber(balanceB.toString()).lt(maxTestB)) {
- throw new InternalServerErrorException(
- `${tokenB.symbol}余额不足, 需要${ethers.utils.formatUnits(
- maxTestB.toString(),
- tokenB.decimal
- )}, 当前${ethers.utils.formatUnits(balanceB, tokenB.decimal)}`
- )
- }
- Logger.log(`mintParams: ${JSON.stringify(mintParams, null, 4)}`, 'addLiquidity')
- const gasPrice = await web3.eth.getGasPrice()
- const { mintCalling, options } = getMintCall(
- liquidityManagerContract,
- zkWallet.address,
- chain,
- mintParams,
- gasPrice.toString()
- )
- let calling = mintCalling
- if (calling instanceof Array) {
- calling = liquidityManagerContract.methods.multicall(mintCalling)
- }
- const gasLimit = await calling.estimateGas({ from: zkWallet.address })
- Logger.log(`gas limit: ${gasLimit}`, 'addLiquidity')
- // sign transaction
- const tx = await zkWallet.sendTransaction({
- from: options.from,
- value: Web3.utils.numberToHex(options.value),
- to: web3Config[account.network].liquidityManagerAddress,
- data: calling.encodeABI(),
- gasLimit
- })
- Logger.log(`tx hash: ${tx.hash}`, 'addLiquidity')
- account.addLiuidityNum = (account.addLiuidityNum || 0) + 1
- account.lastAddLiuidity = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
- }
- async removeLiquidity(accountId) {
- const account = await this.accountService.findById(accountId)
- const chainId =
- web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const wallet = new Wallet(account.privateKey).connect(provider)
- const chain = initialChainTable[chainId]
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
- const liquidityManagerContract = getLiquidityManagerContract(
- web3Config[account.network].liquidityManagerAddress,
- web3 as any
- )
- Logger.log('liquidity manager address: ', web3Config[account.network].liquidityManagerAddress)
- const tokenA = getGasToken(chainId)
- const tokenB = await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- Logger.log(`tokenA: ${tokenA.symbol} tokenB: ${tokenB.symbol}`, 'FetchLiquidities')
- const liquidities = await fetchLiquiditiesOfAccount(
- chain,
- web3 as any,
- liquidityManagerContract,
- account.address,
- [tokenA, tokenB]
- )
- Logger.log(`${liquidities.length} liquidities fetched`, 'FetchLiquidities')
- if (liquidities.length <= 0) {
- throw new InternalServerErrorException('No liquidity found')
- }
- const liquidity0 = liquidities.filter((i) => Number(i.liquidity) > 0)[0]
- if (!liquidity0) {
- throw new InternalServerErrorException('all liquidities are removed')
- }
- const decRate = 1
- const originLiquidity = new BigNumber(liquidity0.liquidity)
- const decLiquidity = originLiquidity.times(decRate)
- const { amountX, amountY } = getWithdrawLiquidityValue(liquidity0, liquidity0.state, decLiquidity)
- // here the slippery is 1.5%
- const minAmountX = amountX.times(0.985).toFixed(0)
- const minAmountY = amountY.times(0.985).toFixed(0)
- const gasPrice = await web3.eth.getGasPrice()
- const { decLiquidityCalling, options } = getDecLiquidityCall(
- liquidityManagerContract,
- account.address,
- chain,
- {
- tokenId: liquidity0.tokenId,
- liquidDelta: decLiquidity.toFixed(0),
- minAmountX,
- minAmountY
- } as DecLiquidityParam,
- gasPrice.toString()
- )
- const gasLimit = await decLiquidityCalling.estimateGas(options)
- console.log('gas limit: ', gasLimit)
- const tx0 = await wallet.sendTransaction({
- from: wallet.address,
- to: web3Config[account.network].liquidityManagerAddress,
- data: decLiquidityCalling.encodeABI(),
- gasLimit
- })
- console.log('decLiquidityCalling tx: ', JSON.stringify(tx0, null, 4))
- account.removeLiuidityNum = (account.removeLiuidityNum || 0) + 1
- account.lastRemoveLiuidity = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx0.hash, web3Config[account.network], true)
- }
- async allowance(tokenAddress, spender, wallet: Wallet, network: Network): Promise<number> {
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[network].zksyncRpcUrl))
- const tokenAContract = new web3.eth.Contract(erc20, tokenAddress)
- // @ts-ignore
- const allowanceCalling = tokenAContract.methods.allowance(wallet.address, spender)
- const out = await allowanceCalling.call()
- Logger.log(`allowance: ${out}`, 'GetAllowance')
- return out as unknown as number
- }
- async approve(tokenAddress, spender, wallet: Wallet, network: Network) {
- const allowance = await this.allowance(tokenAddress, spender, wallet, network)
- if (allowance > 0) {
- return
- }
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[network].zksyncRpcUrl))
- const tokenAContract = new web3.eth.Contract(erc20, tokenAddress)
- // @ts-ignore
- const approveCalling = tokenAContract.methods.approve(spender, '0xffffffffffffffffffffffffffffffff')
- let gasLimit = await approveCalling.estimateGas({ from: wallet.address })
- console.log('approve gas limit: ', gasLimit)
- const tx0 = await wallet.sendTransaction({
- from: wallet.address,
- to: tokenAddress,
- data: approveCalling.encodeABI(),
- gasLimit
- })
- console.log('approve tx: ', JSON.stringify(tx0, null, 4))
- }
- async swapWithExactOutput(accountId, amount, outputToken: 'eth' | 'usdc' = 'usdc') {
- const account = await this.accountService.findById(accountId)
- const chainId =
- web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
- const chain = initialChainTable[chainId]
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const wallet = new Wallet(account.privateKey).connect(provider)
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
- console.log('address: ', wallet.address)
- const balance = await web3.eth.getBalance(wallet.address)
- console.log('ethBalance: ' + Web3.utils.fromWei(balance, 'ether'))
- const fromToken =
- outputToken === 'usdc'
- ? getGasToken(chainId)
- : await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- console.log('fromToken: ', fromToken)
- const toToken =
- outputToken === 'usdc'
- ? await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- : getGasToken(chainId)
- console.log('toToken: ', toToken)
- const fee = 2000 // 2000 means 0.2%
- const toTokenContract = getErc20TokenContract(toToken.address, web3 as any)
- const toTokenBalance = await toTokenContract.methods.balanceOf(wallet.address).call()
- console.log(toToken.symbol + ' balance: ' + amount2Decimal(new BigNumber(toTokenBalance), toToken))
- const quoterContract = getQuoterContract(web3Config[account.network].quoterAddress, web3 as any)
- const receiveAmount = new BigNumber(amount).times(10 ** toToken.decimal)
- const params = {
- // pay testA to buy testB
- tokenChain: [fromToken, toToken],
- feeChain: [fee],
- outputAmount: receiveAmount.toFixed(0)
- }
- const { inputAmount } = await quoterSwapChainWithExactOutput(quoterContract, params)
- const payAmount = inputAmount
- const payAmountDecimal = amount2Decimal(new BigNumber(payAmount), fromToken)
- console.log(toToken.symbol + ' to desired: ', amount)
- console.log(fromToken.symbol + ' to pay: ', payAmountDecimal)
- const swapContract = getSwapContract(web3Config[account.network].swapAddress, web3 as any)
- const swapParams = {
- ...params,
- // slippery is 1.5%
- maxInputAmount: new BigNumber(payAmount).times(1.015).toFixed(0),
- strictERC20Token: false
- }
- const gasPrice = await web3.eth.getGasPrice()
- const { swapCalling, options } = getSwapChainWithExactOutputCall(
- swapContract,
- wallet.address,
- chain,
- swapParams,
- gasPrice.toString()
- )
- console.log(JSON.stringify({ swapCalling, options }, null, 4))
- const gasLimit = await swapCalling.estimateGas(options)
- console.log('gas limit: ', gasLimit)
- const tx = await wallet.sendTransaction({
- value: Web3.utils.numberToHex(options.value),
- data: swapCalling.encodeABI(),
- to: web3Config[account.network].swapAddress,
- gasLimit
- })
- console.log(tx)
- account.swapNum = (account.swapNum || 0) + 1
- account.lastSwap = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
- }
- async swapWithExactInput(accountId, amount, inputToken: 'eth' | 'usdc' = 'usdc') {
- const account = await this.accountService.findById(accountId)
- const chainId =
- web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
- const chain = initialChainTable[chainId]
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const wallet = new Wallet(account.privateKey).connect(provider)
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
- console.log('address: ', wallet.address)
- const fromToken =
- inputToken === 'eth'
- ? getGasToken(chainId)
- : await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- console.log('fromToken: ', fromToken)
- const toToken =
- inputToken === 'eth'
- ? await fetchToken(web3Config[account.network].zkUsdcAddress, chain, web3 as any)
- : getGasToken(chainId)
- console.log('toToken: ', toToken)
- await this.approve(fromToken.address, web3Config[account.network].swapAddress, wallet, account.network)
- const quoterContract = getQuoterContract(web3Config[account.network].quoterAddress, web3 as any)
- const payAmount = new BigNumber(amount).times(10 ** fromToken.decimal)
- const fee = 2000 // 2000 means 0.2%
- const params = {
- // pay testA to buy testB
- tokenChain: [fromToken, toToken],
- feeChain: [fee],
- inputAmount: payAmount.toFixed(0)
- }
- const { outputAmount } = await quoterSwapChainWithExactInput(quoterContract, params)
- const receiveAmount = outputAmount
- const receiveAmountDecimal = amount2Decimal(new BigNumber(receiveAmount), toToken)
- console.log(fromToken.symbol + ' to pay: ', amount)
- console.log(toToken.symbol + ' to acquire: ', receiveAmountDecimal)
- const swapContract = getSwapContract(web3Config[account.network].swapAddress, web3 as any)
- const swapParams = {
- ...params,
- // slippery is 1.5%
- minOutputAmount: new BigNumber(receiveAmount).times(0.985).toFixed(0),
- strictERC20Token: false
- }
- const gasPrice = await web3.eth.getGasPrice()
- const { swapCalling, options } = getSwapChainWithExactInputCall(
- swapContract,
- account.address,
- chain,
- swapParams,
- gasPrice.toString()
- )
- const gasLimit = await swapCalling.estimateGas(options)
- console.log('gas limit: ', gasLimit)
- const tx = await wallet.sendTransaction({
- value: Web3.utils.numberToHex(options.value),
- data: swapCalling.encodeABI(),
- to: web3Config[account.network].swapAddress,
- gasLimit
- })
- console.log(JSON.stringify(tx, null, 4))
- account.swapNum = (account.swapNum || 0) + 1
- account.lastSwap = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
- }
- async mint(accountId) {
- // const { data: buffer } = await axios.get('https://cataas.com/cat', {
- // responseType: 'arraybuffer'
- // })
- // const f = new FormData()
- // f.append('file', new Blob([buffer], { type: 'image/jpeg' }), 'cat.jpg')
- // const { data: image } = await axios.post('https://api.mintsquare.io/files/upload/', f)
- const f1 = new FormData()
- f1.append(
- 'file',
- new Blob([
- JSON.stringify({
- name: randomString.generate({ length: 8, charset: 'alphanumeric' }),
- attributes: [],
- image: 'https://mintsquare.sfo3.cdn.digitaloceanspaces.com/mintsquare/mintsquare/RJRohgvdN6xwSBvFefo8z6_1687229689762946549.jpg'
- })
- ])
- )
- const { data: res } = await axios.post('https://ipfs.infura.io:5001/api/v0/add', f1, {
- auth: {
- username: '2RrUoAzIHbABPzXlH4M7Rnc3Fir',
- password: 'aaa4218c6944d2b9ad706275e5f1d6f1'
- }
- })
- Logger.log(res)
- const account = await this.accountService.findById(accountId)
- const chainId =
- web3Config[account.network].ethereumNetwork == 'goerli' ? ChainId.ZkSyncAlphaTest : ChainId.ZkSyncEra
- const chain = initialChainTable[chainId]
- const provider = new Provider(web3Config[account.network].zksyncRpcUrl)
- const wallet = new Wallet(account.privateKey).connect(provider)
- const web3 = new Web3(new Web3.providers.HttpProvider(web3Config[account.network].zksyncRpcUrl))
- console.log('address: ', wallet.address)
- const contract = new web3.eth.Contract(mintSquareAbi, web3Config[account.network].mintAddress, web3 as any)
- // @ts-ignore
- const mintCall = await contract.methods.mint(`ipfs://${res.Hash}`)
- Logger.log(`ipfs://${res.Hash}`, 'mint')
- const gasLimit = await mintCall.estimateGas({ from: wallet.address })
- console.log('gas limit: ', gasLimit)
- const tx = await wallet.sendTransaction({
- from: wallet.address,
- to: web3Config[account.network].mintAddress,
- data: mintCall.encodeABI(),
- gasLimit
- })
- console.log(tx)
- account.mintNum = (account.mintNum || 0) + 1
- account.lastMint = new Date()
- await this.accountService.save([account])
- return new Web3Result(account.address, tx.hash, web3Config[account.network], true)
- }
- async randomPercent(account: Account) {}
- }
|