Example: Real Estate Tokenization Library
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract RealEstateToken is ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
struct Property {
uint256 id;
string location;
uint256 valuation;
bool forSale;
}
mapping(uint256 => Property) public properties;
event PropertyTokenized(uint256 tokenId, string location, uint256 valuation, address owner);
event PropertyForSale(uint256 tokenId, uint256 valuation);
event PropertySold(uint256 tokenId, address newOwner, uint256 salePrice);
constructor() ERC721("RealEstateToken", "RET") {}
function tokenizeProperty(string memory _location, uint256 _valuation) public onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newPropertyId = _tokenIds.current();
_mint(msg.sender, newPropertyId);
_setTokenURI(newPropertyId, _location);
properties[newPropertyId] = Property({
id: newPropertyId,
location: _location,
valuation: _valuation,
forSale: false
});
emit PropertyTokenized(newPropertyId, _location, _valuation, msg.sender);
return newPropertyId;
}
function setForSale(uint256 _tokenId, uint256 _valuation) public onlyOwnerOf(_tokenId) {
Property storage property = properties[_tokenId];
property.forSale = true;
property.valuation = _valuation;
emit PropertyForSale(_tokenId, _valuation);
}
function buyProperty(uint256 _tokenId) public payable {
Property storage property = properties[_tokenId];
require(property.forSale, "Property not for sale");
require(msg.value >= property.valuation, "Insufficient funds");
address previousOwner = ownerOf(_tokenId);
_transfer(previousOwner, msg.sender, _tokenId);
property.forSale = false;
payable(previousOwner).transfer(msg.value);
emit PropertySold(_tokenId, msg.sender, msg.value);
}
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender, "Not the owner");
_;
}
}Explanation
Example of Usage:
Explanation
Last updated