【区块链】走进web3的世界-常用工具方法封装(基于wagmi)

【区块链】走进web3的世界-常用工具方法封装(基于wagmi)_第1张图片

1、创建client

 


import { createClient, configureChains, mainnet, goerli } from 'wagmi'
import { bsc, bscTestnet } from 'wagmi/chains'

// 申请的aplKey
const AlchemyApiKey = '7EfveD9qe2JYumi9OIJJYzmDrELjvFRl'

// 网络配置
const { chains, provider, webSocketProvider } = configureChains(
    [goerli, mainnet, bscTestnet, bsc],
    [alchemyProvider({ apiKey: AlchemyApiKey }), publicProvider()]
)

// 创建连接
export const client = createClient({
    autoConnect: true,
    connectors: [new MetaMaskConnector({ chains })],
    provider,
    webSocketProvider
})

2、切换网络


import { switchNetwork, getNetwork } from '@wagmi/core'

/**
 *
 * @param chainId 需要切换的网络
 * goerli:5
 * mainnet:1
 * bscTestnet:97
 * bsc:56
 */
export const handleSwitchNetwork = async (chainId: number = 56) => {
    const {
        chain: { id }
    } = getNetwork()
    if (id == chainId) {
        return true
    }
    let isSwitch = true
    await switchNetwork({
        chainId
    }).catch(e => {
        isSwitch = false
    })
    return isSwitch
}

// 使用方式
export BNB_CHAIN_ID = 5
import { BNB_CHAIN_ID } from '@/constants'
handleSwitchNetwork(BNB_CHAIN_ID)

3、获取gas费用,并转换为eth


import { ethers } from 'ethers'
import { getProvider } from '@wagmi/core'

export const getGasPrice = async () => {
    const providers = getProvider()
    const result = await providers.getGasPrice()
    return ethers.utils.formatUnits(result.toString())
}

4、判断钱包是否登录


import { getAccount } from '@wagmi/core'

/**
 * 判断钱包有没有登录
 */
export const checkWalletConnect = () => {
    // 先判断一下钱包有没有登录,在详情页可以看到
    const { isConnected } = getAccount()
    if (!isConnected) {
        return false
    }
    return true
}

5、创建签名


import { signMessage } from '@wagmi/core'

/**
 * 给字符串签名
 * @param message 签名的字符串
 * @returns 签名后的字符串
 */
export const getSigMessage = async message => {
    const signature = await signMessage({
        message
    })
    return signature
}

6、获取gas费用

import { getProvider } from '@wagmi/core'

// 获取单价的gas费用
export const getGasPrice = async () => {
    const providers = getProvider()
    const result = await providers.getGasPrice()
    console.log('getGasPrice...', getGasPrice)
    return result.toString()
}

import { utils } from 'ethers'
const { formatEther } = utils
/**
 * 获取完整的gas费用
 * @param abiType 合约对应的abi文件
 * @param funcName 合约中具体的方法
 * @param address 合约地址
 * @returns 预估的gas费用 string类型
 */
export const estimateGasService = async (abiType, funcName: string, address: Address): Promise => {
    const iface = new Interface(abiType)
    const sigHash = iface.getSighash(funcName)
    console.log('sigHash...', sigHash)
    const provider = getProvider()
    const gasPrice = await provider.getGasPrice()
    console.log('gasPrice....', formatEther(gasPrice))
    const gas = await provider.estimateGas({
        to: address,
        data: sigHash,
        value: parseEther('1')
    })
    console.log('gas...', gas)
    return formatEther(gasPrice.mul(gas))
}

// 使用方式
import { estimateGasService } from '@/web3/common'
import WethBalanceAbi from '@/web3/eth/WethBalanceAbi.json'
import { Address } from 'abitype'

const data = await estimateGasService(WethBalanceAbi, 'deposit', wethAddress as Address)

// WethBalanceAbi.json
[
    {
        "constant": true,
        "inputs": [],
        "name": "name",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "guy",
                "type": "address"
            },
            {
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "approve",
        "outputs": [
            {
                "name": "",
                "type": "bool"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "totalSupply",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "src",
                "type": "address"
            },
            {
                "name": "dst",
                "type": "address"
            },
            {
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "transferFrom",
        "outputs": [
            {
                "name": "",
                "type": "bool"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "withdraw",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "decimals",
        "outputs": [
            {
                "name": "",
                "type": "uint8"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "name": "",
                "type": "address"
            }
        ],
        "name": "balanceOf",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "symbol",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "dst",
                "type": "address"
            },
            {
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "transfer",
        "outputs": [
            {
                "name": "",
                "type": "bool"
            }
        ],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [],
        "name": "deposit",
        "outputs": [],
        "payable": true,
        "stateMutability": "payable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "name": "",
                "type": "address"
            },
            {
                "name": "",
                "type": "address"
            }
        ],
        "name": "allowance",
        "outputs": [
            {
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "payable": true,
        "stateMutability": "payable",
        "type": "fallback"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "name": "src",
                "type": "address"
            },
            {
                "indexed": true,
                "name": "guy",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "Approval",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "name": "src",
                "type": "address"
            },
            {
                "indexed": true,
                "name": "dst",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "Transfer",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "name": "dst",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "Deposit",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": true,
                "name": "src",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "wad",
                "type": "uint256"
            }
        ],
        "name": "Withdrawal",
        "type": "event"
    }
]

你可能感兴趣的:(区块链,web3)