MENU

typescript记录

August 27, 2022 • 区块链

BigNumber&Wei&GWei&数字千分位格式化

import { BigNumber } from 'ethers';
export const toBigNumber = (value: any) => {
    return BigNumber.from(value);
};

export const toWei = (value: any) => {
    return BigNumber.from(10).pow(18).mul(value);
};

export const toGWei = (value: any) => {
    return BigNumber.from(10).pow(9).mul(value);
};
// 方法四
function toThousands(num) {
    var num = (num || 0).toString(), result = '';
    while (num.length > 3) {
        result = ',' + num.slice(-3) + result;
        num = num.slice(0, num.length - 3);
    }
    if (num) { result = num + result; }
    return result;
}

参照:从千分位格式化谈 JS 性能优化

ERC20 类 rpc 节点获取 chainId

export const getChainId = async (rpcurl: string) => {
    const provider = new ethers.providers.JsonRpcProvider(rpcurl);
    const network = await provider.getNetwork();
    return network.chainId;
};

本地调节区块时间轴

const { ethers, upgrades, config, network } = require("hardhat");

export const advanceTime = async (time: any) => {
    return ethers.provider.send("evm_increaseTime", [time]);
};

export const advanceBlock = async () => {
    await ethers.provider.send("evm_mine", []);
    return (await ethers.provider.getBlock("latest")).hash;
};

export const advanceTimeAndBlock = async (time: any) => {
    await advanceTime(time);
    await advanceBlock();
    return ethers.provider.getBlock("latest");
};

export const setBlockTimeStamp = async (time: any) => {
    await ethers.provider.send("evm_setNextBlockTimestamp", [time]);
    await ethers.provider.send("evm_mine");
};

export const getBlockTimeStamp = async () => {
    const blockNum = await ethers.provider.getBlockNumber();
    const block = await ethers.provider.getBlock(blockNum);
    return block.timestamp;
};

取合约函数接口签名

export const getFunctionSignature = (fnabi: any[], fn: string, ...params?: any[]) => {
    let contractInterface = new ethers.utils.Interface(fnabi);
    let sig= contractInterface.encodeFunctionData(fn, ...params);
    return sig;
};