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