使用自带方法或web3js或ethersjs三种方式实现转账、查余额等原生币

metamask获取的etherum,使用etherum自带方法实现,etherum参数都是16进制。web3js参数为10进制。

获取gasPrice

metamask:结果返回16进制

async getGasPrice() {
    let ret;
    await ethereum.request({"method": "eth_gasPrice"}).then(res => {
      ret = res;
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret + "";
  }

web3js:结果返回10进制bignumber,Number(num)默认十进制

  async getGasPrice() {
    let ret;
    await web3.eth.getGasPrice().then(res => {
      ret = Number(res);
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret + "";
  }

ethersjs:结果返回16进制bignumber,Number(num)默认十进制

  async getGasPrice() {
    let ret;
    let provider = new ethers.providers.Web3Provider(ethereum);
    await provider.getGasPrice().then(res => {
      ret = Number(res);
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret + "";
  }

获取gasLimit

metamask:结果返回16进制

async estimateGas(param) {
    let ret;
    const myContract = this.getContract(param.abi, param.address);
    await ethereum.request({
      "method":"eth_estimateGas",
      "params":[{
        "form":param.from,
        "to":param.address,
        "value": toHex(param.amount * Math.pow(10,18)),
        "input": myContract.methods[param.funcName]().encodeABI()}]
    }).then(res => {
      //16进制结果
      console.log(res)
      ret = res;
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret;
  }

web3js:10进制bignumber,转为10进制

  async estimateGas(param) {
    let ret;
    const myContract = this.getContract(param.abi, param.address);
    await web3.eth.estimateGas({
      form:param.from,
      to:param.address,
      value: param.amount * Math.pow(10,18),
      data: myContract.methods[param.funcName]().encodeABI()
    }).then(res => {
      ret = Number(res);
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret + "";
  }

ethersjs:16进制bignumber

  async estimateGas(param) {
    let ret;
    let provider = new ethers.providers.Web3Provider(ethereum);
    const myContract = this.getContract(param.abi, param.address);
    await provider.estimateGas({
      form:param.from,
      to:param.address,
      value: param.amount * Math.pow(10,18),
      data: myContract.methods[param.funcName]().encodeABI()
    }).then(res => {
      ret = Number(res);
    }).catch(err => {
      errorHandlerOfMetaMaskRequest(err)
    });
    return ret + "";
  }

ABI编码合约方法

//web3js
myContract.methods[param.funcName]().encodeABI()
//ethersjs
myContract.functions[param.funcName]().encode()

转账

async sendTransaction(param) {
    let price = await this.getGasPrice();//16进制
    let gas = await this.estimateGas(param);
    const myContract = this.getContract(param.abi, param.address);
    if (!myContract) return;
    return new Promise((resolve, reject) => {
      //metamask参数都是16进制,web3js方法10进制
      ethereum.request({
        method: "eth_sendTransaction",
        params: [{
          from: param.from, 
          to: param.address, 
          value: toHex(param.amount * Math.pow(10,18)), 
          gasPrice: price, 
          gas: gas, 
          chainId: store.state.metaMask?.chainID,
          data: myContract.methods[param.funcName]().encodeABI()
        }]
      })
        .then((res) => {
          console.log(res)
          resolve(res)
        })
        .catch((error) => { console.error(error); reject(error) });
    })
  }

web3js

async sendTransaction(param) {
	const myContract = this.getContract(param.abi, param.address);
    if (!myContract) return;
    return new Promise((resolve, reject) => {
  	web3.eth.sendTransaction({
          from: param.from,
          to: param.address, // Required except during contract publications.
          value: param.amount * Math.pow(10, 18),
          chainId: store.state.metaMask?.chainID,
          data: myContract.methods[param.funcName]().encodeABI()
        })
        .then((res) => {
          console.log(res)
          resolve(res)
        })
        .catch((error) => { console.error(error); reject(error) });
    })
}    

ethersjs实现原生币转账提现等

sendTransactionUseEthers(param) {
    const ethprovider = new ethers.providers.Web3Provider(ethereum);
    const signer = ethprovider.getSigner();
    const contract = new ethers.Contract(param.address, param.abi, signer)
    return new Promise((resolve, reject) => {
      try {
        const func = async () => {
          let value = param.amount?ethers.utils.parseEther(param.amount):null;
          let tx = await contract[param.funcName](value?{ value: value }:null);
          let receipt = await tx.wait();
          resolve(receipt)
        }
        func();
      } catch (error) {
        console.log(error)
        reject(error)
      }
    })
}

余额

metamask

async getBalance(account) {
    let balance;
    await ethereum.request({ method: 'eth_getBalance', params: [account, "latest"] }).then(res => {
      balance = Number(res)/Math.pow(10,18)
    })
    return balance;
  }

web3js

async getBalance(account) {
    let balance;
    await web3.eth.getBalance(account).then(res => {
      balance = Number(res)/Math.pow(10,18)
    })
    return balance;
  }

ethersjs

async getBalance(account) {
    let balance;
    const ethprovider = new ethers.providers.Web3Provider(ethereum);
    const signer = ethprovider.getSigner();
    await ethprovider.getBalance(account).then(res => {
      balance = Number(res)/Math.pow(10,18)
    })
    return balance;
  }

你可能感兴趣的:(web3,web3,javascript)