Skip to content

Instantly share code, notes, and snippets.

@shobhitic
Last active August 12, 2023 03:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save shobhitic/63b6c58b5897886d39cd014a24c045de to your computer and use it in GitHub Desktop.
Save shobhitic/63b6c58b5897886d39cd014a24c045de to your computer and use it in GitHub Desktop.
Simple NFT Staking Smart Contract - https://youtu.be/m0w6JyqJKks
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts@4.6.0/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts@4.6.0/access/Ownable.sol";
contract MyNFT is ERC721, Ownable {
uint256 public totalSupply;
constructor() ERC721("MyNFT", "MNFT") {}
function safeMint(address to) public {
totalSupply++;
_safeMint(to, totalSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
contract MyToken is ERC20, ERC721Holder, Ownable {
IERC721 public nft;
mapping(uint256 => address) public tokenOwnerOf;
mapping(uint256 => uint256) public tokenStakedAt;
uint256 public EMISSION_RATE = (50 * 10 ** decimals()) / 1 days;
constructor(address _nft) ERC20("MyToken", "MTK") {
nft = IERC721(_nft);
}
function stake(uint256 tokenId) external {
nft.safeTransferFrom(msg.sender, address(this), tokenId);
tokenOwnerOf[tokenId] = msg.sender;
tokenStakedAt[tokenId] = block.timestamp;
}
function calculateTokens(uint256 tokenId) public view returns (uint256) {
uint256 timeElapsed = block.timestamp - tokenStakedAt[tokenId];
return timeElapsed * EMISSION_RATE;
}
function unstake(uint256 tokenId) external {
require(tokenOwnerOf[tokenId] == msg.sender, "You can't unstake");
_mint(msg.sender, calculateTokens(tokenId)); // Minting the tokens for staking
nft.transferFrom(address(this), msg.sender, tokenId);
delete tokenOwnerOf[tokenId];
delete tokenStakedAt[tokenId];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment