You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web3.js中contract.methods.sendToOwner().send()未执行问题及解决

合约sendToOwner()函数交易收据返回成功但未执行的问题解决

问题场景

调用代码如下:

const web3 = new Web3(window.ethereum);
const contract = new web3.eth.Contract(CONTRACT.abi, contractAddress);

await contract.methods.sendToOwner().send({ from: currentAccount.address })
    .then(receipt => {
        console.log(receipt);
    });

交易收据显示成功,但合约内的sendToOwner()函数并未实际执行。调用合约的getIsSendToOwner()方法返回false,与函数执行后应返回true的预期不符。

合约代码

测试用Solidity合约代码如下:

contract UserAcc {
    address owner;
    bool isGetEther;
    bool isSendToOwner;

    modifier onlyOwner() {
        require(
            msg.sender == owner,
            "Only the contract administrator can call this function!"
        );
        _;
    }

    modifier onlyOneTranOrOnlyOwner() {
        require(!isGetEther || msg.sender == owner, 
        "Only the one transaction can be by other users!");
        _;
    }

    constructor() {
        owner = msg.sender;
    }

    receive() external payable onlyOneTranOrOnlyOwner {
        if (msg.value != 0 && !isGetEther) {
            isGetEther = true;
        }
    }

    fallback() external payable onlyOneTranOrOnlyOwner {
        if (msg.value != 0 && !isGetEther) {
            isGetEther = true;
        }
    }

    function getBalance() public view onlyOwner returns(uint) {
        return address(this).balance;
    }

    function getOwner() public view onlyOwner returns(address) {
        return owner;
    }

    function getIsSendToOwner() public view onlyOwner returns(bool) {
        return isSendToOwner;
    }

    function sendToOwner() public onlyOwner {
        (bool success, ) = owner.call{value: address(this).balance}("");
        require(success, "Transaction failed!");
        isSendToOwner = true;
    }

}

解决方法

将调用代码修改为以下形式后,问题得到解决:sendToOwner()函数正常执行,getIsSendToOwner()返回预期的true。

const web3 = new Web3(window.ethereum);
const contract = new web3.eth.Contract(CONTRACT.abi, contractAddress);

const transactionParameters = {
    to: contractAddress,
    from: currentAccount.address,
    data: contract.methods.sendToOwner().encodeABI()
};

await window.ethereum.request({
    method: "eth_sendTransaction",
    params: [transactionParameters],
})
    .then(receipt => {
        console.log(receipt);
    });

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:35:21