Metamask 以太坊合约金额显示为 0,而不是用户在 formData 中输入的金额

问题描述 投票:0回答:1

在此示例中(请参阅屏幕截图错误),用户想要将 0.002 以太币转移到目标地址。然而,当服务器连接到metamask时,metamask中显示的交易金额是0而不是0.002。

Screenshot error

我有一个输入表单,供用户输入他们想要转移到某个地址的以太币数量。此用户输入数据量将传递到 TransactionContext.jsx 文件(请参阅下面的代码)和 sendTransaction 函数。我console.log传递给sendTransaction函数的parseAmount,它正确显示为0.002以太。因此,我不确定为什么 Metamask 显示 0 以太币。

import React, {useEffect, useState} from 'react'
import {ethers} from 'ethers'
import { contractABI, contractAddress } from "../utils/constants"
export const TransactionContext = React.createContext()

const { ethereum } = window;

const createEthereumContract = async () => {
  
try {
    const provider = new ethers.BrowserProvider(window.ethereum);
    
    const signer = await provider.getSigner();
    const transactionContract = new ethers.Contract(contractAddress, contractABI, signer);
  
    return transactionContract;
} catch (error) {console.error('Error creating Ethereum contract:', error);
  
}
};

//function to check if a wallet is connected at the start
export const TransactionProvider = ({children}) => {
  
  const [formData, setformData] = useState({ addressTo: "", amount: "", keyword: "", message: "" });
  const [currentAccount, setCurrentAccount] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [transactionCount, setTransactionCount] = useState(localStorage.getItem("transactionCount"));
  const [transactions, setTransactions] = useState([]);
  
  //handleChange func interact with inputs except the event
  const handleChange = (e, name) => {
    setformData((prevState) => ({ ...prevState, [name]: e.target.value }));
  };

  const getAllTransactions = async () =>{
    //check if browser has metamask installed
    try {if(!ethereum) return alert("Please install metamask")

    const transactionContract = await createEthereumContract();
    const availableTransactions = await transactionContract.getAllTransactions();
    
    //change structure of data 
    const structuredTransactions = availableTransactions.map((transaction)=>({
      addressTo: transaction.receiver,
      addressFrom: transaction.sender,
      timestamp: new Date(Number(transaction.timestamp) * 1000).toLocaleString(),
      message: transaction.message,
      keyword: transaction.keyword,
      amount: parseInt(transaction.amount._hex) / (10 ** 18)
    }))

    console.log(structuredTransactions)

    } catch(error){
      console.log(error);

    }
  }


  const checkIfWalletIsConnected = async() =>{
    try{
      if(!ethereum) return alert("Please install metamask")
      const accounts = await ethereum.request({method:'eth_accounts'})
      console.log(accounts)

      if(accounts.length){
        setCurrentAccount(accounts[0])

        getAllTransactions()

      } else {
        console.log('No accounts found')
      }
    } catch(error){
      console.log(error)
      throw new Error("No ethereum object")
    }
  }

const checkIfTransactionsExist = async () => {
  try {
    const transactionContract = await createEthereumContract()
    const transactionCount = await transactionContract.getTransactionCount()

    window.localStorage.setItem("transactionCount",transactionCount)

  } catch(error) {

  }

}

  {/*function for connecting the account */}
  const connectWallet = async () => {
    try {
      if (!ethereum) return alert("Please install MetaMask.");

      const accounts = await ethereum.request({ method: "eth_requestAccounts", });

      setCurrentAccount(accounts[0]);
      window.location.reload();
    } catch (error) {
      console.error(error);

      throw new Error("No ethereum object");
    }
  }

  const sendTransaction = async () => {
    try {
      if (ethereum) {
        const { addressTo, amount, keyword, message } = formData;
        const transactionContract = await createEthereumContract();
        const parsedAmount = ethers.parseEther(amount);

        console.log(parsedAmount)

        await ethereum.request({
          method: "eth_sendTransaction",
          params: [{
            from: currentAccount,
            to: addressTo,
            gas: "0x5208",
            value: parsedAmount._hex,
          }],
        });

        const transactionHash = await transactionContract.addToBlockchain(addressTo, parsedAmount, message, keyword);

        setIsLoading(true);
        console.log(`Loading - ${transactionHash.hash}`);
        await transactionHash.wait();
        console.log(`Success - ${transactionHash.hash}`);
        setIsLoading(false);

        const transactionCount = await transactionContract.getTransactionCount();

        setTransactionCount(Number(transactionCount));
        window.location.reload();
        
      } else {
        console.log("No ethereum object");
      }
    } catch (error) {
      console.error(error);

      throw new Error("No ethereum object");
    }
  }


  {/* need a use effect function to call check if wallet is connected right inside */}
  useEffect(()=>{
    checkIfWalletIsConnected()
    checkIfTransactionsExist()
  },[])


  
  return(
<TransactionContext.Provider value={{connectWallet, currentAccount,formData,handleChange,sendTransaction,transactions,isLoading}}>
  {children} 
  
  {/*whatever we wrap inside of this transaction provider is going to be rented and 
  its going to have access to this value object*/}

</TransactionContext.Provider>)}
javascript solidity
1个回答
0
投票

面临同样的问题。请任何人帮忙!

© www.soinside.com 2019 - 2024. All rights reserved.