【问题标题】:How to send eth from a specified account to a smart contract如何将 eth 从指定账户发送到智能合约
【发布时间】:2021-09-26 07:04:16
【问题描述】:

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

【问题讨论】:

  • 这取决于智能合约出口端点是否接受第三方支付的交易最终具有将 A 所有权转移到 B 的效果,如果您发布特定的合约地址会更容易跨度>
  • 嗨,我正在创建合同。可以进行任何所需的更改。

标签: ethereum solidity web3


【解决方案1】:

首先,账户 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'),
});

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2022-11-25
    • 2021-09-10
    • 2021-11-14
    • 2022-08-12
    • 2022-01-02
    • 2023-03-15
    • 2020-07-31
    • 2020-10-25
    相关资源
    最近更新 更多