Skip to content

Instantly share code, notes, and snippets.

@Mexidense
Last active May 7, 2024 18:01
Show Gist options
  • Save Mexidense/506448745b66cec6c3606c07e59b9551 to your computer and use it in GitHub Desktop.
Save Mexidense/506448745b66cec6c3606c07e59b9551 to your computer and use it in GitHub Desktop.
NFT Marketplace
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts@4.9.0/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts@4.9.0/security/ReentrancyGuard.sol";
contract Marketplace is ReentrancyGuard {
address payable public immutable feeAccount;
uint public immutable feePercentage;
uint public itemsCount;
struct Item {
uint itemId;
IERC721 nft;
uint tokenId;
uint price;
address payable seller;
bool isSold;
}
mapping (uint => Item) public items;
event Offered (
uint itemId,
address indexed nft,
uint tokenId,
uint price,
address indexed seller
);
event Bought (
uint itemId,
address indexed nft,
uint tokenId,
uint price,
address indexed seller,
address indexed buyer
);
constructor (uint _feePercentage) {
feeAccount = payable(msg.sender);
feePercentage = _feePercentage;
}
function makeItem(IERC721 _nft, uint _tokenId, uint _price) external nonReentrant {
require(_price > 0, "Price must be over 0");
itemsCount++;
_nft.transferFrom(msg.sender, address(this), _tokenId);
items[itemsCount] = Item(
itemsCount,
_nft,
_tokenId,
_price,
payable(msg.sender),
false
);
emit Offered(itemsCount, address(_nft), _tokenId, _price, msg.sender);
}
function purchaseItem(uint _itemId) external payable nonReentrant {
uint _totalPrice = getTotalPrice(_itemId);
Item storage item = items[_itemId];
require(_itemId > 0 && _itemId <= itemsCount, "Item ID must be greater than 0");
require(msg.value > 0, "Amount paid must be greater than 0");
require(!item.isSold, "Item is sold");
item.seller.transfer(item.price);
feeAccount.transfer(_totalPrice - item.price);
item.isSold = true;
item.nft.transferFrom(address(this), msg.sender, item.tokenId);
emit Bought(
_itemId,
address(item.nft),
item.tokenId,
item.price,
item.seller,
msg.sender
);
}
function getTotalPrice(uint _itemId) view public returns (uint) {
return ((items[_itemId].price * (100 + feePercentage)) / 100);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@openzeppelin/contracts@4.9.0/token/ERC721/extensions/ERC721URIStorage.sol";
contract NFT is ERC721URIStorage {
uint public tokenCount;
constructor() ERC721("DApp NFT", "DAPP") {}
function mint(string memory _tokenUri) external returns (uint) {
tokenCount++;
_safeMint(msg.sender, tokenCount);
_setTokenURI(tokenCount, _tokenUri);
return tokenCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment