ERC20的精度换算(ETH转WEI, WEI转ETH)

    ERC20的Token精度字段为decimals,取值范围为1~18,decimals默认为18。不同的Token,其decimals也是不同的,具体要根据Token合约代码里的deicmals来进行判断。在ethers.js里有个非常好的的库utils,使用utils.formatUnits()、utils.parseUnits()可以非常方便的进行精度换算。

1 ETH --> WEI

  • 若decimals=18,则
        y = utils.parseUnits(x,18)
  • 若decimals=6,则
        y = utils.parseUnits(x,6)

2 WEI --> ETH

  • 若decimals=18,则
        y = utils.formatUnits(x,18)

  • 若decimals=6,则
        y = utils.formatUnits(x,6)

案例代码

    //change.js

const { utils, BigNumber } = require("ethers")

function eth2Wei(x,decimals) {
    return utils.parseUnits(x,decimals).toString()
}

function wei2Eth(x,decimals) {
    return utils.formatUnits(x,decimals).toString()
}

async function doMain() {
    //1) 已知 100 ethers X (100枚X), decimals = 18
    //   求它可以转化为多少wei?
    let x1 = "100"
    let decimals1 = 18
    let y1 = eth2Wei(x1,decimals1)
    console.log("wei: y1=",y1)

    //2) 已知 100 ethers X (100枚X), decimals = 6
    //   求它可以转化为多少wei?
    let x2 = "100"
    let decimals2 = 6
    let y2 = eth2Wei(x2,decimals2)
    console.log("wei: y2=",y2)

    //3) 在Solidity中,uint = wei
    // 已知 500000000000000000000 uint X(用最小单位表示),decimals = 18
    // 求它可以转化为多少ethers?
    let x3 = BigNumber.from("500000000000000000000")
    let decimals3 = 18
    let y3 = wei2Eth(x3,decimals3)
    console.log("ethers: y3=",y3)

    //4) 在Solidity中,uint = wei
    // 已知 500000000000000000000 uint X(用最小单位表示),decimals = 6
    // 求它可以转化为多少ethers?
    let x4 = BigNumber.from("500000000000000000000")
    let decimals4 = 6
    let y4 = wei2Eth(x4,decimals4)
    console.log("ethers: y4=",y4)

}

doMain()

    效果如下:

图(1) 使用utils库进行精度换算

附录

    在黑框框命令行里,输入如下命令即可安装ethers.js

npm init -y
npm install ethers

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>