Solidity

NFT 市場如何運作?

  • October 16, 2021

如果我想實現一個小型 NFT 市場並希望使用者能夠出售物品,而其他使用者可以購買這些物品,我應該怎麼做?每次有人出售某物時,我是否需要製定獲得批准的市場契約,並且當有人購買該物品時,契約將執行該safeTransferFrom功能?

是的,這是人們通常這樣做的一種方式。

如果您的市場僅適用於一種特定代幣,則可以使用更好的選擇。

我使用這個契約:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.9.0;

import '@openzeppelin-contracts/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin-contracts/contracts/finance/PaymentSplitter.sol';

contract BALANCE is ERC721 {
   event NftBought(address _seller, address _buyer, uint256 _price);

   mapping (uint256 => uint256) public tokenIdToPrice;
   uint public nextTokenId;
     address public admin;

   constructor() ERC721('Balance', 'BALANCE') {
         admin = msg.sender;
   }
   
     function mint(address to) external {
   require(msg.sender == admin, 'only admin');
   if(nextTokenId < 2){_safeMint(to, nextTokenId);
   nextTokenId++;
   }
 } 
   
             function _baseURI() internal view override returns (string memory) {
   return 'https://.herokuapp.com/';
 }

   function allowBuy(uint256 _tokenId, uint256 _price) external {
       require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
       require(_price > 0, 'Price zero');
       tokenIdToPrice[_tokenId] = _price;
   }

   function disallowBuy(uint256 _tokenId) external {
       require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
       tokenIdToPrice[_tokenId] = 0;
   }
   
   function buy(uint256 _tokenId) external payable {
       uint256 price = tokenIdToPrice[_tokenId];
       require(price > 0, 'This token is not for sale');
       require(msg.value == price, 'Incorrect value');
       
       address seller = ownerOf(_tokenId);
       _transfer(seller, msg.sender, _tokenId);
       tokenIdToPrice[_tokenId] = 0; // not for sale anymore
       payable(seller).transfer(msg.value); // send the ETH to the seller

       emit NftBought(seller, msg.sender, msg.value);
   }
}

我呼叫 allowBuy(’tokenId’, ‘prince_in_WEI’) 來設置 id 價格,然後發送 buy(’tokenId’) 儘管我遇到了大數字的問題。

引用自:https://ethereum.stackexchange.com/questions/98826