reactjs - 如何将来自ethersjs的事务哈希传递到其他函数reactjs
问题描述
我可能有一些非常简单的问题,提前感谢您的帮助!
ethersjs
使用和开发一个简单的 dApp REACTJS
。startPayment
我已经设法让付款正常工作,并在函数中查找交易哈希
问题:
- 我如何能够将数据从
const WalletDeposit
through 传递const handleSubmit
到 rawtx 中? - 我如何能够主动检查哈希是否存在,如果存在则启动
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()}>
×
</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;
解决方案
推荐阅读
- c - SPOJ - 好斗的奶牛,“最大最小距离”术语的含义是什么?
- model-view-controller - 如何使用 ASP.Net MVC 4 使用 pingfederate 配置 SAML 身份验证
- orocrm - 如何解决 ORO-CRM - 应用程序配置不正确(消息消费者不可用)。请联系系统管理员
- python - pytest 检测是否排除标记
- ruby-on-rails - Nginx + Rails + sendfile:找不到文件
- html - 两行间距问题 - HTML 模板
- python - Python - 如果添加新文本,如何每 xxx 次读取 txt 文件并添加到多进程
- javascript - 如果父类有子类,则使用 CSS 或 Jquery 隐藏母 div 次子类
- javascript - Javascript 通过 getElementbyId 访问动态创建的元素
- python - 使用 pandas 写入 csv 时如何保留格式?