首页 > 解决方案 > 如何将来自ethersjs的事务哈希传递到其他函数reactjs

问题描述

我可能有一些非常简单的问题,提前感谢您的帮助!

ethersjs使用和开发一个简单的 dApp REACTJSstartPayment我已经设法让付款正常工作,并在函数中查找交易哈希

问题:

  1. 我如何能够将数据从const WalletDepositthrough 传递const handleSubmit到 rawtx 中?
  2. 我如何能够主动检查哈希是否存在,如果存在则启动const postTransaction功能?

附加信息:console.log('Hash', txhash)at 行在line 56付款后会收到交易哈希。但我无法使用handleSubmit 中的数据。我已经尝试使用 useState 创建一个变量,但没有让我到任何地方。

到目前为止我的代码:

import React, {useState, useEffect} from 'react';
import axios from 'axios';
import { ethers } from "ethers";
import ErrorMessage from "./ErrorMessage";
import TxList from "./TxList";

import UserService from "../../../services/user.service";
 
const startPayment = async ({ setError, setTxs, setHash, ether, addr }) => {

    try {
      if (!window.ethereum)
        throw new Error("No crypto wallet found. Please install it.");
  
      await window.ethereum.send("eth_requestAccounts");
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      
      // const userAddress = await signer.getAddress();

      ethers.utils.getAddress(addr);
      const tx = await signer.sendTransaction({
        to: addr,
        value: ethers.utils.parseEther(ether)
      });
      setTxs([tx]);
      setHash([tx][0].hash);

      
    } catch (err) {
      if (err.message === 'Internal JSON-RPC error.') {
        setError("Check your balance, insufficient funds")
      } 
      if (err.message === 'MetaMask Tx Signature: User denied transaction signature.') {
        setError("You have rejected the transaction!")
      }
      else {
        setError(err.message);
      }
    }
};


const WalletDeposit = ({show, close}) => {
    const [price, setPrice] = useState('');

    const [firstName, setFirstName] = useState('');
    const [error, setError] = useState();
    const [txs, setTxs] = useState([]);
    const [txhash, setHash] = useState();

    const [totalTokens, setTokens] = useState();
    const [tokenPrice, setTokenPrice] = useState();
    const [checkboxvalue1, setCheckboxValue1] = useState('');

    console.log('Hash: ', txhash);
  
  
    const handleSubmit = async (e) => {
      e.preventDefault();
      const data = new FormData(e.target);
      const tokens = data.get("tokens");
      const tokenPrice = tokens / price.usd;
      
      setTokens(tokens);
      setTokenPrice(tokenPrice);

        
  
      setError();
      await startPayment({
        setError,
        setTxs,
        setHash,
        ether: tokenPrice.toString(),
        addr: '0x000000000000000000000000000' <= not using this address ;)
      });

      const postTransaction = () => {
        const rawtx = {
          "type": "deposit",
          "status": "pending",
          "fees": 2,
          "txamount": tokens,
          "ticker": "usd",
          "txhash": txhash,
          "product": 0,
          "ethPrice": tokenPrice.toString()
        };

        
        
        UserService.postTransactionType(rawtx)
          .then( 
            response => {
              close()
              window.location.reload();
              alert('We have received a deposit and it will be checked, the status will be updated in your transaction overview.');
              return response.data.data
            }
          )
          .catch(error => {
                console.error('There was an error!', error);
          });
        }

        if (!txhash === '') {
          postTransaction();
        }
    };

    const calculatePrice = () => {
        axios.get('http://api.coingecko.com/api/v3/simple/price?ids=binancecoin&vs_currencies=usd')
        .then((response) => {
            setPrice(response.data.binancecoin)
        })
    } 
    
    useEffect(() => {
        calculatePrice()
    }, []);
       
    return (
        <>
        
      {
        show ?
            <div className="popup popup_settings" id="popup-settings">
                <div className="popup-wrapper">
                    <button className="close" onClick={() => close()}>
                        &times;
                    </button>

                    <div className="popup__title h6">Deposit Funds</div>
                    
                    <form className="popup__form" onSubmit={handleSubmit}>
                        <div className="popup__field field js-field">
                            <div className="field__label">Amount in USD</div>
                            <div className="field__wrap">
                                <input className="field__input js-field-input" 
                                name="tokens"
                                min={1}
                                type="number"
                                onChange={e => setFirstName(e.target.value)}
                                />
                            </div>
                        </div>
                        <div>
                          Amount USD in BNB: {firstName / price.usd} 
                          {/* (amount (usd price) : bnb price (calc)) */}
                        </div>
                        
                        <div className="popup__variants">
                            <label className="checkbox">
                                <input className="checkbox__input" type="checkbox"
                                onChange={() => setCheckboxValue1(!checkboxvalue1)} />
                                <span className="checkbox__in">
                                    <span className="checkbox__tick"></span>
                                    <span className="checkbox__text">
                                        I hereby confirm that I will add funds and can't redo this unless I withdraw my funds.
                                    </span>
                                </span>
                            </label>
                        </div>
                        <button
                            type="submit"
                            className="popup__btn btn btn_blue btn_wide"
                            className={!checkboxvalue1 ? "popup__btn btn btn_gray btn_wide" : "popup__btn btn btn_blue btn_wide"}
                            disabled={!checkboxvalue1}
                            >
                            Buy now
                        </button>
                        <ErrorMessage message={error} />
                        <TxList txs={txs} />
                    </form>
                
                </div>
            </div>
    
    : null
  }
        </>
        
    );
    
}

export default WalletDeposit;

标签: reactjshashtransactionsmetamaskethers.js

解决方案


推荐阅读