web3使用,MetaMask钱包对接登录退出,计算apy,添加流动性,发erc20, Events事件读取限制,解析哈希值

1.Pool

getApy = async () => {
        let LPcontracts = await getLpPairContracts();//交易对合约
        let totalSupply = await LPcontracts.methods.totalSupply().call();

        const blockOutput = await sendContracts.MedalFactory.methods.blockOutput().call(); //每块产出
        const rewardPerBlock = sendWeb3.utils.toBN(blockOutput);
        const rewardOfYear = sendWeb3.utils.toBN(Math.floor((365 * 86400) / 3)).mul(rewardPerBlock).toString().toBN(); //年产出

        
        let pairBalance = await sendContracts.USDTToken.methods.balanceOf(LPcontracts._address).call();
        const totalLPPrice = pairBalance .toBN().times(2);
        const lpPrice = totalLPPrice.div(totalSupply).toFixed().toWei().toFixed(0).fromWei();

        let LPtotalSupply = await LPcontracts.methods.balanceOf(sendContracts.MedalFactory._address).call(); //pool lp余额

        
        LPcontracts.methods.getReserves().call((err, res) => {
            //固定计算
            const amountInWithFee = '1'.toWei().toBN().times(997);
            const numeratorIn = amountInWithFee.times(res._reserve1.toBN());
            const denominatorIn = (res._reserve0.toBN()).times(1000).plus(amountInWithFee);
            const otherPrice= numeratorIn.div(denominatorIn).toFixed(0).fromWei();//产出token价格

            const apyx = (rewardOfYear.times(otherPrice)).div((LPtotalSupply.toBN().times(lpPrice))).times(sendWeb3.utils.toBN('100'));

            
            if (apyx.gt(0) && apyx.isFinite()) {
                this.setState({
                    LPAPY: apyx.toFixed(2)
                });
            }
        });

    }

2.单个Token

export async function getAPR(web3,rewardToken,rewardTokenPrice, blockOutput,totalSupply,token) {

    if (totalSupply.toString() === '0') {
        return totalSupply;
    }

    let rewardPerBlock = web3.utils.toBN(blockOutput);
    let rewardOfYear = web3.utils.toBN(Math.floor(365 * 86400 / 3)).mul(rewardPerBlock);
    let TokenPrice=0;
    let totalPrice=0;
    
         TokenPrice = await getAmountOut(web3, [token, USDTTokenAddress], ONE_ETHER);
 totalPrice=web3.utils.toBN(TokenPrice).mul(web3.utils.toBN(totalSupply)).div(ONE_ETHER);
    
   totalPrice=web3.utils.toBN(TokenPrice).mul(web3.utils.toBN(totalSupply)).div(ONE_ETHER);
    
    
    return rewardOfYear.mul(rewardTokenPrice).mul(web3.utils.toBN('100')).div(totalPrice);
}

3.

1.获取链ID
let chainId = await sendWeb3.eth.getChainId();

获取主币余额
let balanceOf = await sendWeb3.eth.getBalance(address);

2.检测账户切换
window.ethereum.on('accountsChanged', accounts => {
            if (accounts[0]) {
                global.$address = accounts[0];
            }
            location.reload(true);
        });

3.检测节点切换
window.ethereum.on('networkChanged', () => {
            location.reload(true);
        });

4.添加ERC20(options参数更换需要的代币)

function tokenAdded(){
const tokenAdded = await window.ethereum.request({
    method: 'wallet_watchAsset',
    params: {
      type: 'ERC20',
      options: {
        address: '0x............................',
        symbol: 'USDT',
        decimals: 18,
        image: `${BASE_URL}/images/tokens/${tokenAddress}.png`,
      },
    },
  })
}

5.登录退出

if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
}

// 当用户点击登录按钮时,请求 MetaMask 授权
const login = async () => {
  try {
    // 请求 MetaMask 授权
    await window.ethereum.request({ method: 'eth_requestAccounts' });
    console.log('Logged in!');
  } catch (error) {
    console.error(error);
  }
};

// 当用户点击退出按钮时,清除 MetaMask 授权信息
const logout = async () => {
  try {
    // 清除 MetaMask 授权信息
    await window.ethereum.request({ method: 'eth_logout' });
    console.log('Logged out!');
  } catch (error) {
    console.error(error);
  }
};


// 获取当前登录账户的地址
const getAddress = () => {
  return window.ethereum.selectedAddress;
}

// 判断用户是否已登录
const isLoggedIn = () => {
  return Boolean(window.ethereum.selectedAddress);
}

5.添加流动性

this.$Router.methods.addLiquidity(
                this.token0.address,  代币地址
                this.token1.address,   代币地址
                amountADesired,   //第1个代币的数量
                amountBDesired,   //第2个代币的数量
                amountAMin,   //允许实际添加的第1个代币的最小数量
                amountBMin,   //允许实际添加的第2个代币的最小数量
                this.$address,  //地址
                deadline。 //交易的截止时间
            )

6发币

7.Events事件读取限制解决

//bsc
setHistoryList([]);
        setLoadingsSpin(true);
        const latestBlock = await sendWeb3.eth.getBlockNumber();
        const fixedBlock = 28200000;   //固定

        const totalPages = Math.ceil((latestBlock - fixedBlock) / 3000);
        const pageNumbers = Array.from(Array(totalPages).keys());
        
        const eventFilter = {
            account: address,
        };

        const fetchEventsByPage = async (page) => {
            const fromBlock = fixedBlock + page * 3000;
            const toBlock = Math.min(fromBlock + 3000, latestBlock);

            const events = await callContracts.Mapper.getPastEvents('MapToken', {
                fromBlock: Math.max(fromBlock, fixedBlock),
                toBlock: toBlock,
                filter: eventFilter,
            });

            return events.filter((event) => event.returnValues.oldToken.toLowerCase() === tokenAddress.toLowerCase())
                .map((event) => ({
                    tokenAddress: event.returnValues.oldToken,
                    amount: event.returnValues.Out.fromWei(),
                    symbol: symbol
                }));
        };
        const allEvents = await Promise.all(pageNumbers.map(fetchEventsByPage));
        setLoadingsSpin(false);
        setHistoryList([].concat(...allEvents));

8.哈希值

let transaction = await web3.eth.getTransaction('0xa01013c5c808b76090fbc41f74565c142f88ebc0f0fa0588b8402a0d692c11c8')

  const abi = {
    "inputs": [
      { "internalType": "address[]", "name": "useChildren", "type": "address[]" },
      { "internalType": "address", "name": "cardAddr", "type": "address" }
    ],
    "name": "levelUpgrade",
    "outputs": [
      { "internalType": "uint8", "name": "origin", "type": "uint8" },
      { "internalType": "uint8", "name": "current", "type": "uint8" }
    ],
    "stateMutability": "nonpayable",
    "type": "function"
  };
  
  const paramTypes = abi.inputs.map(input => input.type);
  
  const params = web3.eth.abi.decodeParameters(['address[]','address'], '0x' + transaction.input.slice(10));  // remove function selector (first 10 bytes)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值