ethers.js 封装

import { utils, BigNumber } from 'ethers'
import { Message } from 'element-ui'
import config from '@/config'
import { fmtWalletAddress } from '@/utils/utils'
import Bus from '@/utils/bus'

class contractFn {
  constructor({ account, provider, chainId }) {
    console.log(`[ account : ${account} ] >`)
    this.provider = provider
    this.account = account.toLowerCase()
    this.fmtAccount = fmtWalletAddress(account)
    this.chainId = chainId
    this.config = config
  }

  async call({ to, methods, params, abi }) {
    const iface = new utils.Interface(abi)
    const data = iface.encodeFunctionData(methods, params)
    return this.provider
      .call({
        to,
        data
      })
      .then(res => {
        return iface.decodeFunctionResult(methods, res)
      })
  }

  async transaction({ to, methods, params, abi, value=0 }) {
    const iface = new utils.Interface(abi)
    const data = iface.encodeFunctionData(methods, params)
    let gas = BigNumber.from('10000')
    try {
      gas = await this.provider.estimateGas({
        from: this.account,
        to: to,
        data: data,
        value: value
      })
      Bus.$emit('transaction', {
        state: 'pending'
      })
    } catch (error) {
      const message = error.data ? error.data.message : error.error.message
      const msg = message.replace('execution reverted:', '')
      Message.warning(msg)
      return Promise.reject(error)
    }
    try {
      const signer = this.provider.getSigner()
      const tx = await signer.sendTransaction({
        to: to,
        data: data,
        value: value,
        gasLimit: gas.toNumber()
      })
      const obj = Object.assign(
        { methods, params },
        { hash: tx.hash },
        {
          state: 'success'
        }
      )
      Bus.$emit('transaction', obj)
      return Promise.resolve(tx)
    } catch (error) {
      Bus.$emit('transaction', {
        state: 'rejected'
      })
      // Message.error(error.data)
      return Promise.reject(error)
    }
  }
}

export default contractFn
 
 
 
 
 
posted @ 2021-11-25 15:18  起风了1573  阅读(392)  评论(0)    收藏  举报