Created
October 25, 2021 11:04
-
-
Save AliWisam/6a996f6fa9d003ff7ec126983da35d27 to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.8.7+commit.e28d00a7.js&optimize=true&runs=200&gist=
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//SPDX-License-Identifier: UNLICENSED | |
pragma solidity ^0.8.4; | |
contract ParentVehicle { | |
function start() public pure virtual returns(string memory){ | |
string memory message = "The Vehicle has just Started"; | |
return message; | |
} | |
function accelerate() public pure virtual returns(string memory ){ | |
string memory message = "The Vehicle has just Accelerated"; | |
return message; | |
} | |
function stop() public pure virtual returns(string memory){ | |
string memory message = "The Vehicle has just Stopped"; | |
return message; | |
} | |
function service() public pure virtual returns(string memory){ | |
string memory message = "The Vehicle is being serviced"; | |
return message; | |
} | |
} | |
contract Cars is ParentVehicle{ | |
function service() public pure override returns(string memory){ | |
string memory message = "The Car is being serviced"; | |
return message; | |
} | |
} | |
contract Truck is ParentVehicle{ | |
function service() public pure override returns(string memory){ | |
string memory message = "The Truck is being serviced"; | |
return message; | |
} | |
} | |
contract MotorCycle is ParentVehicle{ | |
function service() public pure override returns(string memory){ | |
string memory message = "The MotorCycle is being serviced"; | |
return message; | |
} | |
} | |
contract AltoMehran is Cars{ | |
} | |
contract Hino is Truck{ | |
} | |
contract Yamaha is MotorCycle{ | |
} | |
contract ServiceStation{ | |
function vehicleServiceCar(AltoMehran _car) public pure returns(string memory){ | |
return _car.service(); | |
} | |
function vehicleServiceTruck(Hino _truck) public pure returns(string memory){ | |
return _truck.service(); | |
} | |
function vehicleServiceMotorCycle(Yamaha _motorCycle) public pure returns(string memory){ | |
return _motorCycle.service(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; | |
contract MyBank is Ownable{ | |
uint256 private totalBalance; | |
address[] accounts; | |
mapping(address => uint256) private balanceOfAccount; | |
mapping(address => uint256) private initialDeposit; | |
mapping(address => bool) private hasAccount; | |
mapping(address => accountsCloseRequestsStruct) private accCloseMapping; | |
address[] private reqAddrArr; | |
struct accountsCloseRequestsStruct{ | |
bool accoutCloseRequest; | |
string reason; | |
} | |
event ContractBalance(uint256 contractBalance); | |
event BankClosed(string message); | |
event AccountOpenedBy(address acc); | |
event Deposit(uint256 bal); | |
event WithdrewBy(address addr); | |
event WithdrewValue(uint256 val); | |
event BonusValue(uint256 bonusValue); | |
event AccountCloseRequest(address addr, string reason ); | |
event AccountClosed(address addr); | |
constructor() payable { | |
require(msg.value >= 50 ether,"constructor: Initial deposit should be equal to greater than 50"); | |
payable(address(this)).transfer(msg.value); | |
totalBalance += msg.value; | |
emit ContractBalance(totalBalance); | |
} | |
function closeBank() public onlyOwner returns(bool){ | |
selfdestruct(payable(msg.sender)); | |
emit BankClosed("Transferred all balance to owner and bank is closed"); | |
return true; | |
} | |
function openNewAccount() public payable returns(bool){ | |
require(hasAccount[msg.sender] == false,"You have already created your account"); | |
require(msg.value >= 1 ether,"openNewAccount: Initial deposit should be equal to greater than 1"); | |
totalBalance += msg.value; | |
hasAccount[msg.sender] = true; | |
initialDeposit[msg.sender] = msg.value; | |
balanceOfAccount[msg.sender] += msg.value; | |
accounts.push(msg.sender); | |
emit AccountOpenedBy(msg.sender); | |
emit Deposit(msg.value); | |
emit ContractBalance(totalBalance); | |
return true; | |
} | |
function getBalanceByAddress(address _addr) external view onlyOwner returns(uint256){ | |
return balanceOfAccount[_addr]; | |
} | |
function getBalanceUser() external view returns(uint256){ | |
return balanceOfAccount[msg.sender]; | |
} | |
function getBalanceByIndex(uint256 _index) external view onlyOwner returns(uint256){ | |
return balanceOfAccount[accounts[_index]]; | |
} | |
function depositEther() external payable returns(bool){ | |
require(msg.value != 0,"msg.value should not be equal to zero, please send some ethers"); | |
totalBalance += msg.value; | |
balanceOfAccount[msg.sender] += msg.value; | |
accounts.push(msg.sender); | |
return true; | |
} | |
function withdrawEthers(uint256 _amount) external returns(bool){ | |
require(hasAccount[msg.sender] == true,"you are not valid account holder"); | |
require(_amount<= balanceOfAccount[msg.sender],"withdraw amount should be less then your balance"); | |
totalBalance -= _amount; | |
balanceOfAccount[msg.sender] -= _amount; | |
emit WithdrewBy(msg.sender); | |
emit WithdrewValue(_amount); | |
return true; | |
} | |
function bonus() external onlyOwner{ | |
for(uint256 i = 0; i<= 4; i++){ | |
payable(accounts[i]).transfer(1 ether); | |
totalBalance -= 1 ether; | |
balanceOfAccount[accounts[i]] += 1 ether; | |
} | |
emit BonusValue(1 ether); | |
} | |
function accountCloseRequest(string memory _reason) external returns(bool){ | |
accCloseMapping[msg.sender].accoutCloseRequest = true; | |
accCloseMapping[msg.sender].reason = _reason; | |
reqAddrArr.push(msg.sender); | |
emit AccountCloseRequest(msg.sender, accCloseMapping[msg.sender].reason); | |
return true; | |
} | |
function getCloseRequestedAccounts() external onlyOwner view returns(address[] memory){ | |
return reqAddrArr; | |
} | |
function closeAccount(address _add) external onlyOwner returns(bool success){ | |
hasAccount[msg.sender] == false; | |
payable(_add).transfer(balanceOfAccount[_add]); | |
delete accCloseMapping[msg.sender]; | |
uint256 index = getIndexToDel(_add); | |
for(uint256 i = index; i < reqAddrArr.length - 1; i++){ | |
reqAddrArr[i] = reqAddrArr[i + 1]; | |
} | |
reqAddrArr.pop(); | |
emit AccountClosed(_add); | |
return true; | |
} | |
function getIndexToDel(address _add) internal view returns(uint256 index){ | |
for(uint256 i = 0; i<=reqAddrArr.length; i++){ | |
if(reqAddrArr[i] == _add){ | |
return i; | |
} | |
} | |
} | |
function getAllAccounts() external view onlyOwner returns(address[] memory){ | |
return accounts; | |
} | |
function getTotalBalance() external view onlyOwner returns(uint256,uint256 totalBalanceC){ | |
return (totalBalance, address(this).balance); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.2; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/ERC20.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Capped.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; | |
contract MyToken is ERC20Capped, Ownable { | |
using SafeMath for uint256; | |
// timestamp when token release is enabled | |
uint256 private immutable _releaseTime; | |
uint256 price; // the price, in wei, per token | |
constructor( | |
string memory name, | |
string memory symbol, | |
uint256 cap, | |
uint256 _price | |
) | |
ERC20(name, symbol) | |
ERC20Capped(cap) | |
{ | |
price = _price; | |
_releaseTime = block.timestamp + 30 days; | |
} | |
function buyTokens() public payable{ | |
uint256 scaledAmount = msg.value.mul(10 ** decimals()).div(price); | |
_mint(msg.sender, scaledAmount); | |
} | |
function setPrice(uint256 _price) public onlyOwner returns(uint256){ | |
price = _price; | |
return price; | |
} | |
// This function is called for all messages sent to | |
// this contract, except plain Ether transfers | |
// (there is no other function except the receive function). | |
// Any call with non-empty calldata to this contract will execute | |
// the fallback function (even if Ether is sent along with the call). | |
fallback() external payable { | |
buyTokens(); | |
} | |
// This function is called for plain Ether transfers, i.e. | |
// for every call with empty calldata. | |
receive() external payable { } | |
//anyone can also direct buy tokens | |
// function buy(uint256 numberOfTokens) public payable onlyOwner { | |
// require(msg.value == numberOfTokens.mul(price)); | |
// uint256 scaledAmount = numberOfTokens.mul(uint256(10) ** decimals()); | |
// _mint(msg.sender, scaledAmount); | |
// } | |
/** | |
* @return the time when the tokens are released. | |
*/ | |
function releaseTime() public view virtual returns (uint256) { | |
return _releaseTime; | |
} | |
function mint(uint256 _amount) public { | |
_mint(owner(), _amount); | |
} | |
function transfer(address recepient, uint256 amount) public override returns (bool){ | |
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); | |
super._transfer(msg.sender,recepient,amount); | |
return true; | |
} | |
function transferFrom(address sender,address recepient, uint256 amount) public override returns (bool){ | |
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); | |
super._transfer(sender,recepient,amount); | |
return true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.2; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC20Capped.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/AccessControl.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol"; | |
contract MyToken is ERC20Capped, Ownable, AccessControl { | |
using SafeMath for uint256; | |
bytes32 public constant PRICE_CHANGE_ROLE = keccak256("PRICE_CHANGE_ROLE"); | |
// timestamp when token release is enabled | |
uint256 private immutable _releaseTime; | |
uint256 price; // the price, in wei, per token | |
event TokenValue(uint256 withDecimals, uint256 withoutDecimals); | |
constructor( | |
string memory name, | |
string memory symbol, | |
uint256 cap, | |
uint256 _price | |
) | |
ERC20(name, symbol) | |
ERC20Capped(cap) | |
{ | |
price = _price; | |
_releaseTime = block.timestamp + 30 days; | |
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); | |
_setupRole(PRICE_CHANGE_ROLE, msg.sender); | |
} | |
// This function is called for all messages sent to | |
// this contract, except plain Ether transfers | |
// (there is no other function except the receive function). | |
// Any call with non-empty calldata to this contract will execute | |
// the fallback function (even if Ether is sent along with the call). | |
fallback() external payable { | |
buyTokens(); | |
} | |
function buyTokens() public payable returns(uint256){ | |
require(msg.value != 0,"Value shouldn't be equal to zero"); | |
uint256 scaledAmount = msg.value.mul(10 ** decimals()).div(price); | |
_mint(msg.sender, scaledAmount); | |
emit TokenValue(scaledAmount,scaledAmount.div(10 ** decimals())); | |
return scaledAmount; | |
} | |
/** | |
* @return the time when the tokens are released. | |
*/ | |
function releaseTime() public view virtual returns (uint256) { | |
return _releaseTime; | |
} | |
function mint(uint256 _amount) internal { | |
_mint(owner(), _amount); | |
} | |
function changePrice(uint256 _price) public onlyRole(PRICE_CHANGE_ROLE) returns(uint256){ | |
price = _price; | |
return price; | |
} | |
function transfer(address recepient, uint256 amount) public override returns (bool){ | |
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); | |
super._transfer(msg.sender,recepient,amount); | |
return true; | |
} | |
function transferFrom(address sender,address recepient, uint256 amount) public onlyRole(PRICE_CHANGE_ROLE) override returns (bool){ | |
require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); | |
super._transfer(sender,recepient,amount); | |
return true; | |
} | |
function sellToken(uint256 _tokenAmount) external returns(uint256){ | |
require(transfer(owner(), _tokenAmount) == true,"Error in Token Transfer"); | |
uint256 scaledAmount = _tokenAmount.div(price); | |
payable(msg.sender).transfer(scaledAmount * 1 ether); | |
return scaledAmount * 1 ether; | |
} | |
// This function is called for plain Ether transfers, i.e. | |
// for every call with empty calldata. | |
receive() external payable { } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.2; | |
import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; | |
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; | |
import "@openzeppelin/contracts/access/Ownable.sol"; | |
import "@openzeppelin/contracts/utils/Counters.sol"; | |
contract MyToken is ERC721, ERC721URIStorage, Ownable { | |
using Counters for Counters.Counter; | |
Counters.Counter private _tokenIdCounter; | |
bool private saleStarted; | |
uint256 private saleStartTime; | |
uint256 private saleEndTime; | |
uint256 private NFTPRice; | |
constructor(uint256 _NFTPriceInWei) ERC721("MyToken", "MTK") { | |
NFTPRice = _NFTPriceInWei; | |
} | |
modifier saleCheck{ | |
require(saleStarted == true,""); | |
_; | |
} | |
//buy NFT | |
function buyNFT() public payable returns(bool){ | |
require(msg.value ==NFTPRice ,"please buy with correct price"); | |
require(saleStarted == true && block.timestamp >= saleStartTime && block.timestamp <= saleEndTime,"Sale not started or ended yet"); | |
safeMint(msg.sender,"https://floydnft.com/token/""); | |
return true; | |
} | |
function getNFTPrice() public view returns(uint256){ | |
return NFTPRice; | |
} | |
function changePrice(uint256 _NFTPriceInWei) external onlyOwner returns(uint256){ | |
NFTPRice = _NFTPriceInWei; | |
return NFTPRice; | |
} | |
function changeTokenURI(uint256 tokenId, string memory _tokenURI) public { | |
_setTokenURI(tokenId,_tokenURI); | |
} | |
//setURI | |
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal override(ERC721URIStorage){ | |
require(msg.sender == ownerOf(tokenId),"you are not owner of this token"); | |
super._setTokenURI(tokenId,_tokenURI); | |
} | |
function safeMint(address to, string memory _tokenURI) internal { | |
_safeMint(to, _tokenIdCounter.current()); | |
_setTokenURI(_tokenIdCounter.current(), _tokenURI); | |
_tokenIdCounter.increment(); | |
} | |
function startSale() public returns(bool){ | |
saleStarted = true; | |
saleStartTime = block.timestamp; | |
saleEndTime = block.timestamp + 30 days; | |
return true; | |
} | |
function endSale() public returns(bool){ | |
saleStarted = false; | |
return false; | |
} | |
// The following functions are overrides required by Solidity. | |
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { | |
super._burn(tokenId); | |
} | |
function tokenURI(uint256 tokenId) | |
public | |
view | |
override(ERC721, ERC721URIStorage) | |
returns (string memory) | |
{ | |
return super.tokenURI(tokenId); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.4; | |
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; | |
import '@openzeppelin/contracts/access/Ownable.sol'; | |
contract Reflective is ERC721Enumerable, Ownable { | |
using Address for address; | |
// Starting and stopping sale and presale | |
bool public saleActive = false; | |
bool public presaleActive = false; | |
uint256 counter = 0; | |
// Reserved for the team, customs, giveaways, collabs and so on. | |
uint256 public reserved = 60; | |
// Price of each token | |
uint256 public price = 0.08 ether; | |
// Maximum limit of tokens that can ever exist | |
uint256 constant MAX_SUPPLY = 10000; | |
uint256 public remainingTokens = MAX_SUPPLY; | |
// The base link that leads to the image / video of the token | |
string public baseTokenURI; | |
//to show moc | |
string public blankURI; | |
// List of addresses that have a number of reserved tokens for presale | |
mapping (address => uint256) public presaleReserved; | |
constructor (string memory newBaseURI) ERC721 ("Reflective Collective", "RC") { | |
remainingTokens = remainingTokens - reserved; | |
setBaseURI(newBaseURI); | |
} | |
// Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead | |
function _baseURI() internal view virtual override returns (string memory) { | |
return baseTokenURI; | |
} | |
// See which address owns which tokens | |
function tokensOfOwner(address addr) public view returns(uint256[] memory) { | |
uint256 tokenCount = balanceOf(addr); | |
uint256[] memory tokensId = new uint256[](tokenCount); | |
for(uint256 i; i < tokenCount; i++){ | |
tokensId[i] = tokenOfOwnerByIndex(addr, i); | |
} | |
return tokensId; | |
} | |
// Exclusive presale minting | |
function mintPresale() public payable { | |
uint256 supply = totalSupply(); | |
uint256 reservedAmt = presaleReserved[msg.sender]; | |
require( presaleActive, "Presale isn't active" ); | |
require( reservedAmt > 0, "No tokens reserved for your address" ); | |
require( reservedAmt <= 0, "Can't mint more than reserved" ); | |
require( supply <= MAX_SUPPLY, "Can't mint more than max supply" ); | |
require( msg.value == price, "Wrong amount of ETH sent" ); | |
presaleReserved[msg.sender] = reservedAmt - 1; | |
_safeMint( msg.sender, supply + 1 ); | |
remainingTokens--; | |
counter++; | |
} | |
// Standard mint function1 | |
function mintToken() public payable { | |
require( msg.value == price, "Wrong amount of ETH sent" ); | |
payable(owner()).transfer(msg.value); | |
uint256 supply = totalSupply(); | |
require( saleActive, "Sale isn't active" ); | |
require( supply + 1 <= MAX_SUPPLY, "Can't mint more than max supply" ); | |
_safeMint( msg.sender, supply + 1 ); | |
remainingTokens--; | |
counter++; | |
} | |
//withdraw ethers() from contract onlyy Admin | |
function withdrawfunds() public onlyOwner payable{ | |
require(msg.sender==owner(),"only Owner can call this function"); | |
payable(owner()).transfer(address(this).balance); | |
} | |
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways | |
function mintReserved(uint256 _amount) public onlyOwner { | |
// Limited to a publicly set amount | |
require( _amount <= reserved, "Can't reserve more than set amount" ); | |
reserved -= _amount; | |
uint256 supply = totalSupply(); | |
for(uint256 i; i < _amount; i++){ | |
_safeMint( msg.sender, supply + i ); | |
remainingTokens--; | |
} | |
} | |
// Edit reserved presale spots | |
function editPresaleReserved(address[] memory _a, uint256 _amount) public onlyOwner { | |
for(uint256 i; i < _a.length; i++){ | |
presaleReserved[_a[i]] = _amount; | |
} | |
} | |
// Start and stop presale | |
function setPresaleActive(bool val) public onlyOwner { | |
presaleActive = val; | |
} | |
// Start and stop sale | |
function setSaleActive(bool val) public onlyOwner { | |
saleActive = val; | |
} | |
// Set new baseURI | |
function setBaseURI(string memory baseURI) public onlyOwner { | |
baseTokenURI = baseURI; | |
} | |
// Set a different price in case ETH changes drastically | |
function setPrice(uint256 newPrice) public onlyOwner { | |
price = newPrice; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
// File: @openzeppelin/contracts/utils/Strings.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev String operations. | |
*/ | |
library Strings { | |
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` decimal representation. | |
*/ | |
function toString(uint256 value) internal pure returns (string memory) { | |
// Inspired by OraclizeAPI's implementation - MIT licence | |
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol | |
if (value == 0) { | |
return "0"; | |
} | |
uint256 temp = value; | |
uint256 digits; | |
while (temp != 0) { | |
digits++; | |
temp /= 10; | |
} | |
bytes memory buffer = new bytes(digits); | |
while (value != 0) { | |
digits -= 1; | |
buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); | |
value /= 10; | |
} | |
return string(buffer); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. | |
*/ | |
function toHexString(uint256 value) internal pure returns (string memory) { | |
if (value == 0) { | |
return "0x00"; | |
} | |
uint256 temp = value; | |
uint256 length = 0; | |
while (temp != 0) { | |
length++; | |
temp >>= 8; | |
} | |
return toHexString(value, length); | |
} | |
/** | |
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. | |
*/ | |
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { | |
bytes memory buffer = new bytes(2 * length + 2); | |
buffer[0] = "0"; | |
buffer[1] = "x"; | |
for (uint256 i = 2 * length + 1; i > 1; --i) { | |
buffer[i] = _HEX_SYMBOLS[value & 0xf]; | |
value >>= 4; | |
} | |
require(value == 0, "Strings: hex length insufficient"); | |
return string(buffer); | |
} | |
} | |
// File: @openzeppelin/contracts/utils/Context.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Provides information about the current execution context, including the | |
* sender of the transaction and its data. While these are generally available | |
* via msg.sender and msg.data, they should not be accessed in such a direct | |
* manner, since when dealing with meta-transactions the account sending and | |
* paying for execution may not be the actual sender (as far as an application | |
* is concerned). | |
* | |
* This contract is only required for intermediate, library-like contracts. | |
*/ | |
abstract contract Context { | |
function _msgSender() internal view virtual returns (address) { | |
return msg.sender; | |
} | |
function _msgData() internal view virtual returns (bytes calldata) { | |
return msg.data; | |
} | |
} | |
// File: @openzeppelin/contracts/access/Ownable.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Contract module which provides a basic access control mechanism, where | |
* there is an account (an owner) that can be granted exclusive access to | |
* specific functions. | |
* | |
* By default, the owner account will be the one that deploys the contract. This | |
* can later be changed with {transferOwnership}. | |
* | |
* This module is used through inheritance. It will make available the modifier | |
* `onlyOwner`, which can be applied to your functions to restrict their use to | |
* the owner. | |
*/ | |
abstract contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() { | |
_setOwner(_msgSender()); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view virtual returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(owner() == _msgSender(), "Ownable: caller is not the owner"); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public virtual onlyOwner { | |
_setOwner(address(0)); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public virtual onlyOwner { | |
require(newOwner != address(0), "Ownable: new owner is the zero address"); | |
_setOwner(newOwner); | |
} | |
function _setOwner(address newOwner) private { | |
address oldOwner = _owner; | |
_owner = newOwner; | |
emit OwnershipTransferred(oldOwner, newOwner); | |
} | |
} | |
// File: @openzeppelin/contracts/utils/Address.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Collection of functions related to the address type | |
*/ | |
library Address { | |
/** | |
* @dev Returns true if `account` is a contract. | |
* | |
* [IMPORTANT] | |
* ==== | |
* It is unsafe to assume that an address for which this function returns | |
* false is an externally-owned account (EOA) and not a contract. | |
* | |
* Among others, `isContract` will return false for the following | |
* types of addresses: | |
* | |
* - an externally-owned account | |
* - a contract in construction | |
* - an address where a contract will be created | |
* - an address where a contract lived, but was destroyed | |
* ==== | |
*/ | |
function isContract(address account) internal view returns (bool) { | |
// This method relies on extcodesize, which returns 0 for contracts in | |
// construction, since the code is only stored at the end of the | |
// constructor execution. | |
uint256 size; | |
assembly { | |
size := extcodesize(account) | |
} | |
return size > 0; | |
} | |
/** | |
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to | |
* `recipient`, forwarding all available gas and reverting on errors. | |
* | |
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost | |
* of certain opcodes, possibly making contracts go over the 2300 gas limit | |
* imposed by `transfer`, making them unable to receive funds via | |
* `transfer`. {sendValue} removes this limitation. | |
* | |
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. | |
* | |
* IMPORTANT: because control is transferred to `recipient`, care must be | |
* taken to not create reentrancy vulnerabilities. Consider using | |
* {ReentrancyGuard} or the | |
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. | |
*/ | |
function sendValue(address payable recipient, uint256 amount) internal { | |
require(address(this).balance >= amount, "Address: insufficient balance"); | |
(bool success, ) = recipient.call{value: amount}(""); | |
require(success, "Address: unable to send value, recipient may have reverted"); | |
} | |
/** | |
* @dev Performs a Solidity function call using a low level `call`. A | |
* plain `call` is an unsafe replacement for a function call: use this | |
* function instead. | |
* | |
* If `target` reverts with a revert reason, it is bubbled up by this | |
* function (like regular Solidity function calls). | |
* | |
* Returns the raw returned data. To convert to the expected return value, | |
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. | |
* | |
* Requirements: | |
* | |
* - `target` must be a contract. | |
* - calling `target` with `data` must not revert. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCall(address target, bytes memory data) internal returns (bytes memory) { | |
return functionCall(target, data, "Address: low-level call failed"); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with | |
* `errorMessage` as a fallback revert reason when `target` reverts. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCall( | |
address target, | |
bytes memory data, | |
string memory errorMessage | |
) internal returns (bytes memory) { | |
return functionCallWithValue(target, data, 0, errorMessage); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], | |
* but also transferring `value` wei to `target`. | |
* | |
* Requirements: | |
* | |
* - the calling contract must have an ETH balance of at least `value`. | |
* - the called Solidity function must be `payable`. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCallWithValue( | |
address target, | |
bytes memory data, | |
uint256 value | |
) internal returns (bytes memory) { | |
return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but | |
* with `errorMessage` as a fallback revert reason when `target` reverts. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCallWithValue( | |
address target, | |
bytes memory data, | |
uint256 value, | |
string memory errorMessage | |
) internal returns (bytes memory) { | |
require(address(this).balance >= value, "Address: insufficient balance for call"); | |
require(isContract(target), "Address: call to non-contract"); | |
(bool success, bytes memory returndata) = target.call{value: value}(data); | |
return verifyCallResult(success, returndata, errorMessage); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], | |
* but performing a static call. | |
* | |
* _Available since v3.3._ | |
*/ | |
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { | |
return functionStaticCall(target, data, "Address: low-level static call failed"); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], | |
* but performing a static call. | |
* | |
* _Available since v3.3._ | |
*/ | |
function functionStaticCall( | |
address target, | |
bytes memory data, | |
string memory errorMessage | |
) internal view returns (bytes memory) { | |
require(isContract(target), "Address: static call to non-contract"); | |
(bool success, bytes memory returndata) = target.staticcall(data); | |
return verifyCallResult(success, returndata, errorMessage); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], | |
* but performing a delegate call. | |
* | |
* _Available since v3.4._ | |
*/ | |
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { | |
return functionDelegateCall(target, data, "Address: low-level delegate call failed"); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], | |
* but performing a delegate call. | |
* | |
* _Available since v3.4._ | |
*/ | |
function functionDelegateCall( | |
address target, | |
bytes memory data, | |
string memory errorMessage | |
) internal returns (bytes memory) { | |
require(isContract(target), "Address: delegate call to non-contract"); | |
(bool success, bytes memory returndata) = target.delegatecall(data); | |
return verifyCallResult(success, returndata, errorMessage); | |
} | |
/** | |
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the | |
* revert reason using the provided one. | |
* | |
* _Available since v4.3._ | |
*/ | |
function verifyCallResult( | |
bool success, | |
bytes memory returndata, | |
string memory errorMessage | |
) internal pure returns (bytes memory) { | |
if (success) { | |
return returndata; | |
} else { | |
// Look for revert reason and bubble it up if present | |
if (returndata.length > 0) { | |
// The easiest way to bubble the revert reason is using memory via assembly | |
assembly { | |
let returndata_size := mload(returndata) | |
revert(add(32, returndata), returndata_size) | |
} | |
} else { | |
revert(errorMessage); | |
} | |
} | |
} | |
} | |
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC721 token receiver interface | |
* @dev Interface for any contract that wants to support safeTransfers | |
* from ERC721 asset contracts. | |
*/ | |
interface IERC721Receiver { | |
/** | |
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} | |
* by `operator` from `from`, this function is called. | |
* | |
* It must return its Solidity selector to confirm the token transfer. | |
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. | |
* | |
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. | |
*/ | |
function onERC721Received( | |
address operator, | |
address from, | |
uint256 tokenId, | |
bytes calldata data | |
) external returns (bytes4); | |
} | |
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Interface of the ERC165 standard, as defined in the | |
* https://eips.ethereum.org/EIPS/eip-165[EIP]. | |
* | |
* Implementers can declare support of contract interfaces, which can then be | |
* queried by others ({ERC165Checker}). | |
* | |
* For an implementation, see {ERC165}. | |
*/ | |
interface IERC165 { | |
/** | |
* @dev Returns true if this contract implements the interface defined by | |
* `interfaceId`. See the corresponding | |
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] | |
* to learn more about how these ids are created. | |
* | |
* This function call must use less than 30 000 gas. | |
*/ | |
function supportsInterface(bytes4 interfaceId) external view returns (bool); | |
} | |
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Implementation of the {IERC165} interface. | |
* | |
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check | |
* for the additional interface id that will be supported. For example: | |
* | |
* ```solidity | |
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); | |
* } | |
* ``` | |
* | |
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. | |
*/ | |
abstract contract ERC165 is IERC165 { | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { | |
return interfaceId == type(IERC165).interfaceId; | |
} | |
} | |
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Required interface of an ERC721 compliant contract. | |
*/ | |
interface IERC721 is IERC165 { | |
/** | |
* @dev Emitted when `tokenId` token is transferred from `from` to `to`. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. | |
*/ | |
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); | |
/** | |
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. | |
*/ | |
event ApprovalForAll(address indexed owner, address indexed operator, bool approved); | |
/** | |
* @dev Returns the number of tokens in ``owner``'s account. | |
*/ | |
function balanceOf(address owner) external view returns (uint256 balance); | |
/** | |
* @dev Returns the owner of the `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function ownerOf(uint256 tokenId) external view returns (address owner); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients | |
* are aware of the ERC721 protocol to prevent tokens from being forever locked. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external; | |
/** | |
* @dev Transfers `tokenId` token from `from` to `to`. | |
* | |
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) external; | |
/** | |
* @dev Gives permission to `to` to transfer `tokenId` token to another account. | |
* The approval is cleared when the token is transferred. | |
* | |
* Only a single account can be approved at a time, so approving the zero address clears previous approvals. | |
* | |
* Requirements: | |
* | |
* - The caller must own the token or be an approved operator. | |
* - `tokenId` must exist. | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address to, uint256 tokenId) external; | |
/** | |
* @dev Returns the account approved for `tokenId` token. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function getApproved(uint256 tokenId) external view returns (address operator); | |
/** | |
* @dev Approve or remove `operator` as an operator for the caller. | |
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. | |
* | |
* Requirements: | |
* | |
* - The `operator` cannot be the caller. | |
* | |
* Emits an {ApprovalForAll} event. | |
*/ | |
function setApprovalForAll(address operator, bool _approved) external; | |
/** | |
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. | |
* | |
* See {setApprovalForAll} | |
*/ | |
function isApprovedForAll(address owner, address operator) external view returns (bool); | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes calldata data | |
) external; | |
} | |
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension | |
* @dev See https://eips.ethereum.org/EIPS/eip-721 | |
*/ | |
interface IERC721Enumerable is IERC721 { | |
/** | |
* @dev Returns the total amount of tokens stored by the contract. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns a token ID owned by `owner` at a given `index` of its token list. | |
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens. | |
*/ | |
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); | |
/** | |
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract. | |
* Use along with {totalSupply} to enumerate all tokens. | |
*/ | |
function tokenByIndex(uint256 index) external view returns (uint256); | |
} | |
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension | |
* @dev See https://eips.ethereum.org/EIPS/eip-721 | |
*/ | |
interface IERC721Metadata is IERC721 { | |
/** | |
* @dev Returns the token collection name. | |
*/ | |
function name() external view returns (string memory); | |
/** | |
* @dev Returns the token collection symbol. | |
*/ | |
function symbol() external view returns (string memory); | |
/** | |
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. | |
*/ | |
function tokenURI(uint256 tokenId) external view returns (string memory); | |
} | |
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including | |
* the Metadata extension, but not including the Enumerable extension, which is available separately as | |
* {ERC721Enumerable}. | |
*/ | |
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { | |
using Address for address; | |
using Strings for uint256; | |
// Token name | |
string private _name; | |
// Token symbol | |
string private _symbol; | |
// Mapping from token ID to owner address | |
mapping(uint256 => address) private _owners; | |
// Mapping owner address to token count | |
mapping(address => uint256) private _balances; | |
// Mapping from token ID to approved address | |
mapping(uint256 => address) private _tokenApprovals; | |
// Mapping from owner to operator approvals | |
mapping(address => mapping(address => bool)) private _operatorApprovals; | |
/** | |
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. | |
*/ | |
constructor(string memory name_, string memory symbol_) { | |
_name = name_; | |
_symbol = symbol_; | |
} | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { | |
return | |
interfaceId == type(IERC721).interfaceId || | |
interfaceId == type(IERC721Metadata).interfaceId || | |
super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev See {IERC721-balanceOf}. | |
*/ | |
function balanceOf(address owner) public view virtual override returns (uint256) { | |
require(owner != address(0), "ERC721: balance query for the zero address"); | |
return _balances[owner]; | |
} | |
/** | |
* @dev See {IERC721-ownerOf}. | |
*/ | |
function ownerOf(uint256 tokenId) public view virtual override returns (address) { | |
address owner = _owners[tokenId]; | |
require(owner != address(0), "ERC721: owner query for nonexistent token"); | |
return owner; | |
} | |
/** | |
* @dev See {IERC721Metadata-name}. | |
*/ | |
function name() public view virtual override returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev See {IERC721Metadata-symbol}. | |
*/ | |
function symbol() public view virtual override returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev See {IERC721Metadata-tokenURI}. | |
*/ | |
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { | |
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); | |
string memory baseURI = _baseURI(); | |
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; | |
} | |
/** | |
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each | |
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty | |
* by default, can be overriden in child contracts. | |
*/ | |
function _baseURI() internal view virtual returns (string memory) { | |
return ""; | |
} | |
/** | |
* @dev See {IERC721-approve}. | |
*/ | |
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); | |
} | |
/** | |
* @dev See {IERC721-getApproved}. | |
*/ | |
function getApproved(uint256 tokenId) public view virtual override returns (address) { | |
require(_exists(tokenId), "ERC721: approved query for nonexistent token"); | |
return _tokenApprovals[tokenId]; | |
} | |
/** | |
* @dev See {IERC721-setApprovalForAll}. | |
*/ | |
function setApprovalForAll(address operator, bool approved) public virtual override { | |
require(operator != _msgSender(), "ERC721: approve to caller"); | |
_operatorApprovals[_msgSender()][operator] = approved; | |
emit ApprovalForAll(_msgSender(), operator, approved); | |
} | |
/** | |
* @dev See {IERC721-isApprovedForAll}. | |
*/ | |
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { | |
return _operatorApprovals[owner][operator]; | |
} | |
/** | |
* @dev See {IERC721-transferFrom}. | |
*/ | |
function transferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public virtual override { | |
//solhint-disable-next-line max-line-length | |
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); | |
_transfer(from, to, tokenId); | |
} | |
/** | |
* @dev See {IERC721-safeTransferFrom}. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId | |
) public virtual override { | |
safeTransferFrom(from, to, tokenId, ""); | |
} | |
/** | |
* @dev See {IERC721-safeTransferFrom}. | |
*/ | |
function safeTransferFrom( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) public virtual override { | |
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); | |
_safeTransfer(from, to, tokenId, _data); | |
} | |
/** | |
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients | |
* are aware of the ERC721 protocol to prevent tokens from being forever locked. | |
* | |
* `_data` is additional data, it has no specified format and it is sent in call to `to`. | |
* | |
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. | |
* implement alternative mechanisms to perform token transfer, such as signature-based. | |
* | |
* Requirements: | |
* | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must exist and be owned by `from`. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _safeTransfer( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) internal virtual { | |
_transfer(from, to, tokenId); | |
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); | |
} | |
/** | |
* @dev Returns whether `tokenId` exists. | |
* | |
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. | |
* | |
* Tokens start existing when they are minted (`_mint`), | |
* and stop existing when they are burned (`_burn`). | |
*/ | |
function _exists(uint256 tokenId) internal view virtual returns (bool) { | |
return _owners[tokenId] != address(0); | |
} | |
/** | |
* @dev Returns whether `spender` is allowed to manage `tokenId`. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
*/ | |
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { | |
require(_exists(tokenId), "ERC721: operator query for nonexistent token"); | |
address owner = ERC721.ownerOf(tokenId); | |
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); | |
} | |
/** | |
* @dev Safely mints `tokenId` and transfers it to `to`. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must not exist. | |
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _safeMint(address to, uint256 tokenId) internal virtual { | |
_safeMint(to, tokenId, ""); | |
} | |
/** | |
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is | |
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients. | |
*/ | |
function _safeMint( | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) internal virtual { | |
_mint(to, tokenId); | |
require( | |
_checkOnERC721Received(address(0), to, tokenId, _data), | |
"ERC721: transfer to non ERC721Receiver implementer" | |
); | |
} | |
/** | |
* @dev Mints `tokenId` and transfers it to `to`. | |
* | |
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible | |
* | |
* Requirements: | |
* | |
* - `tokenId` must not exist. | |
* - `to` cannot be the zero address. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _mint(address to, uint256 tokenId) internal virtual { | |
require(to != address(0), "ERC721: mint to the zero address"); | |
require(!_exists(tokenId), "ERC721: token already minted"); | |
_beforeTokenTransfer(address(0), to, tokenId); | |
_balances[to] += 1; | |
_owners[tokenId] = to; | |
emit Transfer(address(0), to, tokenId); | |
} | |
/** | |
* @dev Destroys `tokenId`. | |
* The approval is cleared when the token is burned. | |
* | |
* Requirements: | |
* | |
* - `tokenId` must exist. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _burn(uint256 tokenId) internal virtual { | |
address owner = ERC721.ownerOf(tokenId); | |
_beforeTokenTransfer(owner, address(0), tokenId); | |
// Clear approvals | |
_approve(address(0), tokenId); | |
_balances[owner] -= 1; | |
delete _owners[tokenId]; | |
emit Transfer(owner, address(0), tokenId); | |
} | |
/** | |
* @dev Transfers `tokenId` from `from` to `to`. | |
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender. | |
* | |
* Requirements: | |
* | |
* - `to` cannot be the zero address. | |
* - `tokenId` token must be owned by `from`. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function _transfer( | |
address from, | |
address to, | |
uint256 tokenId | |
) internal virtual { | |
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); | |
require(to != address(0), "ERC721: transfer to the zero address"); | |
_beforeTokenTransfer(from, to, tokenId); | |
// Clear approvals from the previous owner | |
_approve(address(0), tokenId); | |
_balances[from] -= 1; | |
_balances[to] += 1; | |
_owners[tokenId] = to; | |
emit Transfer(from, to, tokenId); | |
} | |
/** | |
* @dev Approve `to` to operate on `tokenId` | |
* | |
* Emits a {Approval} event. | |
*/ | |
function _approve(address to, uint256 tokenId) internal virtual { | |
_tokenApprovals[tokenId] = to; | |
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); | |
} | |
/** | |
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. | |
* The call is not executed if the target address is not a contract. | |
* | |
* @param from address representing the previous owner of the given token ID | |
* @param to target address that will receive the tokens | |
* @param tokenId uint256 ID of the token to be transferred | |
* @param _data bytes optional data to send along with the call | |
* @return bool whether the call correctly returned the expected magic value | |
*/ | |
function _checkOnERC721Received( | |
address from, | |
address to, | |
uint256 tokenId, | |
bytes memory _data | |
) private returns (bool) { | |
if (to.isContract()) { | |
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { | |
return retval == IERC721Receiver.onERC721Received.selector; | |
} catch (bytes memory reason) { | |
if (reason.length == 0) { | |
revert("ERC721: transfer to non ERC721Receiver implementer"); | |
} else { | |
assembly { | |
revert(add(32, reason), mload(reason)) | |
} | |
} | |
} | |
} else { | |
return true; | |
} | |
} | |
/** | |
* @dev Hook that is called before any token transfer. This includes minting | |
* and burning. | |
* | |
* Calling conditions: | |
* | |
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be | |
* transferred to `to`. | |
* - When `from` is zero, `tokenId` will be minted for `to`. | |
* - When `to` is zero, ``from``'s `tokenId` will be burned. | |
* - `from` and `to` are never both zero. | |
* | |
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. | |
*/ | |
function _beforeTokenTransfer( | |
address from, | |
address to, | |
uint256 tokenId | |
) internal virtual {} | |
} | |
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol | |
pragma solidity ^0.8.0; | |
/** | |
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds | |
* enumerability of all the token ids in the contract as well as all token ids owned by each | |
* account. | |
*/ | |
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { | |
// Mapping from owner to list of owned token IDs | |
mapping(address => mapping(uint256 => uint256)) private _ownedTokens; | |
// Mapping from token ID to index of the owner tokens list | |
mapping(uint256 => uint256) private _ownedTokensIndex; | |
// Array with all token ids, used for enumeration | |
uint256[] private _allTokens; | |
// Mapping from token id to position in the allTokens array | |
mapping(uint256 => uint256) private _allTokensIndex; | |
/** | |
* @dev See {IERC165-supportsInterface}. | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { | |
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); | |
} | |
/** | |
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. | |
*/ | |
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { | |
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); | |
return _ownedTokens[owner][index]; | |
} | |
/** | |
* @dev See {IERC721Enumerable-totalSupply}. | |
*/ | |
function totalSupply() public view virtual override returns (uint256) { | |
return _allTokens.length; | |
} | |
/** | |
* @dev See {IERC721Enumerable-tokenByIndex}. | |
*/ | |
function tokenByIndex(uint256 index) public view virtual override returns (uint256) { | |
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); | |
return _allTokens[index]; | |
} | |
/** | |
* @dev Hook that is called before any token transfer. This includes minting | |
* and burning. | |
* | |
* Calling conditions: | |
* | |
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be | |
* transferred to `to`. | |
* - When `from` is zero, `tokenId` will be minted for `to`. | |
* - When `to` is zero, ``from``'s `tokenId` will be burned. | |
* - `from` cannot be the zero address. | |
* - `to` cannot be the zero address. | |
* | |
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. | |
*/ | |
function _beforeTokenTransfer( | |
address from, | |
address to, | |
uint256 tokenId | |
) internal virtual override { | |
super._beforeTokenTransfer(from, to, tokenId); | |
if (from == address(0)) { | |
_addTokenToAllTokensEnumeration(tokenId); | |
} else if (from != to) { | |
_removeTokenFromOwnerEnumeration(from, tokenId); | |
} | |
if (to == address(0)) { | |
_removeTokenFromAllTokensEnumeration(tokenId); | |
} else if (to != from) { | |
_addTokenToOwnerEnumeration(to, tokenId); | |
} | |
} | |
/** | |
* @dev Private function to add a token to this extension's ownership-tracking data structures. | |
* @param to address representing the new owner of the given token ID | |
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address | |
*/ | |
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { | |
uint256 length = ERC721.balanceOf(to); | |
_ownedTokens[to][length] = tokenId; | |
_ownedTokensIndex[tokenId] = length; | |
} | |
/** | |
* @dev Private function to add a token to this extension's token tracking data structures. | |
* @param tokenId uint256 ID of the token to be added to the tokens list | |
*/ | |
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { | |
_allTokensIndex[tokenId] = _allTokens.length; | |
_allTokens.push(tokenId); | |
} | |
/** | |
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that | |
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for | |
* gas optimizations e.g. when performing a transfer operation (avoiding double writes). | |
* This has O(1) time complexity, but alters the order of the _ownedTokens array. | |
* @param from address representing the previous owner of the given token ID | |
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address | |
*/ | |
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { | |
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and | |
// then delete the last slot (swap and pop). | |
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; | |
uint256 tokenIndex = _ownedTokensIndex[tokenId]; | |
// When the token to delete is the last token, the swap operation is unnecessary | |
if (tokenIndex != lastTokenIndex) { | |
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; | |
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token | |
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index | |
} | |
// This also deletes the contents at the last position of the array | |
delete _ownedTokensIndex[tokenId]; | |
delete _ownedTokens[from][lastTokenIndex]; | |
} | |
/** | |
* @dev Private function to remove a token from this extension's token tracking data structures. | |
* This has O(1) time complexity, but alters the order of the _allTokens array. | |
* @param tokenId uint256 ID of the token to be removed from the tokens list | |
*/ | |
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { | |
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and | |
// then delete the last slot (swap and pop). | |
uint256 lastTokenIndex = _allTokens.length - 1; | |
uint256 tokenIndex = _allTokensIndex[tokenId]; | |
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so | |
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding | |
// an 'if' statement (like in _removeTokenFromOwnerEnumeration) | |
uint256 lastTokenId = _allTokens[lastTokenIndex]; | |
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token | |
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index | |
// This also deletes the contents at the last position of the array | |
delete _allTokensIndex[tokenId]; | |
_allTokens.pop(); | |
} | |
} | |
// File: Reflective.sol | |
pragma solidity ^0.8.4; | |
contract Reflective is ERC721Enumerable, Ownable { | |
using Address for address; | |
// Starting and stopping sale and presale | |
bool public saleActive = false; | |
bool public presaleActive = false; | |
uint256 counter = 0; | |
// Reserved for the team, customs, giveaways, collabs and so on. | |
uint256 public reserved = 60; | |
// Price of each token | |
uint256 public price = 1 wei; | |
// Maximum limit of tokens that can ever exist | |
uint256 constant MAX_SUPPLY = 10000; | |
uint256 public remainingTokens = MAX_SUPPLY; | |
// The base link that leads to the image / video of the token | |
string public baseTokenURI; | |
//to show moc | |
string public blankURI; | |
// List of addresses that have a number of reserved tokens for presale | |
mapping (address => uint256) public presaleReserved; | |
constructor (string memory newBaseURI) ERC721 ("Reflective Collective", "RC") { | |
remainingTokens = remainingTokens - reserved; | |
setBaseURI(newBaseURI); | |
} | |
// Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead | |
function _baseURI() internal view virtual override returns (string memory) { | |
return baseTokenURI; | |
} | |
// See which address owns which tokens | |
function tokensOfOwner(address addr) public view returns(uint256[] memory) { | |
uint256 tokenCount = balanceOf(addr); | |
uint256[] memory tokensId = new uint256[](tokenCount); | |
for(uint256 i; i < tokenCount; i++){ | |
tokensId[i] = tokenOfOwnerByIndex(addr, i); | |
} | |
return tokensId; | |
} | |
//Mint | |
function mint() public payable { | |
require(presaleActive ==true || saleActive ==true,"sale is not activated yet"); | |
if(presaleActive==true && saleActive == false){ | |
mintPresale(); | |
} | |
if(saleActive==true && presaleActive ==false){ | |
mintToken(); | |
} | |
} | |
// Exclusive presale minting | |
function mintPresale() internal { | |
uint256 supply = totalSupply(); | |
uint256 reservedAmt = presaleReserved[msg.sender]; | |
require( presaleActive, "Presale isn't active" ); | |
require( reservedAmt > 0, "No tokens reserved for your address" ); | |
// require( reservedAmt <= 0, "Can't mint more than reserved" ); | |
require( supply <= MAX_SUPPLY, "Can't mint more than max supply" ); | |
require( msg.value == price, "Wrong amount of ETH sent" ); | |
presaleReserved[msg.sender] = reservedAmt - 1; | |
_safeMint( msg.sender, supply + 1 ); | |
remainingTokens--; | |
counter++; | |
} | |
// Standard mint function1 | |
function mintToken() internal { | |
require( msg.value == price, "Wrong amount of ETH sent" ); | |
payable(owner()).transfer(msg.value); | |
uint256 supply = totalSupply(); | |
require( saleActive, "Sale isn't active" ); | |
require( supply + 1 <= MAX_SUPPLY, "Can't mint more than max supply" ); | |
_safeMint( msg.sender, supply + 1 ); | |
remainingTokens--; | |
counter++; | |
} | |
//withdraw ethers() from contract onlyy Admin | |
function withdrawfunds() public onlyOwner payable{ | |
require(msg.sender==owner(),"only Owner can call this function"); | |
payable(owner()).transfer(address(this).balance); | |
} | |
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways | |
function mintReserved(uint256 _amount) public onlyOwner { | |
// Limited to a publicly set amount | |
require( _amount <= reserved, "Can't reserve more than set amount" ); | |
reserved -= _amount; | |
uint256 supply = totalSupply(); | |
for(uint256 i; i < _amount; i++){ | |
_safeMint( msg.sender, supply + i ); | |
remainingTokens--; | |
} | |
} | |
// Edit reserved presale spots | |
function editPresaleReserved(address[] memory _a, uint256 _amount) public onlyOwner { | |
for(uint256 i; i < _a.length; i++){ | |
presaleReserved[_a[i]] = _amount; | |
} | |
} | |
// Start and stop presale | |
function setPresaleActive(bool val) public onlyOwner { | |
presaleActive = val; | |
if(val == true){ | |
saleActive = false; | |
} | |
} | |
// Start and stop sale | |
function setSaleActive(bool val) public onlyOwner { | |
saleActive = val; | |
if(val == true){ | |
presaleActive = false; | |
} | |
} | |
// Set new baseURI | |
function setBaseURI(string memory baseURI) public onlyOwner { | |
baseTokenURI = baseURI; | |
} | |
// Set a different price in case ETH changes drastically | |
function setPrice(uint256 newPrice) public onlyOwner { | |
price = newPrice; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity >=0.4.0; | |
/** | |
* @dev Wrappers over Solidity's arithmetic operations with added overflow | |
* checks. | |
* | |
* Arithmetic operations in Solidity wrap on overflow. This can easily result | |
* in bugs, because programmers usually assume that an overflow raises an | |
* error, which is the standard behavior in high level programming languages. | |
* `SafeMath` restores this intuition by reverting the transaction when an | |
* operation overflows. | |
* | |
* Using this library instead of the unchecked operations eliminates an entire | |
* class of bugs, so it's recommended to use it always. | |
*/ | |
library SafeMath { | |
/** | |
* @dev Returns the addition of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `+` operator. | |
* | |
* Requirements: | |
* | |
* - Addition cannot overflow. | |
*/ | |
function add(uint256 a, uint256 b) internal pure returns (uint256) { | |
uint256 c = a + b; | |
require(c >= a, 'SafeMath: addition overflow'); | |
return c; | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub(uint256 a, uint256 b) internal pure returns (uint256) { | |
return sub(a, b, 'SafeMath: subtraction overflow'); | |
} | |
/** | |
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on | |
* overflow (when the result is negative). | |
* | |
* Counterpart to Solidity's `-` operator. | |
* | |
* Requirements: | |
* | |
* - Subtraction cannot overflow. | |
*/ | |
function sub( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b <= a, errorMessage); | |
uint256 c = a - b; | |
return c; | |
} | |
/** | |
* @dev Returns the multiplication of two unsigned integers, reverting on | |
* overflow. | |
* | |
* Counterpart to Solidity's `*` operator. | |
* | |
* Requirements: | |
* | |
* - Multiplication cannot overflow. | |
*/ | |
function mul(uint256 a, uint256 b) internal pure returns (uint256) { | |
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the | |
// benefit is lost if 'b' is also tested. | |
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 | |
if (a == 0) { | |
return 0; | |
} | |
uint256 c = a * b; | |
require(c / a == b, 'SafeMath: multiplication overflow'); | |
return c; | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div(uint256 a, uint256 b) internal pure returns (uint256) { | |
return div(a, b, 'SafeMath: division by zero'); | |
} | |
/** | |
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on | |
* division by zero. The result is rounded towards zero. | |
* | |
* Counterpart to Solidity's `/` operator. Note: this function uses a | |
* `revert` opcode (which leaves remaining gas untouched) while Solidity | |
* uses an invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function div( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b > 0, errorMessage); | |
uint256 c = a / b; | |
// assert(a == b * c + a % b); // There is no case in which this doesn't hold | |
return c; | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod(uint256 a, uint256 b) internal pure returns (uint256) { | |
return mod(a, b, 'SafeMath: modulo by zero'); | |
} | |
/** | |
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), | |
* Reverts with custom message when dividing by zero. | |
* | |
* Counterpart to Solidity's `%` operator. This function uses a `revert` | |
* opcode (which leaves remaining gas untouched) while Solidity uses an | |
* invalid opcode to revert (consuming all remaining gas). | |
* | |
* Requirements: | |
* | |
* - The divisor cannot be zero. | |
*/ | |
function mod( | |
uint256 a, | |
uint256 b, | |
string memory errorMessage | |
) internal pure returns (uint256) { | |
require(b != 0, errorMessage); | |
return a % b; | |
} | |
function min(uint256 x, uint256 y) internal pure returns (uint256 z) { | |
z = x < y ? x : y; | |
} | |
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) | |
function sqrt(uint256 y) internal pure returns (uint256 z) { | |
if (y > 3) { | |
z = y; | |
uint256 x = y / 2 + 1; | |
while (x < z) { | |
z = x; | |
x = (y / x + x) / 2; | |
} | |
} else if (y != 0) { | |
z = 1; | |
} | |
} | |
} | |
pragma solidity >=0.4.0; | |
interface IBEP20 { | |
/** | |
* @dev Returns the amount of tokens in existence. | |
*/ | |
function totalSupply() external view returns (uint256); | |
/** | |
* @dev Returns the token decimals. | |
*/ | |
function decimals() external view returns (uint8); | |
/** | |
* @dev Returns the token symbol. | |
*/ | |
function symbol() external view returns (string memory); | |
/** | |
* @dev Returns the token name. | |
*/ | |
function name() external view returns (string memory); | |
/** | |
* @dev Returns the bep token owner. | |
*/ | |
function getOwner() external view returns (address); | |
/** | |
* @dev Returns the amount of tokens owned by `account`. | |
*/ | |
function balanceOf(address account) external view returns (uint256); | |
/** | |
* @dev Moves `amount` tokens from the caller's account to `recipient`. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transfer(address recipient, uint256 amount) external returns (bool); | |
/** | |
* @dev Returns the remaining number of tokens that `spender` will be | |
* allowed to spend on behalf of `owner` through {transferFrom}. This is | |
* zero by default. | |
* | |
* This value changes when {approve} or {transferFrom} are called. | |
*/ | |
function allowance(address _owner, address spender) external view returns (uint256); | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* IMPORTANT: Beware that changing an allowance with this method brings the risk | |
* that someone may use both the old and the new allowance by unfortunate | |
* transaction ordering. One possible solution to mitigate this race | |
* condition is to first reduce the spender's allowance to 0 and set the | |
* desired value afterwards: | |
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 | |
* | |
* Emits an {Approval} event. | |
*/ | |
function approve(address spender, uint256 amount) external returns (bool); | |
/** | |
* @dev Moves `amount` tokens from `sender` to `recipient` using the | |
* allowance mechanism. `amount` is then deducted from the caller's | |
* allowance. | |
* | |
* Returns a boolean value indicating whether the operation succeeded. | |
* | |
* Emits a {Transfer} event. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) external returns (bool); | |
/** | |
* @dev Emitted when `value` tokens are moved from one account (`from`) to | |
* another (`to`). | |
* | |
* Note that `value` may be zero. | |
*/ | |
event Transfer(address indexed from, address indexed to, uint256 value); | |
/** | |
* @dev Emitted when the allowance of a `spender` for an `owner` is set by | |
* a call to {approve}. `value` is the new allowance. | |
*/ | |
event Approval(address indexed owner, address indexed spender, uint256 value); | |
} | |
pragma solidity ^0.6.2; | |
/** | |
* @dev Collection of functions related to the address type | |
*/ | |
library Address { | |
/** | |
* @dev Returns true if `account` is a contract. | |
* | |
* [IMPORTANT] | |
* ==== | |
* It is unsafe to assume that an address for which this function returns | |
* false is an externally-owned account (EOA) and not a contract. | |
* | |
* Among others, `isContract` will return false for the following | |
* types of addresses: | |
* | |
* - an externally-owned account | |
* - a contract in construction | |
* - an address where a contract will be created | |
* - an address where a contract lived, but was destroyed | |
* ==== | |
*/ | |
function isContract(address account) internal view returns (bool) { | |
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts | |
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned | |
// for accounts without code, i.e. `keccak256('')` | |
bytes32 codehash; | |
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; | |
// solhint-disable-next-line no-inline-assembly | |
assembly { | |
codehash := extcodehash(account) | |
} | |
return (codehash != accountHash && codehash != 0x0); | |
} | |
/** | |
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to | |
* `recipient`, forwarding all available gas and reverting on errors. | |
* | |
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost | |
* of certain opcodes, possibly making contracts go over the 2300 gas limit | |
* imposed by `transfer`, making them unable to receive funds via | |
* `transfer`. {sendValue} removes this limitation. | |
* | |
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. | |
* | |
* IMPORTANT: because control is transferred to `recipient`, care must be | |
* taken to not create reentrancy vulnerabilities. Consider using | |
* {ReentrancyGuard} or the | |
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. | |
*/ | |
function sendValue(address payable recipient, uint256 amount) internal { | |
require(address(this).balance >= amount, 'Address: insufficient balance'); | |
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value | |
(bool success, ) = recipient.call{value: amount}(''); | |
require(success, 'Address: unable to send value, recipient may have reverted'); | |
} | |
/** | |
* @dev Performs a Solidity function call using a low level `call`. A | |
* plain`call` is an unsafe replacement for a function call: use this | |
* function instead. | |
* | |
* If `target` reverts with a revert reason, it is bubbled up by this | |
* function (like regular Solidity function calls). | |
* | |
* Returns the raw returned data. To convert to the expected return value, | |
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. | |
* | |
* Requirements: | |
* | |
* - `target` must be a contract. | |
* - calling `target` with `data` must not revert. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCall(address target, bytes memory data) internal returns (bytes memory) { | |
return functionCall(target, data, 'Address: low-level call failed'); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with | |
* `errorMessage` as a fallback revert reason when `target` reverts. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCall( | |
address target, | |
bytes memory data, | |
string memory errorMessage | |
) internal returns (bytes memory) { | |
return _functionCallWithValue(target, data, 0, errorMessage); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], | |
* but also transferring `value` wei to `target`. | |
* | |
* Requirements: | |
* | |
* - the calling contract must have an ETH balance of at least `value`. | |
* - the called Solidity function must be `payable`. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCallWithValue( | |
address target, | |
bytes memory data, | |
uint256 value | |
) internal returns (bytes memory) { | |
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); | |
} | |
/** | |
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but | |
* with `errorMessage` as a fallback revert reason when `target` reverts. | |
* | |
* _Available since v3.1._ | |
*/ | |
function functionCallWithValue( | |
address target, | |
bytes memory data, | |
uint256 value, | |
string memory errorMessage | |
) internal returns (bytes memory) { | |
require(address(this).balance >= value, 'Address: insufficient balance for call'); | |
return _functionCallWithValue(target, data, value, errorMessage); | |
} | |
function _functionCallWithValue( | |
address target, | |
bytes memory data, | |
uint256 weiValue, | |
string memory errorMessage | |
) private returns (bytes memory) { | |
require(isContract(target), 'Address: call to non-contract'); | |
// solhint-disable-next-line avoid-low-level-calls | |
(bool success, bytes memory returndata) = target.call{value: weiValue}(data); | |
if (success) { | |
return returndata; | |
} else { | |
// Look for revert reason and bubble it up if present | |
if (returndata.length > 0) { | |
// The easiest way to bubble the revert reason is using memory via assembly | |
// solhint-disable-next-line no-inline-assembly | |
assembly { | |
let returndata_size := mload(returndata) | |
revert(add(32, returndata), returndata_size) | |
} | |
} else { | |
revert(errorMessage); | |
} | |
} | |
} | |
} | |
pragma solidity ^0.6.0; | |
/** | |
* @title SafeBEP20 | |
* @dev Wrappers around BEP20 operations that throw on failure (when the token | |
* contract returns false). Tokens that return no value (and instead revert or | |
* throw on failure) are also supported, non-reverting calls are assumed to be | |
* successful. | |
* To use this library you can add a `using SafeBEP20 for IBEP20;` statement to your contract, | |
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc. | |
*/ | |
library SafeBEP20 { | |
using SafeMath for uint256; | |
using Address for address; | |
function safeTransfer( | |
IBEP20 token, | |
address to, | |
uint256 value | |
) internal { | |
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); | |
} | |
function safeTransferFrom( | |
IBEP20 token, | |
address from, | |
address to, | |
uint256 value | |
) internal { | |
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); | |
} | |
/** | |
* @dev Deprecated. This function has issues similar to the ones found in | |
* {IBEP20-approve}, and its usage is discouraged. | |
* | |
* Whenever possible, use {safeIncreaseAllowance} and | |
* {safeDecreaseAllowance} instead. | |
*/ | |
function safeApprove( | |
IBEP20 token, | |
address spender, | |
uint256 value | |
) internal { | |
// safeApprove should only be called when setting an initial allowance, | |
// or when resetting it to zero. To increase and decrease it, use | |
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance' | |
// solhint-disable-next-line max-line-length | |
require( | |
(value == 0) || (token.allowance(address(this), spender) == 0), | |
'SafeBEP20: approve from non-zero to non-zero allowance' | |
); | |
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); | |
} | |
function safeIncreaseAllowance( | |
IBEP20 token, | |
address spender, | |
uint256 value | |
) internal { | |
uint256 newAllowance = token.allowance(address(this), spender).add(value); | |
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); | |
} | |
function safeDecreaseAllowance( | |
IBEP20 token, | |
address spender, | |
uint256 value | |
) internal { | |
uint256 newAllowance = token.allowance(address(this), spender).sub( | |
value, | |
'SafeBEP20: decreased allowance below zero' | |
); | |
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); | |
} | |
/** | |
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement | |
* on the return value: the return value is optional (but if data is returned, it must not be false). | |
* @param token The token targeted by the call. | |
* @param data The call data (encoded using abi.encode or one of its variants). | |
*/ | |
function _callOptionalReturn(IBEP20 token, bytes memory data) private { | |
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since | |
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that | |
// the target address contains contract code and also asserts for success in the low-level call. | |
bytes memory returndata = address(token).functionCall(data, 'SafeBEP20: low-level call failed'); | |
if (returndata.length > 0) { | |
// Return data is optional | |
// solhint-disable-next-line max-line-length | |
require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); | |
} | |
} | |
} | |
pragma solidity >=0.4.0; | |
/* | |
* @dev Provides information about the current execution context, including the | |
* sender of the transaction and its data. While these are generally available | |
* via msg.sender and msg.data, they should not be accessed in such a direct | |
* manner, since when dealing with GSN meta-transactions the account sending and | |
* paying for execution may not be the actual sender (as far as an application | |
* is concerned). | |
* | |
* This contract is only required for intermediate, library-like contracts. | |
*/ | |
contract Context { | |
// Empty internal constructor, to prevent people from mistakenly deploying | |
// an instance of this contract, which should be used via inheritance. | |
constructor() internal {} | |
function _msgSender() internal view returns (address payable) { | |
return msg.sender; | |
} | |
function _msgData() internal view returns (bytes memory) { | |
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 | |
return msg.data; | |
} | |
} | |
pragma solidity >=0.4.0; | |
/** | |
* @dev Contract module which provides a basic access control mechanism, where | |
* there is an account (an owner) that can be granted exclusive access to | |
* specific functions. | |
* | |
* By default, the owner account will be the one that deploys the contract. This | |
* can later be changed with {transferOwnership}. | |
* | |
* This module is used through inheritance. It will make available the modifier | |
* `onlyOwner`, which can be applied to your functions to restrict their use to | |
* the owner. | |
*/ | |
contract Ownable is Context { | |
address private _owner; | |
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); | |
/** | |
* @dev Initializes the contract setting the deployer as the initial owner. | |
*/ | |
constructor() internal { | |
address msgSender = _msgSender(); | |
_owner = msgSender; | |
emit OwnershipTransferred(address(0), msgSender); | |
} | |
/** | |
* @dev Returns the address of the current owner. | |
*/ | |
function owner() public view returns (address) { | |
return _owner; | |
} | |
/** | |
* @dev Throws if called by any account other than the owner. | |
*/ | |
modifier onlyOwner() { | |
require(_owner == _msgSender(), 'Ownable: caller is not the owner'); | |
_; | |
} | |
/** | |
* @dev Leaves the contract without owner. It will not be possible to call | |
* `onlyOwner` functions anymore. Can only be called by the current owner. | |
* | |
* NOTE: Renouncing ownership will leave the contract without an owner, | |
* thereby removing any functionality that is only available to the owner. | |
*/ | |
function renounceOwnership() public onlyOwner { | |
emit OwnershipTransferred(_owner, address(0)); | |
_owner = address(0); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
* Can only be called by the current owner. | |
*/ | |
function transferOwnership(address newOwner) public onlyOwner { | |
_transferOwnership(newOwner); | |
} | |
/** | |
* @dev Transfers ownership of the contract to a new account (`newOwner`). | |
*/ | |
function _transferOwnership(address newOwner) internal { | |
require(newOwner != address(0), 'Ownable: new owner is the zero address'); | |
emit OwnershipTransferred(_owner, newOwner); | |
_owner = newOwner; | |
} | |
} | |
pragma solidity >=0.4.0; | |
/** | |
* @dev Implementation of the {IBEP20} interface. | |
* | |
* This implementation is agnostic to the way tokens are created. This means | |
* that a supply mechanism has to be added in a derived contract using {_mint}. | |
* For a generic mechanism see {BEP20PresetMinterPauser}. | |
* | |
* TIP: For a detailed writeup see our guide | |
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-supply-mechanisms/226[How | |
* to implement supply mechanisms]. | |
* | |
* We have followed general OpenZeppelin guidelines: functions revert instead | |
* of returning `false` on failure. This behavior is nonetheless conventional | |
* and does not conflict with the expectations of BEP20 applications. | |
* | |
* Additionally, an {Approval} event is emitted on calls to {transferFrom}. | |
* This allows applications to reconstruct the allowance for all accounts just | |
* by listening to said events. Other implementations of the EIP may not emit | |
* these events, as it isn't required by the specification. | |
* | |
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance} | |
* functions have been added to mitigate the well-known issues around setting | |
* allowances. See {IBEP20-approve}. | |
*/ | |
contract BEP20 is Context, IBEP20, Ownable { | |
using SafeMath for uint256; | |
using Address for address; | |
mapping(address => uint256) private _balances; | |
mapping(address => mapping(address => uint256)) private _allowances; | |
uint256 private _totalSupply; | |
string private _name; | |
string private _symbol; | |
uint8 private _decimals; | |
/** | |
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with | |
* a default value of 18. | |
* | |
* To select a different value for {decimals}, use {_setupDecimals}. | |
* | |
* All three of these values are immutable: they can only be set once during | |
* construction. | |
*/ | |
constructor(string memory name, string memory symbol) public { | |
_name = name; | |
_symbol = symbol; | |
_decimals = 18; | |
} | |
/** | |
* @dev Returns the bep token owner. | |
*/ | |
function getOwner() external override view returns (address) { | |
return owner(); | |
} | |
/** | |
* @dev Returns the token name. | |
*/ | |
function name() public override view returns (string memory) { | |
return _name; | |
} | |
/** | |
* @dev Returns the token decimals. | |
*/ | |
function decimals() public override view returns (uint8) { | |
return _decimals; | |
} | |
/** | |
* @dev Returns the token symbol. | |
*/ | |
function symbol() public override view returns (string memory) { | |
return _symbol; | |
} | |
/** | |
* @dev See {BEP20-totalSupply}. | |
*/ | |
function totalSupply() public override view returns (uint256) { | |
return _totalSupply; | |
} | |
/** | |
* @dev See {BEP20-balanceOf}. | |
*/ | |
function balanceOf(address account) public override view returns (uint256) { | |
return _balances[account]; | |
} | |
/** | |
* @dev See {BEP20-transfer}. | |
* | |
* Requirements: | |
* | |
* - `recipient` cannot be the zero address. | |
* - the caller must have a balance of at least `amount`. | |
*/ | |
function transfer(address recipient, uint256 amount) public override returns (bool) { | |
_transfer(_msgSender(), recipient, amount); | |
return true; | |
} | |
/** | |
* @dev See {BEP20-allowance}. | |
*/ | |
function allowance(address owner, address spender) public override view returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
/** | |
* @dev See {BEP20-approve}. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function approve(address spender, uint256 amount) public override returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
/** | |
* @dev See {BEP20-transferFrom}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. This is not | |
* required by the EIP. See the note at the beginning of {BEP20}; | |
* | |
* Requirements: | |
* - `sender` and `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
* - the caller must have allowance for `sender`'s tokens of at least | |
* `amount`. | |
*/ | |
function transferFrom( | |
address sender, | |
address recipient, | |
uint256 amount | |
) public override returns (bool) { | |
_transfer(sender, recipient, amount); | |
_approve( | |
sender, | |
_msgSender(), | |
_allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') | |
); | |
return true; | |
} | |
/** | |
* @dev Atomically increases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {BEP20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
*/ | |
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); | |
return true; | |
} | |
/** | |
* @dev Atomically decreases the allowance granted to `spender` by the caller. | |
* | |
* This is an alternative to {approve} that can be used as a mitigation for | |
* problems described in {BEP20-approve}. | |
* | |
* Emits an {Approval} event indicating the updated allowance. | |
* | |
* Requirements: | |
* | |
* - `spender` cannot be the zero address. | |
* - `spender` must have allowance for the caller of at least | |
* `subtractedValue`. | |
*/ | |
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { | |
_approve( | |
_msgSender(), | |
spender, | |
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') | |
); | |
return true; | |
} | |
/** | |
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing | |
* the total supply. | |
* | |
* Requirements | |
* | |
* - `msg.sender` must be the token owner | |
*/ | |
function mint(uint256 amount) public onlyOwner returns (bool) { | |
_mint(_msgSender(), amount); | |
return true; | |
} | |
/** | |
* @dev Moves tokens `amount` from `sender` to `recipient`. | |
* | |
* This is internal function is equivalent to {transfer}, and can be used to | |
* e.g. implement automatic token fees, slashing mechanisms, etc. | |
* | |
* Emits a {Transfer} event. | |
* | |
* Requirements: | |
* | |
* - `sender` cannot be the zero address. | |
* - `recipient` cannot be the zero address. | |
* - `sender` must have a balance of at least `amount`. | |
*/ | |
function _transfer( | |
address sender, | |
address recipient, | |
uint256 amount | |
) internal { | |
require(sender != address(0), 'BEP20: transfer from the zero address'); | |
require(recipient != address(0), 'BEP20: transfer to the zero address'); | |
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); | |
_balances[recipient] = _balances[recipient].add(amount); | |
emit Transfer(sender, recipient, amount); | |
} | |
/** @dev Creates `amount` tokens and assigns them to `account`, increasing | |
* the total supply. | |
* | |
* Emits a {Transfer} event with `from` set to the zero address. | |
* | |
* Requirements | |
* | |
* - `to` cannot be the zero address. | |
*/ | |
function _mint(address account, uint256 amount) internal { | |
require(account != address(0), 'BEP20: mint to the zero address'); | |
_totalSupply = _totalSupply.add(amount); | |
_balances[account] = _balances[account].add(amount); | |
emit Transfer(address(0), account, amount); | |
} | |
/** | |
* @dev Destroys `amount` tokens from `account`, reducing the | |
* total supply. | |
* | |
* Emits a {Transfer} event with `to` set to the zero address. | |
* | |
* Requirements | |
* | |
* - `account` cannot be the zero address. | |
* - `account` must have at least `amount` tokens. | |
*/ | |
function _burn(address account, uint256 amount) internal { | |
require(account != address(0), 'BEP20: burn from the zero address'); | |
_balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); | |
_totalSupply = _totalSupply.sub(amount); | |
emit Transfer(account, address(0), amount); | |
} | |
/** | |
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. | |
* | |
* This is internal function is equivalent to `approve`, and can be used to | |
* e.g. set automatic allowances for certain subsystems, etc. | |
* | |
* Emits an {Approval} event. | |
* | |
* Requirements: | |
* | |
* - `owner` cannot be the zero address. | |
* - `spender` cannot be the zero address. | |
*/ | |
function _approve( | |
address owner, | |
address spender, | |
uint256 amount | |
) internal { | |
require(owner != address(0), 'BEP20: approve from the zero address'); | |
require(spender != address(0), 'BEP20: approve to the zero address'); | |
_allowances[owner][spender] = amount; | |
emit Approval(owner, spender, amount); | |
} | |
/** | |
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted | |
* from the caller's allowance. | |
* | |
* See {_burn} and {_approve}. | |
*/ | |
function _burnFrom(address account, uint256 amount) internal { | |
_burn(account, amount); | |
_approve( | |
account, | |
_msgSender(), | |
_allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') | |
); | |
} | |
} | |
pragma solidity 0.6.12; | |
// SeaToken with Governance. | |
contract SeaToken is BEP20('SeaWorld', 'SEA') { | |
// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). | |
function mint(address _to, uint256 _amount) public onlyOwner { | |
_mint(_to, _amount); | |
_moveDelegates(address(0), _delegates[_to], _amount); | |
} | |
// Copied and modified from YAM code: | |
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol | |
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol | |
// Which is copied and modified from COMPOUND: | |
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol | |
/// @notice A record of each accounts delegate | |
mapping (address => address) internal _delegates; | |
/// @notice A checkpoint for marking number of votes from a given block | |
struct Checkpoint { | |
uint32 fromBlock; | |
uint256 votes; | |
} | |
/// @notice A record of votes checkpoints for each account, by index | |
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; | |
/// @notice The number of checkpoints for each account | |
mapping (address => uint32) public numCheckpoints; | |
/// @notice The EIP-712 typehash for the contract's domain | |
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); | |
/// @notice The EIP-712 typehash for the delegation struct used by the contract | |
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); | |
/// @notice A record of states for signing / validating signatures | |
mapping (address => uint) public nonces; | |
/// @notice An event thats emitted when an account changes its delegate | |
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); | |
/// @notice An event thats emitted when a delegate account's vote balance changes | |
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); | |
/** | |
* @notice Delegate votes from `msg.sender` to `delegatee` | |
* @param delegator The address to get delegatee for | |
*/ | |
function delegates(address delegator) | |
external | |
view | |
returns (address) | |
{ | |
return _delegates[delegator]; | |
} | |
/** | |
* @notice Delegate votes from `msg.sender` to `delegatee` | |
* @param delegatee The address to delegate votes to | |
*/ | |
function delegate(address delegatee) external { | |
return _delegate(msg.sender, delegatee); | |
} | |
/** | |
* @notice Delegates votes from signatory to `delegatee` | |
* @param delegatee The address to delegate votes to | |
* @param nonce The contract state required to match the signature | |
* @param expiry The time at which to expire the signature | |
* @param v The recovery byte of the signature | |
* @param r Half of the ECDSA signature pair | |
* @param s Half of the ECDSA signature pair | |
*/ | |
function delegateBySig( | |
address delegatee, | |
uint nonce, | |
uint expiry, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) | |
external | |
{ | |
bytes32 domainSeparator = keccak256( | |
abi.encode( | |
DOMAIN_TYPEHASH, | |
keccak256(bytes(name())), | |
getChainId(), | |
address(this) | |
) | |
); | |
bytes32 structHash = keccak256( | |
abi.encode( | |
DELEGATION_TYPEHASH, | |
delegatee, | |
nonce, | |
expiry | |
) | |
); | |
bytes32 digest = keccak256( | |
abi.encodePacked( | |
"\x19\x01", | |
domainSeparator, | |
structHash | |
) | |
); | |
address signatory = ecrecover(digest, v, r, s); | |
require(signatory != address(0), "SEA::delegateBySig: invalid signature"); | |
require(nonce == nonces[signatory]++, "SEA::delegateBySig: invalid nonce"); | |
require(now <= expiry, "SEA::delegateBySig: signature expired"); | |
return _delegate(signatory, delegatee); | |
} | |
/** | |
* @notice Gets the current votes balance for `account` | |
* @param account The address to get votes balance | |
* @return The number of current votes for `account` | |
*/ | |
function getCurrentVotes(address account) | |
external | |
view | |
returns (uint256) | |
{ | |
uint32 nCheckpoints = numCheckpoints[account]; | |
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; | |
} | |
/** | |
* @notice Determine the prior number of votes for an account as of a block number | |
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation. | |
* @param account The address of the account to check | |
* @param blockNumber The block number to get the vote balance at | |
* @return The number of votes the account had as of the given block | |
*/ | |
function getPriorVotes(address account, uint blockNumber) | |
external | |
view | |
returns (uint256) | |
{ | |
require(blockNumber < block.number, "SEA::getPriorVotes: not yet determined"); | |
uint32 nCheckpoints = numCheckpoints[account]; | |
if (nCheckpoints == 0) { | |
return 0; | |
} | |
// First check most recent balance | |
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { | |
return checkpoints[account][nCheckpoints - 1].votes; | |
} | |
// Next check implicit zero balance | |
if (checkpoints[account][0].fromBlock > blockNumber) { | |
return 0; | |
} | |
uint32 lower = 0; | |
uint32 upper = nCheckpoints - 1; | |
while (upper > lower) { | |
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow | |
Checkpoint memory cp = checkpoints[account][center]; | |
if (cp.fromBlock == blockNumber) { | |
return cp.votes; | |
} else if (cp.fromBlock < blockNumber) { | |
lower = center; | |
} else { | |
upper = center - 1; | |
} | |
} | |
return checkpoints[account][lower].votes; | |
} | |
function _delegate(address delegator, address delegatee) | |
internal | |
{ | |
address currentDelegate = _delegates[delegator]; | |
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled); | |
_delegates[delegator] = delegatee; | |
emit DelegateChanged(delegator, currentDelegate, delegatee); | |
_moveDelegates(currentDelegate, delegatee, delegatorBalance); | |
} | |
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { | |
if (srcRep != dstRep && amount > 0) { | |
if (srcRep != address(0)) { | |
// decrease old representative | |
uint32 srcRepNum = numCheckpoints[srcRep]; | |
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; | |
uint256 srcRepNew = srcRepOld.sub(amount); | |
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); | |
} | |
if (dstRep != address(0)) { | |
// increase new representative | |
uint32 dstRepNum = numCheckpoints[dstRep]; | |
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; | |
uint256 dstRepNew = dstRepOld.add(amount); | |
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); | |
} | |
} | |
} | |
function _writeCheckpoint( | |
address delegatee, | |
uint32 nCheckpoints, | |
uint256 oldVotes, | |
uint256 newVotes | |
) | |
internal | |
{ | |
uint32 blockNumber = safe32(block.number, "SEA::_writeCheckpoint: block number exceeds 32 bits"); | |
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { | |
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; | |
} else { | |
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); | |
numCheckpoints[delegatee] = nCheckpoints + 1; | |
} | |
emit DelegateVotesChanged(delegatee, oldVotes, newVotes); | |
} | |
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { | |
require(n < 2**32, errorMessage); | |
return uint32(n); | |
} | |
function getChainId() internal pure returns (uint) { | |
uint256 chainId; | |
assembly { chainId := chainid() } | |
return chainId; | |
} | |
} | |
pragma solidity 0.6.12; | |
// SearupBar with Governance. | |
contract SearupBar is BEP20('SeaBar Token', 'SeaBar') { | |
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). | |
function mint(address _to, uint256 _amount) public onlyOwner { | |
_mint(_to, _amount); | |
_moveDelegates(address(0), _delegates[_to], _amount); | |
} | |
function burn(address _from ,uint256 _amount) public onlyOwner { | |
_burn(_from, _amount); | |
_moveDelegates(_delegates[_from], address(0), _amount); | |
} | |
// The CAKE TOKEN! | |
SeaToken public sea; | |
constructor( | |
SeaToken _sea | |
) public { | |
sea = _sea; | |
} | |
// Safe sea transfer function, just in case if rounding error causes pool to not have enough CAKEs. | |
function safeSeaTransfer(address _to, uint256 _amount) public onlyOwner { | |
uint256 seaBal = sea.balanceOf(address(this)); | |
if (_amount > seaBal) { | |
sea.transfer(_to, seaBal); | |
} else { | |
sea.transfer(_to, _amount); | |
} | |
} | |
// Copied and modified from YAM code: | |
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol | |
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol | |
// Which is copied and modified from COMPOUND: | |
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol | |
/// @notice A record of each accounts delegate | |
mapping (address => address) internal _delegates; | |
/// @notice A checkpoint for marking number of votes from a given block | |
struct Checkpoint { | |
uint32 fromBlock; | |
uint256 votes; | |
} | |
/// @notice A record of votes checkpoints for each account, by index | |
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; | |
/// @notice The number of checkpoints for each account | |
mapping (address => uint32) public numCheckpoints; | |
/// @notice The EIP-712 typehash for the contract's domain | |
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); | |
/// @notice The EIP-712 typehash for the delegation struct used by the contract | |
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); | |
/// @notice A record of states for signing / validating signatures | |
mapping (address => uint) public nonces; | |
/// @notice An event thats emitted when an account changes its delegate | |
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); | |
/// @notice An event thats emitted when a delegate account's vote balance changes | |
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); | |
/** | |
* @notice Delegate votes from `msg.sender` to `delegatee` | |
* @param delegator The address to get delegatee for | |
*/ | |
function delegates(address delegator) | |
external | |
view | |
returns (address) | |
{ | |
return _delegates[delegator]; | |
} | |
/** | |
* @notice Delegate votes from `msg.sender` to `delegatee` | |
* @param delegatee The address to delegate votes to | |
*/ | |
function delegate(address delegatee) external { | |
return _delegate(msg.sender, delegatee); | |
} | |
/** | |
* @notice Delegates votes from signatory to `delegatee` | |
* @param delegatee The address to delegate votes to | |
* @param nonce The contract state required to match the signature | |
* @param expiry The time at which to expire the signature | |
* @param v The recovery byte of the signature | |
* @param r Half of the ECDSA signature pair | |
* @param s Half of the ECDSA signature pair | |
*/ | |
function delegateBySig( | |
address delegatee, | |
uint nonce, | |
uint expiry, | |
uint8 v, | |
bytes32 r, | |
bytes32 s | |
) | |
external | |
{ | |
bytes32 domainSeparator = keccak256( | |
abi.encode( | |
DOMAIN_TYPEHASH, | |
keccak256(bytes(name())), | |
getChainId(), | |
address(this) | |
) | |
); | |
bytes32 structHash = keccak256( | |
abi.encode( | |
DELEGATION_TYPEHASH, | |
delegatee, | |
nonce, | |
expiry | |
) | |
); | |
bytes32 digest = keccak256( | |
abi.encodePacked( | |
"\x19\x01", | |
domainSeparator, | |
structHash | |
) | |
); | |
address signatory = ecrecover(digest, v, r, s); | |
require(signatory != address(0), "CAKE::delegateBySig: invalid signature"); | |
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce"); | |
require(now <= expiry, "CAKE::delegateBySig: signature expired"); | |
return _delegate(signatory, delegatee); | |
} | |
/** | |
* @notice Gets the current votes balance for `account` | |
* @param account The address to get votes balance | |
* @return The number of current votes for `account` | |
*/ | |
function getCurrentVotes(address account) | |
external | |
view | |
returns (uint256) | |
{ | |
uint32 nCheckpoints = numCheckpoints[account]; | |
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; | |
} | |
/** | |
* @notice Determine the prior number of votes for an account as of a block number | |
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation. | |
* @param account The address of the account to check | |
* @param blockNumber The block number to get the vote balance at | |
* @return The number of votes the account had as of the given block | |
*/ | |
function getPriorVotes(address account, uint blockNumber) | |
external | |
view | |
returns (uint256) | |
{ | |
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined"); | |
uint32 nCheckpoints = numCheckpoints[account]; | |
if (nCheckpoints == 0) { | |
return 0; | |
} | |
// First check most recent balance | |
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { | |
return checkpoints[account][nCheckpoints - 1].votes; | |
} | |
// Next check implicit zero balance | |
if (checkpoints[account][0].fromBlock > blockNumber) { | |
return 0; | |
} | |
uint32 lower = 0; | |
uint32 upper = nCheckpoints - 1; | |
while (upper > lower) { | |
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow | |
Checkpoint memory cp = checkpoints[account][center]; | |
if (cp.fromBlock == blockNumber) { | |
return cp.votes; | |
} else if (cp.fromBlock < blockNumber) { | |
lower = center; | |
} else { | |
upper = center - 1; | |
} | |
} | |
return checkpoints[account][lower].votes; | |
} | |
function _delegate(address delegator, address delegatee) | |
internal | |
{ | |
address currentDelegate = _delegates[delegator]; | |
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CAKEs (not scaled); | |
_delegates[delegator] = delegatee; | |
emit DelegateChanged(delegator, currentDelegate, delegatee); | |
_moveDelegates(currentDelegate, delegatee, delegatorBalance); | |
} | |
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { | |
if (srcRep != dstRep && amount > 0) { | |
if (srcRep != address(0)) { | |
// decrease old representative | |
uint32 srcRepNum = numCheckpoints[srcRep]; | |
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; | |
uint256 srcRepNew = srcRepOld.sub(amount); | |
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); | |
} | |
if (dstRep != address(0)) { | |
// increase new representative | |
uint32 dstRepNum = numCheckpoints[dstRep]; | |
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; | |
uint256 dstRepNew = dstRepOld.add(amount); | |
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); | |
} | |
} | |
} | |
function _writeCheckpoint( | |
address delegatee, | |
uint32 nCheckpoints, | |
uint256 oldVotes, | |
uint256 newVotes | |
) | |
internal | |
{ | |
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits"); | |
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { | |
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; | |
} else { | |
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); | |
numCheckpoints[delegatee] = nCheckpoints + 1; | |
} | |
emit DelegateVotesChanged(delegatee, oldVotes, newVotes); | |
} | |
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { | |
require(n < 2**32, errorMessage); | |
return uint32(n); | |
} | |
function getChainId() internal pure returns (uint) { | |
uint256 chainId; | |
assembly { chainId := chainid() } | |
return chainId; | |
} | |
} | |
pragma solidity 0.6.12; | |
interface IMigratorChef { | |
// Perform LP token migration from legacy PancakeSwap to SeaSwap. | |
// Take the current LP token address and return the new LP token address. | |
// Migrator should have full access to the caller's LP token. | |
// Return the new LP token address. | |
// | |
// XXX Migrator must have allowance access to SeaWorld LP tokens. | |
// SeaSwap must mint EXACTLY the same amount of SeaSwap LP tokens or | |
// else something bad will happen. Traditional SeaWorld does not | |
// do that so be careful! | |
function migrate(IBEP20 token) external returns (IBEP20); | |
} | |
// SeaMaster is the master of Sea. He can make Sea and he is a fair guy. | |
// | |
// Note that it's ownable and the owner wields tremendous power. The ownership | |
// will be transferred to a governance smart contract once SEA is sufficiently | |
// distributed and the community can show to govern itself. | |
// | |
// Have fun reading it. Hopefully it's bug-free. God bless. | |
contract SeaMaster is Context, Ownable{ | |
using SafeMath for uint256; | |
using SafeBEP20 for IBEP20; | |
/** | |
Added variables | |
*/ | |
mapping (uint256 => mapping (address => uint256)) _balances; | |
mapping(address => mapping(address => uint256)) private _allowances; | |
/** | |
Added variables end here | |
*/ | |
// Info of each user. | |
struct UserInfo { | |
uint256 amount; // How many LP tokens the user has provided. | |
uint256 rewardDebt; // Reward debt. See explanation below. | |
// | |
// We do some fancy math here. Basically, any point in time, the amount of SEAs | |
// entitled to a user but is pending to be distributed is: | |
// | |
// pending reward = (user.amount * pool.accSeaPerShare) - user.rewardDebt | |
// | |
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: | |
// 1. The pool's `accSeaPerShare` (and `lastRewardBlock`) gets updated. | |
// 2. User receives the pending reward sent to his/her address. | |
// 3. User's `amount` gets updated. | |
// 4. User's `rewardDebt` gets updated. | |
} | |
// Info of each pool. | |
struct PoolInfo { | |
IBEP20 lpToken; // Address of LP token contract. | |
uint256 allocPoint; // How many allocation points assigned to this pool. SEAs to distribute per block. | |
uint256 lastRewardBlock; // Last block number that SEAs distribution occurs. | |
uint256 accSeaPerShare; // Accumulated SEAs per share, times 1e12. See below. | |
} | |
// The SEA TOKEN! | |
SeaToken public sea; | |
// The SEARUP TOKEN! | |
SearupBar public searup; | |
// Dev address. | |
address public devaddr; | |
// SEA tokens created per block. | |
uint256 public seaPerBlock; | |
// Bonus muliplier for early sea makers. | |
uint256 public BONUS_MULTIPLIER = 1; | |
// The migrator contract. It has a lot of power. Can only be set through governance (owner). | |
IMigratorChef public migrator; | |
// Info of each pool. | |
PoolInfo[] public poolInfo; | |
// Info of each user that stakes LP tokens. | |
mapping (uint256 => mapping (address => UserInfo)) public userInfo; | |
// Total allocation points. Must be the sum of all allocation points in all pools. | |
uint256 public totalAllocPoint = 0; | |
// The block number when SEA mining starts. | |
uint256 public startBlock; | |
uint256 private _totalSupply; | |
event Deposit(address indexed user, uint256 indexed pid, uint256 amount); | |
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); | |
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); | |
event Transfer(address from, address to, uint256 value); | |
event Approval(address owner, address spender,uint256 amount); | |
constructor( SeaToken _sea, SearupBar _searup, address _devaddr, uint256 _seaPerBlock, uint256 _startBlock) public { | |
sea = _sea; | |
searup = _searup; | |
devaddr = _devaddr; | |
seaPerBlock = _seaPerBlock; | |
startBlock = _startBlock; | |
// staking pool | |
poolInfo.push(PoolInfo({ | |
lpToken: _sea, | |
allocPoint: 1000, | |
lastRewardBlock: startBlock, | |
accSeaPerShare: 0 | |
})); | |
totalAllocPoint = 1000; | |
} | |
/** | |
Added functions | |
*/ | |
function getOwner() external view returns (address) { | |
return owner(); | |
} | |
function totalSupply() public view returns (uint256) { | |
return _totalSupply; | |
} | |
function balanceOf(address account, uint256 tokenType) public view returns (uint256) { | |
return _balances[tokenType][account]; | |
} | |
function _approve( address owner, address spender, uint256 amount) internal { | |
require(owner != address(0), 'BEP20: approve from the zero address'); | |
require(spender != address(0), 'BEP20: approve to the zero address'); | |
_allowances[owner][spender] = amount; | |
emit Approval(owner, spender, amount); | |
} | |
// function _burn(address account, uint256 amount) internal { | |
// require(account != address(0), 'BEP20: burn from the zero address'); | |
// _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); | |
// _totalSupply = _totalSupply.sub(amount); | |
// emit Transfer(account, address(0), amount); | |
// } | |
// function _burnFrom(address account, uint256 amount) internal { | |
// _burn(account, amount); | |
// _approve(account,_msgSender(), | |
// _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance') | |
// ); | |
// } | |
function allowance(address owner, address spender) public view returns (uint256) { | |
return _allowances[owner][spender]; | |
} | |
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { | |
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); | |
return true; | |
} | |
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { | |
_approve(_msgSender(), spender, | |
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero') | |
); | |
return true; | |
} | |
function approve(address spender, uint256 amount) public returns (bool) { | |
_approve(_msgSender(), spender, amount); | |
return true; | |
} | |
function _transfer(address sender, address recipient, uint256 amount, uint tokenType) internal { | |
require(sender != address(0), 'BEP20: transfer from the zero address'); | |
require(recipient != address(0), 'BEP20: transfer to the zero address'); | |
_balances[tokenType][sender] = _balances[tokenType][sender].sub(amount, 'BEP20: transfer amount exceeds balance'); | |
// _balances[recipient] = _balances[recipient].add(amount); | |
_balances[tokenType][recipient]= _balances[tokenType][recipient].add(amount); | |
emit Transfer(sender, recipient, amount); | |
} | |
function transfer(address recipient, uint256 amount, uint _tokenType) public returns (bool) { | |
_transfer(_msgSender(), recipient, amount, _tokenType); | |
return true; | |
} | |
function transferFrom( address sender, address recipient, uint256 amount, uint _tokenType) public returns (bool) { | |
_transfer(sender, recipient, amount, _tokenType); | |
_approve( | |
sender, | |
_msgSender(), | |
_allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') | |
); | |
return true; | |
} | |
/** | |
Added functions end here | |
*/ | |
function updateMultiplier(uint256 multiplierNumber) public onlyOwner { | |
BONUS_MULTIPLIER = multiplierNumber; | |
} | |
function poolLength() external view returns (uint256) { | |
return poolInfo.length; | |
} | |
// Add a new lp to the pool. Can only be called by the owner. | |
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. | |
function add(uint256 _allocPoint, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { | |
if (_withUpdate) { | |
massUpdatePools(); | |
} | |
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; | |
totalAllocPoint = totalAllocPoint.add(_allocPoint); | |
poolInfo.push(PoolInfo({ | |
lpToken: _lpToken, | |
allocPoint: _allocPoint, | |
lastRewardBlock: lastRewardBlock, | |
accSeaPerShare: 0 | |
})); | |
updateStakingPool(); | |
} | |
// Update the given pool's SEA allocation point. Can only be called by the owner. | |
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { | |
if (_withUpdate) { | |
massUpdatePools(); | |
} | |
uint256 prevAllocPoint = poolInfo[_pid].allocPoint; | |
poolInfo[_pid].allocPoint = _allocPoint; | |
if (prevAllocPoint != _allocPoint) { | |
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); | |
updateStakingPool(); | |
} | |
} | |
function updateStakingPool() internal { | |
uint256 length = poolInfo.length; | |
uint256 points = 0; | |
for (uint256 pid = 1; pid < length; ++pid) { | |
points = points.add(poolInfo[pid].allocPoint); | |
} | |
if (points != 0) { | |
points = points.div(3); | |
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); | |
poolInfo[0].allocPoint = points; | |
} | |
} | |
// Set the migrator contract. Can only be called by the owner. | |
function setMigrator(IMigratorChef _migrator) public onlyOwner { | |
migrator = _migrator; | |
} | |
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. | |
function migrate(uint256 _pid) public { | |
require(address(migrator) != address(0), "migrate: no migrator"); | |
PoolInfo storage pool = poolInfo[_pid]; | |
IBEP20 lpToken = pool.lpToken; | |
uint256 bal = lpToken.balanceOf(address(this)); | |
lpToken.safeApprove(address(migrator), bal); | |
IBEP20 newLpToken = migrator.migrate(lpToken); | |
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); | |
pool.lpToken = newLpToken; | |
} | |
// Return reward multiplier over the given _from to _to block. | |
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { | |
return _to.sub(_from).mul(BONUS_MULTIPLIER); | |
} | |
// View function to see pending SEAs on frontend. | |
function pendingSea(uint256 _pid, address _user) external view returns (uint256) { | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][_user]; | |
uint256 accSeaPerShare = pool.accSeaPerShare; | |
uint256 lpSupply = pool.lpToken.balanceOf(address(this)); | |
if (block.number > pool.lastRewardBlock && lpSupply != 0) { | |
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); | |
uint256 seaReward = multiplier.mul(seaPerBlock).mul(pool.allocPoint).div(totalAllocPoint); | |
accSeaPerShare = accSeaPerShare.add(seaReward.mul(1e12).div(lpSupply)); | |
} | |
return user.amount.mul(accSeaPerShare).div(1e12).sub(user.rewardDebt); | |
} | |
// Update reward variables for all pools. Be careful of gas spending! | |
function massUpdatePools() public { | |
uint256 length = poolInfo.length; | |
for (uint256 pid = 0; pid < length; ++pid) { | |
updatePool(pid); | |
} | |
} | |
// Update reward variables of the given pool to be up-to-date. | |
function updatePool(uint256 _pid) public { | |
PoolInfo storage pool = poolInfo[_pid]; | |
if (block.number <= pool.lastRewardBlock) { | |
return; | |
} | |
uint256 lpSupply = pool.lpToken.balanceOf(address(this)); | |
if (lpSupply == 0) { | |
pool.lastRewardBlock = block.number; | |
return; | |
} | |
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); | |
uint256 seaReward = multiplier.mul(seaPerBlock).mul(pool.allocPoint).div(totalAllocPoint); | |
transferFrom(address(this), devaddr, seaReward.div(10),1); | |
//sea.mint(devaddr, seaReward.div(10)); | |
//sea.mint(address(searup), seaReward); | |
pool.accSeaPerShare = pool.accSeaPerShare.add(seaReward.mul(1e12).div(lpSupply)); | |
pool.lastRewardBlock = block.number; | |
} | |
// Deposit LP tokens to SeaMaster for SEA allocation. | |
function deposit(uint256 _pid, uint256 _amount) public { | |
require (_pid != 0, 'deposit SEA by staking'); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
updatePool(_pid); | |
if (user.amount > 0) { | |
uint256 pending = user.amount.mul(pool.accSeaPerShare).div(1e12).sub(user.rewardDebt); | |
if(pending > 0) { | |
safeSeaTransfer(msg.sender, pending); | |
} | |
} | |
if (_amount > 0) { | |
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); | |
user.amount = user.amount.add(_amount); | |
} | |
user.rewardDebt = user.amount.mul(pool.accSeaPerShare).div(1e12); | |
emit Deposit(msg.sender, _pid, _amount); | |
} | |
// Withdraw LP tokens from SeaMaster. | |
function withdraw(uint256 _pid, uint256 _amount) public { | |
require (_pid != 0, 'withdraw SEA by unstaking'); | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
require(user.amount >= _amount, "withdraw: not good"); | |
updatePool(_pid); | |
uint256 pending = user.amount.mul(pool.accSeaPerShare).div(1e12).sub(user.rewardDebt); | |
if(pending > 0) { | |
safeSeaTransfer(msg.sender, pending); | |
} | |
if(_amount > 0) { | |
user.amount = user.amount.sub(_amount); | |
pool.lpToken.safeTransfer(address(msg.sender), _amount); | |
} | |
user.rewardDebt = user.amount.mul(pool.accSeaPerShare).div(1e12); | |
emit Withdraw(msg.sender, _pid, _amount); | |
} | |
// Stake SEA tokens to SeaMaster | |
function enterStaking(uint256 _amount) public { | |
PoolInfo storage pool = poolInfo[0]; | |
UserInfo storage user = userInfo[0][msg.sender]; | |
updatePool(0); | |
if (user.amount > 0) { | |
uint256 pending = user.amount.mul(pool.accSeaPerShare).div(1e12).sub(user.rewardDebt); | |
if(pending > 0) { | |
safeSeaTransfer(msg.sender, pending); | |
} | |
} | |
if(_amount > 0) { | |
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); | |
user.amount = user.amount.add(_amount); | |
} | |
user.rewardDebt = user.amount.mul(pool.accSeaPerShare).div(1e12); | |
transferFrom(address(this), msg.sender, _amount,2); | |
// searup.mint(msg.sender, _amount); | |
emit Deposit(msg.sender, 0, _amount); | |
} | |
// Withdraw SEA tokens from STAKING. | |
function leaveStaking(uint256 _amount) public { | |
PoolInfo storage pool = poolInfo[0]; | |
UserInfo storage user = userInfo[0][msg.sender]; | |
require(user.amount >= _amount, "withdraw: not good"); | |
updatePool(0); | |
uint256 pending = user.amount.mul(pool.accSeaPerShare).div(1e12).sub(user.rewardDebt); | |
if(pending > 0) { | |
safeSeaTransfer(msg.sender, pending); | |
} | |
if(_amount > 0) { | |
user.amount = user.amount.sub(_amount); | |
pool.lpToken.safeTransfer(address(msg.sender), _amount); | |
} | |
user.rewardDebt = user.amount.mul(pool.accSeaPerShare).div(1e12); | |
searup.burn(msg.sender, _amount); | |
emit Withdraw(msg.sender, 0, _amount); | |
} | |
// Withdraw without caring about rewards. EMERGENCY ONLY. | |
function emergencyWithdraw(uint256 _pid) public { | |
PoolInfo storage pool = poolInfo[_pid]; | |
UserInfo storage user = userInfo[_pid][msg.sender]; | |
pool.lpToken.safeTransfer(address(msg.sender), user.amount); | |
emit EmergencyWithdraw(msg.sender, _pid, user.amount); | |
user.amount = 0; | |
user.rewardDebt = 0; | |
} | |
// Safe sea transfer function, just in case if rounding error causes pool to not have enough SEAs. | |
function safeSeaTransfer(address _to, uint256 _amount) internal { | |
searup.safeSeaTransfer(_to, _amount); | |
} | |
// Update dev address by the previous dev. | |
function dev(address _devaddr) public { | |
require(msg.sender == devaddr, "dev: wut?"); | |
devaddr = _devaddr; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.0; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/ERC1155.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC1155/utils/ERC1155Holder.sol"; | |
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol"; | |
contract ALIAPIToken is ERC1155,ERC1155Holder,Ownable{ | |
using SafeMath for uint256; | |
///////////////////////////////////////////////////////////////////////// | |
// state variables | |
///////////////////////////////////////////////////////////////////////// | |
uint256 totalHolders; | |
//dai address | |
address private _token = 0xc7AD46e0b8a400Bb3C915120d284AafbA8fc4735; | |
IERC20 private token; | |
address panacloud; | |
mapping(uint256 => address) private ownerOfTokenId; | |
bool isSold; | |
///////////////////////////////////////////////////////////////////////// | |
// Tokens | |
///////////////////////////////////////////////////////////////////////// | |
uint256 public constant AliAPIToken =0; | |
uint256 public constant ProjectA = 1; | |
uint256 public constant ProjectB = 2; | |
///////////////////////////////////////////////////////////////////////// | |
// percentages | |
///////////////////////////////////////////////////////////////////////// | |
uint256 public panaCloudPercentage = 5; | |
uint256 public investorPercentage = 10; | |
///////////////////////////////////////////////////////////////////////// | |
// Events | |
///////////////////////////////////////////////////////////////////////// | |
event PanacloudAddessChanged(address); | |
event DaiReceived(uint256 DaiAmount); | |
event APITokenMinted(address,uint256); | |
event RSNFTABoughtby(address); | |
event RSNFTBBoughtby(address); | |
event TransferredInvestorPercentage(address); | |
event TransferredPanacloudPercentage(address); | |
event TransferredToAPIDeveloper(address, uint256); | |
///////////////////////////////////////////////////////////////////////// | |
// constructor | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev Creating instance to Dai contract, minting A & B NFT's to this contract address. | |
* @param _panacloud address to set panacloud address to send revenue percentage. | |
*/ | |
constructor(address _panacloud) ERC1155("") { | |
panacloud = _panacloud; | |
token = IERC20(_token); | |
totalHolders = 0; | |
isSold = false; | |
//minting token to this address | |
_mint(address(this),ProjectA,1,"0x0"); //NFT | |
//minting token to this address | |
_mint(address(this),ProjectB,2,"0x0"); //NFT | |
// setApprovalForAll(address(this), true); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//supportsInterface | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to check whether this contract supportsInterface ERC1155Receiver and ERC1155 | |
* @param interfaceId to check whether this contract supportsInterface ERC1155Receiver and ERC1155 | |
*/ | |
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, ERC1155Receiver) returns (bool) { | |
return super.supportsInterface(interfaceId); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
// changePanacloudAddress | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to change panacloud wallet address | |
* Rules: | |
* - only owner | |
* @param _address to set new wallet address | |
*/ | |
function changePanacloudAddress(address _address) external onlyOwner{ | |
panacloud = _address; | |
emit PanacloudAddessChanged(panacloud); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//checkDaiAllowance | |
///////////////////////////////////////////////////////////////////////// | |
function checkDaiAllowance() external view returns(uint daiAllowed){ | |
uint bal = token.allowance(msg.sender,address(this)); | |
return bal; | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//onDaiReceive | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev when this contract will receive any revenue e.g. dai token, it will send some percentage to panacloud, | |
* developer and Project Share holder addresses. | |
*we can automate this function by calling it in buyAPIToken function. | |
* for now, as per my understanding I am doing this way | |
* Rules: | |
* @param _daiAmount to sent to ALIAPI contract | |
*/ | |
function onDaiReceive(uint _daiAmount) external { | |
// checking dai allowance is not equal to zero | |
require(token.allowance(msg.sender,address(this)) != 0,"zero allowance, pleae approve DAI first to be used by this contract"); | |
address from = msg.sender; | |
//transferring tokens from caller to this contract address | |
require(token.transferFrom(from, address(this), _daiAmount)== true,"error"); | |
//transferring tokens to API developer by getting percentage | |
uint investorP = (_daiAmount*investorPercentage)/100; | |
for(uint i = 0 ; i<=totalHolders; i++) { | |
token.transfer(ownerOfTokenId[i], investorP); | |
emit TransferredInvestorPercentage(ownerOfTokenId[i]); | |
} | |
//transferring token percentage to panacloud | |
uint panacloudP = (_daiAmount*panaCloudPercentage)/100; | |
token.transfer(panacloud, panacloudP); | |
emit TransferredPanacloudPercentage(panacloud); | |
//transfer tokens to API developer | |
require(token.transfer(owner(), token.balanceOf(address(this))),"Fialed to transfer tokens to API Developer"); | |
emit TransferredToAPIDeveloper(owner(),token.balanceOf(address(this))); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//buyAPIToken | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev user can buy AliAPIToken with DAI, that is currency to buy RS-NFT for differet projects. | |
* User must buy AliAPI tokens with Dai, then he can buy RS-NFT with AliAPITokens | |
* Rules: | |
* he needs to set Dai allowance first | |
* @param _amount of Dai to send to this contract to buy FS-NFT | |
*/ | |
function buyAPIToken(uint _amount) external returns(uint){ | |
//checking allowance | |
require(token.allowance(msg.sender,address(this)) != 0,"zero allowance, pleae approve DAI first to be used by this contract"); | |
address from = msg.sender; | |
//transferring DAI tokens from user to this address. | |
// it is different than onDaiReceive | |
require(token.transferFrom(from, address(this), _amount)== true,"error"); | |
emit DaiReceived(_amount); | |
uint256 tAmount = _amount.div(10**18); | |
//minting AliAPITokens to user | |
_mint(msg.sender, AliAPIToken,tAmount * 100, ""); | |
emit APITokenMinted(msg.sender, tAmount * 100); | |
return tAmount; | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//buyRSNFTForProjectA | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to buy share for ProjectA | |
* user will send 100 AlI API tokens to this address to buy RS-NFT for ProjectA | |
*/ | |
function buyRSNFTForProjectA() external { | |
require(isSold == false,"This API token is sold"); | |
//checking balance Of AliAPIToken in user's account | |
require(balanceOf(msg.sender,AliAPIToken) != 0, "Please buy API tokens first to buy RS-NFT"); | |
//transferring tokens from user aaccount to this contract address | |
_safeTransferFrom(msg.sender,address(this), AliAPIToken,100,""); | |
//transfer RS-NFT to user | |
_safeTransferFrom(address(this), msg.sender, ProjectA, 1, ""); | |
ownerOfTokenId[ProjectA] = msg.sender; | |
totalHolders++; | |
isSold = true; | |
emit RSNFTABoughtby(msg.sender); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//buyRSNFTForProjectB | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to buy share for ProjectB | |
* user will send 500 ALI API tokens to this address to buy RS-NFT for ProjectA | |
*/ | |
function buyRSNFTForProjectB() external { | |
require(isSold == false,"This API token is sold"); | |
//checking balance Of AliAPIToken in user's account | |
require(balanceOf(msg.sender,AliAPIToken) != 0, "Please buy API tokens first to buy RS-NFT"); | |
//transferring tokens from user aaccount to this contract address | |
_safeTransferFrom(msg.sender,address(this), AliAPIToken,100,""); | |
//transfer RS-NFT to user | |
_safeTransferFrom(address(this), msg.sender, ProjectB, 1, "0x0"); | |
ownerOfTokenId[ProjectB] = msg.sender; | |
totalHolders++; | |
isSold = true; | |
emit RSNFTBBoughtby(msg.sender); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//balanceOfDaiForContract | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to check balance of Dai tokens in this contract | |
* Rules: | |
* onlyOwner | |
*/ | |
function balanceOfDaiForContract() external view onlyOwner returns(uint daiBalance){ | |
return token.balanceOf(address(this)); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//checkDaiBalanceForUser | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev to check balance of Dai tokens in user wallet address | |
* Rules: | |
* onlyOwner | |
* @param _add to check balance of any user | |
*/ | |
function checkDaiBalanceForUser(address _add) external view returns(uint daiBalanceOFUser){ | |
return token.balanceOf(_add); | |
} | |
///////////////////////////////////////////////////////////////////////// | |
//withdrawDai | |
///////////////////////////////////////////////////////////////////////// | |
/** | |
* @dev withdraw Dai tokens from this smart contract | |
* Rules: | |
* onlyOwner | |
*/ | |
function withdrawDai() external onlyOwner { | |
require(token.balanceOf(address(this)) !=0,""); | |
//transfer tokens to API developer | |
token.transfer(owner(), token.balanceOf(address(this))); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// File: contracts/ExmplToken.sol | |
// ExmplToken Smart Contract. ExmplToken | |
// SPDX-License-Identifier: MIT | |
pragma solidity ^0.8.2; | |
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-ERC20PermitUpgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20VotesUpgradeable.sol"; | |
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; | |
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; | |
contract ExmplToken is Initializable, ERC20Upgradeable, ERC20BurnableUpgradeable, PausableUpgradeable, OwnableUpgradeable, ERC20PermitUpgradeable, ERC20VotesUpgradeable, UUPSUpgradeable { | |
function initialize() initializer public { | |
__ERC20_init("ExmplToken", "EMPL"); | |
__ERC20Burnable_init(); | |
__Pausable_init(); | |
__Ownable_init(); | |
__ERC20Permit_init("ExmplToken"); | |
__UUPSUpgradeable_init(); | |
_mint(msg.sender, 1000000000 * 10 ** decimals()); | |
} | |
function pause() public onlyOwner { | |
_pause(); | |
} | |
function unpause() public onlyOwner { | |
_unpause(); | |
} | |
function mint(address to, uint256 amount) public onlyOwner { | |
_mint(to, amount); | |
} | |
function _beforeTokenTransfer(address from, address to, uint256 amount) | |
internal | |
whenNotPaused | |
override | |
{ | |
super._beforeTokenTransfer(from, to, amount); | |
} | |
function _authorizeUpgrade(address newImplementation) | |
internal | |
onlyOwner | |
override | |
{} | |
function _afterTokenTransfer(address from, address to, uint256 amount) | |
internal | |
override(ERC20Upgradeable, ERC20VotesUpgradeable) | |
{ | |
super._afterTokenTransfer(from, to, amount); | |
} | |
function _mint(address to, uint256 amount) | |
internal | |
override(ERC20Upgradeable, ERC20VotesUpgradeable) | |
{ | |
super._mint(to, amount); | |
} | |
function _burn(address account, uint256 amount) | |
internal | |
override(ERC20Upgradeable, ERC20VotesUpgradeable) | |
{ | |
super._burn(account, amount); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment