简体   繁体   English

将 ERC721 从所有者转让给买家

[英]Transfer ERC721 from owner to buyer

I'm trying to let other address execute the buy function, but it throws me the error ERC721: approve caller is not owner nor approved for all this is the code我试图让其他地址执行购买 function,但它向我抛出了错误ERC721: approve caller is not owner nor approved for all this is the code

function testbuy() public payable{
    require(ownerOf(1) == _owner, "Already bought");
    approve(msg.sender, 1);
    safeTransferFrom(_owner, msg.sender, 1);
}

How could I make other address buy the NFT from the owner address?如何让其他地址从所有者地址购买 NFT? I'm having trouble understanding approve and setApproveForAll.. Thanks:)我无法理解批准和 setApproveForAll .. 谢谢:)

Based on the error message, I'm assuming that you're using the Openzeppelin implementation of ERC721.根据错误消息,我假设您使用的是 ERC721 的 Openzeppelin 实现。

Since your contract derives from the OZ implementation, you can use their internal functions and don't need to go through the approve() and safeTransferFrom() process.由于你的合约是从 OZ 实现派生的,你可以使用它们的internal函数,而不需要通过approve()safeTransferFrom()过程来 go。 If you wanted to go this way, you would need to invoke the approve() function from the _owner address directly - not by the buying user through the testbuy() function, as this was the logical error in your code.如果您想以这种方式 go,则需要直接从_owner地址调用approve() function - 而不是购买用户通过testbuy() ZC1C425268E68385D1AB5074F14 中的逻辑错误。

Specifically, you can use the _transfer() function ( source ):具体来说,您可以使用_transfer() function ( source ):

function testbuy() public payable{
    require(ownerOf(1) == _owner, "Already bought");
    _transfer(_owner, msg.sender, 1);
}

You can find your error OpenZeppelin ERC721 here:您可以在此处找到错误 OpenZeppelin ERC721:

function approve(address to, uint256 tokenId) public virtual override {
    address owner = ERC721.ownerOf(tokenId);
    require(to != owner, "ERC721: approval to current owner");

    require(
        _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
        "ERC721: approve caller is not owner nor approved for all"
    );

    _approve(to, tokenId);
}

Address which is calling testbuy() function has to be the owner of the token.调用 testbuy() function 的地址必须是令牌的所有者。 In other case it cannot give the approval (or the token has to have approval for all), hence the approve function.在其他情况下,它不能给予批准(或者令牌必须得到所有人的批准),因此批准 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM