5 调用metamask向合约转账,交易失败。

触发事件后,metamask 提示,转账不能成功,但在remix和etherscan均能正常执行。请问如何解决?

This transaction is expected to fail. Trying to execute it is expected to be expensive but fail, and is not recommended.

React代码

async function payWithMetamask() {
let ethereum = window.ethereum;
// Request account access if needed
await ethereum.enable();
let provider = new ethers.providers.Web3Provider(ethereum);    

// Acccounts now exposed
const tx = [{
    from: walletAddress,
    to: contractAddress,
    value: ethers.utils.parseUnits('1000000', 'gwei').toHexString(),
}];

const transactionHash = await provider.send('eth_sendTransaction', tx)
console.log('transactionHash is ' + transactionHash);

}

合约代码

function buy() public payable{
        uint256 amount = msg.value;
        address buyer = msg.sender;
        require(amount > 1000, 'money not enjoy.'); 
        acl.push(buyer);
    }
请先 登录 后评论

最佳答案 2022-04-11 15:13

你这个是使用错误,我ethers用的少,你搜索解决下。。

合约代码是需要调用buy方法的。 而你的交易tx里面并没有data,也就是直接给合约发eth. 这个需要有声明回调函数才可以接eth.

你可以在tx里面增加data字段,填 0xa6f2ae3a 试试能不能发成功

请先 登录 后评论

其它 1 个回答

hunk
请先 登录 后评论