如何从指定账户发送eth到智能合约

How to send eth from a specified account to a smart contract

如果我想将 NFT 从账户 A 转移到账户 B,假设它需要支付 X 的金额。但是我想要另一个特定的帐户 C(不是在开发服务器上,而是一个实际的以太坊地址)来支付 X 的金额。可以做到吗?如果是这样,我如何使用 web3 从前端进行操作?感谢您的帮助。

首先,账户 A(NFT 发送方)需要 approve() Mediator 智能合约他们想要转移的特定代币。

Mediator 智能合约将只接受账户 C 的付款,并执行很少的其他验证(例如金额和检查是否真的允许操作令牌)。然后它将执行实际的代币转移和 ETH 转移(这样它就不会卡在 Mediator 合约上)。

pragma solidity ^0.8;

interface IERC721 {
    function getApproved(uint256 _tokenId) external view returns (address);
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}

contract Mediator {
    address accountA = address(0x123);
    address accountB = address(0x456)
    address accountC = address(0x789);
    uint256 amount = 1 ether;
    uint256 tokenId = 1;
    address collection = address(0xabc);

    function foo() external payable {
        require(msg.sender === accountC, 'Only accepting payment from Account C');
        require(msg.value === amount, 'Incorrect amount');

        IERC721 collection = IERC721(collection);
        require(collection.getApproved(tokenId) === address(this), 'This contract is not approved to operate the token');
        
        // transfer the NFT from Account A to Account B
        collection.safeTransferFrom(accountA, accountB, tokenId);
        
        // redirect the payment (from Account C to this contract) to Account A
        payable(accountA).transfer(msg.value);
    }
}

最后,您可以使用 web3 调用 Mediator foo() 功能。如果不满足任何条件(例如发件人不是账户 C 时),它将失败。

const contract = new web3.eth.Contract(jsonAbi, contractAddress);
const tx = await contract.methods.foo().send({
    from: accountC,
    value: web3.utils.toWei(1, 'ether'),
});