我正在NextJS中的NFT网站上工作,并试图在他们成功创建令牌后为用户实现重定向。这是我的mint代码:
const mintToken = () => {
safeMint?.();
router.push('/success');
};
正如您所看到的,在调用safeMint
之后,我尝试重定向到/success
,这就是所发生的。但是,它会重定向,无论薄荷是否成功,我希望它只在对智能合约的调用成功后才重定向。我试过使用回调和超时,但似乎没有工作的方式,我上面列出。在重定向之前,是否有某种方法可以获得或等待成功响应?谢谢!
如果在事务中执行函数,则函数返回值在EVM之外不可用。
您可以等待交易收据。它包含事务状态(成功/恢复)以及事件日志。只有当Tx被包含在一个块中时,才有接收。
根据您的safeMint()
实现,它可能在每次事务成功时生成令牌。但是,如果您的实现允许函数在没有生成令牌的情况下也能成功,则可能需要检查事件日志以确保NFT确实被生成了。
// transaction reverted
function safeMint() external {
require(failedCondition);
_mint(msg.sender, tokenId);
}
// transaction succeeded but no token was minted
function safeMint() external {
if (failedCondition) {
_mint(msg.sender, tokenId);
}
}
如何用ethers
等待收据:
const tx = await myContract.safeMint();
const txReceipt = await transaction.wait();
if (txReceipt.status) {
// not reverted
}
文档:
- https://docs.ethers.io/v5/api/providers/types/providers-TransactionResponse
- https://docs.ethers.io/v5/api/providers/types/providers-TransactionReceipt
在safeMint
函数内部契约中,您可以返回tokenId
(或者您可以返回true)
const mintToken =async () => {
const result=await safeMint?();
if(result){
router.push('/success');
}
};