web3与ethers调用对比

  • webkubor
  • 更新于 2022-03-12 10:26
  • 阅读 3600

web3 ,ethers对比

web3 与 ethers 对比

合约对象返回

web3

const web3 = new Web3(window.ethereum);
  const contractObj = new web3.eth.Contract(constractAbi, ontractAddress);
  const contract = await contractObj(tokenJson, contractAddress.IPISTR);

ether

可读权限

import { ethers } from "ethers";  
const provider = new ethers.providers.JsonRpcProvider(
    contractAddress.baseURL
  );
  const Contract = new ethers.Contract(
    contractAddress.IPISTR,
    tokenJson,
    provider
  )
  console.log(Contract, "ether");

可读可写权限

import { ethers } from "ethers";
/**
 * @description: 基于ether.js返回的合约对象
 * @param {*} tokenJson ABI文件
 * @param {*} contractAddress 合约地址
 * @return {*}
 */
export async function outContract(tokenJson, contractAddress) {
  let ethersProvider = new ethers.providers.Web3Provider(
    window.ethereum,
    "any"
  );
  const Contract = new ethers.Contract(
    contractAddress,
    tokenJson,
    ethersProvider.getSigner()
  );
  return Contract;
}

合约方法调用

查看

左侧web3,右侧ether

metamsk交互

关于web3的数字类型返回

ether.js返回bignumber类型

bignumber => ether.js

const { ethers } require("ethers")

var a = "0x03"

var b = ethers.BigNumber.from(a)

var c = b.toNumber()

console.log(c)

关于返回合约对象

export function getContract(address: string, ABI: any, library: Web3Provider, account?: string): Contract {
  if (!isAddress(address) || address === AddressZero) {
    throw Error(`Invalid 'address' parameter '${address}'.`)
  }

  return new Contract(address, ABI, getProviderOrSigner(library, account) as any)
}

// account is optional
export function getProviderOrSigner(library: Web3Provider, account?: string): Web3Provider | JsonRpcSigner {
  return account ? getSigner(library, account) : library
}

链接跳转功能

export function getEtherscanLink(
  chainId: ChainId,
  data: string,
  type: 'transaction' | 'token' | 'address' | 'block'
): string {
  const prefix = `https://${ETHERSCAN_PREFIXES[chainId] || ETHERSCAN_PREFIXES[1]}etherscan.io`

  switch (type) {
    case 'transaction': {
      return `${prefix}/tx/${data}`
    }
    case 'token': {
      return `${prefix}/token/${data}`
    }
    case 'block': {
      return `${prefix}/block/${data}`
    }
    case 'address':
    default: {
      return `${prefix}/address/${data}`
    }
  }
}
点赞 2
收藏 3
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
webkubor
webkubor
- 前端开发工程师 - dapp开发 - app开发 - node