Ethers.js-BigInt和单位转换

Ethers.js-BigInt和单位转换

BigInt

以太坊中,许多计算都对超出JavaScript整数的安全值(js中最大安全整数为9007199254740991)。因此,ethers.js使用 JavaScript ES2020 版本原生的 BigInt 类 安全地对任何数量级的数字进行数学运算。在ethers.js中,大多数需要返回值的操作将返回 BigInt,而接受值的参数也会接受它们。

创建BigInt实例

你可以利用ethers.getBigInt()函数将string,number等类型转换为BigInt。

注意:超过js最大安全整数的数值将不能转换。

const oneGwei = ethers.BigNumber.from("1000000000")
console.log(oneGwei)
console.log(ethers.BigNumber.from("0x3b9aca00"))
console.log(ethers.BigNumber.from(1000000000))
console.log("js中最大安全整数:", Number.MAX_SAFE_INTEGER)

BigInt运算

BigInt支持很多运算,例如加减乘除、取模mod,幂运算pow,绝对值abs等运算:

注意:数值带后缀n会自动转换成BigInt,BigInt 和 number 不能直接混合运算,必须将它们转换为相同的类型。

// 运算
console.log("加法:", oneGwei + Number(1n))
console.log("减法:", oneGwei - Number(1n))
console.log("乘法:", oneGwei * Number(2n))
console.log("除法:", oneGwei / Number(2n))
// 比较
console.log("是否相等:", oneGwei == Number(1000000000n))

单位转换

在以太坊中,1 ether等于10^18 wei
formatUnits(变量, 单位):格式化,小单位转大单位,比如wei -> ether,在显示余额时很有用。参数中,单位填位数(数字)或指定的单位(字符串)。

console.group('\n2. 格式化:小单位转大单位,formatUnits');
console.log(ethers.utils.formatUnits(oneGwei, 0));
// '1000000000'
console.log(ethers.utils.formatUnits(oneGwei, "gwei"));
// '1.0'
console.log(ethers.utils.formatUnits(oneGwei, 9));
// '1.0'
console.log(ethers.utils.formatUnits(oneGwei, "ether"));
// `0.000000001`
console.log(ethers.utils.formatUnits(1000000000, "gwei"));
// '1.0'
console.log(ethers.utils.formatEther(oneGwei));
// `0.000000001` 等同于formatUnits(value, "ether")
console.groupEnd();

parseUnits:解析,大单位转小单位,比如ether -> wei,在将用户输入的值转为wei为单位的数值很有用。参数中,单位填位数(数字)或指定的单位(字符串)。

console.group('\n3. 解析:大单位转小单位,parseUnits');
console.log(ethers.utils.parseUnits("1.0").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.utils.parseUnits("1.0", "ether").toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.utils.parseUnits("1.0", 18).toString());
// { BigNumber: "1000000000000000000" }
console.log(ethers.utils.parseUnits("1.0", "gwei").toString());
// { BigNumber: "1000000000" }
console.log(ethers.utils.parseUnits("1.0", 9).toString());
// { BigNumber: "1000000000" }
console.log(ethers.utils.parseEther("1.0").toString());
// { BigNumber: "1000000000000000000" } 等同于parseUnits(value, "ether")
console.groupEnd();

猜你喜欢

转载自blog.csdn.net/Geoffrey_Zhu/article/details/142939561
今日推荐