web3js实现通过合约方法进行代币交易查询余额

web3js

这里使用MetaMask注入的etherum

import MetaMaskSDK from '@metamask/sdk';
import Web3 from 'web3';

let option = {
  injectProvider: false,
  communicationLayerPreference: 'webrtc',
  preferDesktop: true
}
const MMSDK = new MetaMaskSDK(option);
const ethereum = MMSDK.getProvider();
let web3 = new Web3(ethereum);

获取合同

getContract(abi, address) {
    if (!web3) return false;
    let contract = new web3.eth.Contract(abi, address);
    return contract
  }

交易

通过合同实现交易,具体参数根据合约需要,数量一般为16进制

async sendTransactionByContract(param) {
    const myContract = this.getContract(param.abi, param.address);
    if (!myContract) return;
    return new Promise((resolve, reject) => {
      myContract.methods[param.funcName](param.amount ? this.toHex(param.amount) : null).send({
        from: param.from
      }).then(res => {
        resolve(res)
      }).catch(err => {
        reject(err);
        showToast(err)
      })
    })
  }

获取余额等

通过合同查询余额等

async queryTransactionByContract(param) {
  const myContract = this.getContract(param.abi, param.address);
  if (!myContract) return;
  let ret = await myContract.methods[param.funcName](param.from).call()
  return ret;
}

你可能感兴趣的:(web3,web3,javascript,开发语言)