file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
pragma solidity 0.4.21;
/*
Nectar Community Governance Proposals Contract, deployed 18/03/18
*/
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
contract Controlled {
/// @notice The address of the controller is the only address that can call
/// a function with this modifier
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
/// @dev The actual token contract, the default controller is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token controller contract, which Giveth will call a "Campaign"
contract MiniMeToken is Controlled {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = 'MMT_0.2'; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The controller of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// controller of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != controller) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != 0) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token controller of the transfer
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(0, _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, 0, _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's controller has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token controller contract
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the controller to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
Copyright 2018, Nikola Klipa @ Decenter
*/
/// @title ProposalManager Contract
/// @author Nikola Klipa @ Decenter
contract ProposalManager is Ownable {
address constant NECTAR_TOKEN = 0xCc80C051057B774cD75067Dc48f8987C4Eb97A5e;
address constant TOKEN_FACTORY = 0x003ea7f54b6Dcf6cEE86986EdC18143A35F15505;
uint constant MIN_PROPOSAL_DURATION = 7;
uint constant MAX_PROPOSAL_DURATION = 45;
struct Proposal {
address proposer;
uint startBlock;
uint startTime;
uint duration;
address token;
bytes32 storageHash;
bool approved;
uint yesVotes;
uint noVotes;
bool denied;
}
Proposal[] proposals;
MiniMeTokenFactory public tokenFactory;
address nectarToken;
mapping(address => bool) admins;
modifier onlyAdmins() {
require(isAdmin(msg.sender));
_;
}
function ProposalManager() public {
tokenFactory = MiniMeTokenFactory(TOKEN_FACTORY);
nectarToken = NECTAR_TOKEN;
admins[msg.sender] = true;
}
/// @notice Add new proposal and put it in list to be approved
/// @param _duration Duration of proposal in days after it is approved
/// @param _storageHash Hash to text of proposal
/// @return Created proposal id
function addProposal(
uint _duration, // number of days
bytes32 _storageHash) public returns (uint _proposalId)
{
require(_duration >= MIN_PROPOSAL_DURATION);
require(_duration <= MAX_PROPOSAL_DURATION);
uint amount = MiniMeToken(nectarToken).balanceOf(msg.sender);
require(amount > 0); // user can't submit proposal if doesn't own any tokens
_proposalId = proposals.length;
proposals.length++;
Proposal storage p = proposals[_proposalId];
p.storageHash = _storageHash;
p.duration = _duration * (1 days);
p.proposer = msg.sender;
emit NewProposal(_proposalId, _duration, _storageHash);
}
/// @notice Admins are able to approve proposal that someone submitted
/// @param _proposalId Id of proposal that admin approves
function approveProposal(uint _proposalId) public onlyAdmins {
require(proposals.length > _proposalId);
require(!proposals[_proposalId].denied);
Proposal storage p = proposals[_proposalId];
// if not checked, admin is able to restart proposal
require(!p.approved);
p.token = tokenFactory.createCloneToken(
nectarToken,
getBlockNumber(),
appendUintToString("NectarProposal-", _proposalId),
MiniMeToken(nectarToken).decimals(),
appendUintToString("NP-", _proposalId),
true);
p.approved = true;
p.startTime = now;
p.startBlock = getBlockNumber();
emit Approved(_proposalId);
}
/// @notice Vote for specific proposal with yes or no
/// @param _proposalId Id of proposal that we user is voting for
/// @param _yes True if user is voting for yes and false if no
function vote(uint _proposalId, bool _yes) public {
require(_proposalId < proposals.length);
require(checkIfCurrentlyActive(_proposalId));
Proposal memory p = proposals[_proposalId];
uint amount = MiniMeToken(p.token).balanceOf(msg.sender);
require(amount > 0);
require(MiniMeToken(p.token).transferFrom(msg.sender, address(this), amount));
if (_yes) {
proposals[_proposalId].yesVotes += amount;
}else {
proposals[_proposalId].noVotes += amount;
}
emit Vote(_proposalId, msg.sender, _yes, amount);
}
/// @notice Any admin is able to add new admin
/// @param _newAdmin Address of new admin
function addAdmin(address _newAdmin) public onlyAdmins {
admins[_newAdmin] = true;
}
/// @notice Only owner is able to remove admin
/// @param _admin Address of current admin
function removeAdmin(address _admin) public onlyOwner {
admins[_admin] = false;
}
/// @notice Get data about specific proposal
/// @param _proposalId Id of proposal
function proposal(uint _proposalId) public view returns(
address _proposer,
uint _startBlock,
uint _startTime,
uint _duration,
bytes32 _storageHash,
bool _active,
bool _finalized,
uint _totalYes,
uint _totalNo,
address _token,
bool _approved,
bool _denied,
bool _hasBalance
) {
require(_proposalId < proposals.length);
Proposal memory p = proposals[_proposalId];
_proposer = p.proposer;
_startBlock = p.startBlock;
_startTime = p.startTime;
_duration = p.duration;
_storageHash = p.storageHash;
_finalized = (_startTime+_duration < now);
_active = !_finalized && (p.startBlock < getBlockNumber()) && p.approved;
_totalYes = p.yesVotes;
_totalNo = p.noVotes;
_token = p.token;
_approved = p.approved;
_denied = p.denied;
_hasBalance = (p.token == 0x0) ? false : (MiniMeToken(p.token).balanceOf(msg.sender) > 0);
}
function denyProposal(uint _proposalId) public onlyAdmins {
require(!proposals[_proposalId].approved);
proposals[_proposalId].denied = true;
}
/// @notice Get all not approved proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getNotApprovedProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (!proposals[i].approved && !proposals[i].denied) {
count++;
}
}
uint[] memory notApprovedProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (!proposals[i].approved && !proposals[i].denied) {
notApprovedProposals[count] = i;
count++;
}
}
return notApprovedProposals;
}
/// @notice Get all approved proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getApprovedProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
count++;
}
}
uint[] memory approvedProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
approvedProposals[count] = i;
count++;
}
}
return approvedProposals;
}
/// @notice Get all active proposals
/// @dev looping two times through array so we can make array with exact count
/// because of Solidity limitation to make dynamic array in memory
function getActiveProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (checkIfCurrentlyActive(i)) {
count++;
}
}
uint[] memory activeProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (checkIfCurrentlyActive(i)) {
activeProposals[count] = i;
count++;
}
}
return activeProposals;
}
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
if (v==0) {
reversed[i++] = byte(48);
} else {
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function nProposals() public view returns(uint) {
return proposals.length;
}
function isAdmin(address _admin) public view returns(bool) {
return admins[_admin];
}
function checkIfCurrentlyActive(uint _proposalId) private view returns(bool) {
Proposal memory p = proposals[_proposalId];
return (p.startTime + p.duration > now && p.startTime < now && p.approved && !p.denied);
}
function proxyPayment(address ) public payable returns(bool) {
return false;
}
function onTransfer(address , address , uint ) public pure returns(bool) {
return true;
}
function onApprove(address , address , uint ) public pure returns(bool) {
return true;
}
function getBlockNumber() internal constant returns (uint) {
return block.number;
}
event Vote(uint indexed idProposal, address indexed _voter, bool yes, uint amount);
event Approved(uint indexed idProposal);
event NewProposal(uint indexed idProposal, uint duration, bytes32 storageHash);
}
|
Get all approved proposals looping two times through array so we can make array with exact count because of Solidity limitation to make dynamic array in memory
|
function getApprovedProposals() public view returns(uint[]) {
uint count = 0;
for (uint i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
count++;
}
}
uint[] memory approvedProposals = new uint[](count);
count = 0;
for (i=0; i<proposals.length; i++) {
if (proposals[i].approved && !proposals[i].denied) {
approvedProposals[count] = i;
count++;
}
}
return approvedProposals;
}
| 344,222
|
pragma solidity ^0.6;
pragma experimental ABIEncoderV2;
import "../../../lib/Math.sol";
import {Classifier64} from "./Classifier.sol";
/**
* A nearest centroid classifier that uses Euclidean distance to predict the closest centroid.
*
* https://en.wikipedia.org/wiki/Nearest_centroid_classifier
*/
contract NearestCentroidClassifier is Classifier64 {
/** A class has been added. */
event AddClass(
/** The name of the class. */
string name,
/** The index for the class in the members of this classifier. */
uint index
);
uint256 constant public UINT256_MAX = ~uint256(0);
uint256 constant public dataCountLimit = 2 ** (256 - 64 - 1);
int64[][] public centroids;
uint[] public dataCounts;
constructor(
string[] memory _classifications,
int64[][] memory _centroids,
uint[] memory _dataCounts)
Classifier64(_classifications) public {
require(_centroids.length == _classifications.length, "The number of centroids and classifications must be the same.");
require(_classifications.length > 0, "At least one class is required.");
require(_classifications.length < 2 ** 64, "Too many classes given.");
centroids = _centroids;
dataCounts = _dataCounts;
uint dimensions = centroids[0].length;
for (uint i = 1; i < centroids.length; ++i) {
require(centroids[i].length == dimensions, "Inconsistent number of dimensions.");
}
}
/**
* Extend the number of dimensions of a centroid.
* Made to be called just after the contract is created and never again.
* @param extension The values to append to a centroid vector.
* @param classification The class to add the extension to.
*/
function extendCentroid(int64[] memory extension, uint64 classification) public onlyOwner {
require(classification < classifications.length, "This classification has not been added yet.");
require(centroids[classification].length + extension.length < 2 ** 63, "Centroid would be too long.");
for (uint i = 0; i < extension.length; ++i) {
centroids[classification].push(extension[i]);
}
}
function addClass(int64[] memory centroid, string memory classification, uint dataCount) public onlyOwner {
require(classifications.length + 1 < 2 ** 64, "There are too many classes already.");
require(centroid.length == centroids[0].length, "Data doesn't have the correct number of dimensions.");
require(dataCount < dataCountLimit, "Data count is too large.");
classifications.push(classification);
centroids.push(centroid);
dataCounts.push(dataCount);
emit AddClass(classification, classifications.length - 1);
}
function norm(int64[] memory data) public override pure returns (uint result) {
result = 0;
for (uint i = 0; i < data.length; ++i) {
result = result.add(uint(int128(data[i]) * data[i]));
}
result = Math.sqrt(result);
}
function predict(int64[] memory data) public override view returns (uint64 bestClass) {
require(data.length == centroids[0].length, "Data doesn't have the correct length.");
uint minDistance = UINT256_MAX;
bestClass = 0;
for (uint64 currentClass = 0; currentClass < centroids.length; ++currentClass) {
uint distance = 0;
for (uint j = 0; j < data.length; ++j) {
// Safe calculation because both values are int64.
int diff = data[j];
diff -= centroids[currentClass][j];
diff *= diff;
// Convert back to our float representation.
diff /= toFloat;
distance = distance.add(uint(diff));
if (distance >= minDistance) {
break;
}
}
if (distance < minDistance) {
minDistance = distance;
bestClass = currentClass;
}
}
}
function update(int64[] memory data, uint64 classification) public override onlyOwner {
require(data.length == centroids[classification].length, "Data doesn't have the correct number of dimensions.");
require(classification < classifications.length, "Classification is out of bounds.");
int64[] memory centroid = centroids[classification];
uint n = dataCounts[classification];
uint newN;
// Keep n small enough for multiplication.
if (n >= dataCountLimit) {
newN = dataCounts[classification];
} else {
newN = dataCounts[classification] + 1;
dataCounts[classification] = newN;
}
// Update centroid using moving average calculation.
int64[] memory c = new int64[](data.length);
uint _norm = 0;
for (uint j = 0; j < data.length; ++j) {
int128 datum = int128(data[j]);
_norm = _norm.add(uint(datum * datum));
c[j] = int64((int(centroid[j]) * int(n) + datum) / int(newN));
}
centroids[classification] = c;
// Must be almost within `toFloat` of `toFloat*toFloat` because we only care about the first `toFloat` digits.
uint oneSquared = uint(toFloat).mul(toFloat);
uint offset = uint(toFloat) * 100;
require(oneSquared - offset < _norm && _norm < oneSquared + offset, "The provided data does not have a norm of 1.");
}
// Useful methods to view the underlying data:
// To match the `SparseNearestCentroidClassifier`.
// These methods are not really needed now but they are added in case the implementation of the class
// changes later after some gas cost analysis.
function getNumSamples(uint classIndex) public view returns (uint) {
return dataCounts[classIndex];
}
function getCentroidValue(uint classIndex, uint featureIndex) public view returns (int64) {
return centroids[classIndex][featureIndex];
}
}
|
Safe calculation because both values are int64. Convert back to our float representation.
|
function predict(int64[] memory data) public override view returns (uint64 bestClass) {
require(data.length == centroids[0].length, "Data doesn't have the correct length.");
uint minDistance = UINT256_MAX;
bestClass = 0;
for (uint64 currentClass = 0; currentClass < centroids.length; ++currentClass) {
uint distance = 0;
for (uint j = 0; j < data.length; ++j) {
int diff = data[j];
diff -= centroids[currentClass][j];
diff *= diff;
diff /= toFloat;
distance = distance.add(uint(diff));
if (distance >= minDistance) {
break;
}
}
if (distance < minDistance) {
minDistance = distance;
bestClass = currentClass;
}
}
}
| 974,538
|
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract IERC20 {
function balanceOf(address _to) public constant returns (uint256);
function transfer(address to, uint256 value) public;
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public;
function allowance(address owner, address spender) public constant returns(uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is IERC20{
using SafeMath for uint256;
// Balances for each account
mapping (address => uint256) balances;
// Owner of account approves the transfer of an amount to another account
mapping (address => mapping(address => uint256)) allowed;
// What is the balance of a particular account?
// @param who The address of the particular account
// @return the balanace the particular account
function balanceOf(address _to) public constant returns (uint256) {
return balances[_to];
}
// @notice send `value` token to `to` from `msg.sender`
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transfer(address to, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
// @notice send `value` token to `to` from `from`
// @param from The address of the sender
// @param to The address of the recipient
// @param value The amount of token to be transferred
// @return the transaction address and send the event as Transfer
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balances[from] >= value && value > 0
);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
// Allow spender to withdraw from your account, multiple times, up to the value amount.
// If this function is called again it overwrites the current allowance with value.
// @param spender The address of the sender
// @param value The amount to be approved
// @return the transaction address and send the event as Approval
function approve(address spender, uint256 value) public {
require (
balances[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address _owner, address spender) public constant returns (uint256) {
return allowed[_owner][spender];
}
}
contract TLC is StandardToken {
using SafeMath for uint256;
string public constant name = "Toplancer";
string public constant symbol = "TLC";
uint256 public constant decimals = 18;
uint256 public constant totalSupply = 400000000e18;
}
contract TLCMarketCrowdsale is TLC {
uint256 public minContribAmount = 0.1 ether; // 0.1 ether
uint256 public presaleCap = 20000000e18; // 5%
uint256 public soldTokenInPresale;
uint256 public publicSaleCap = 320000000e18; // 80%
uint256 public soldTokenInPublicsale;
uint256 public distributionSupply = 60000000e18; // 15%
uint256 public softCap = 5000 ether;
uint256 public hardCap = 60000 ether;
// amount of raised money in wei
uint256 public weiRaised = 0;
// Wallet Address of Token
address public multisig;
// Owner of Token
address public owner;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// how many token units a buyer gets per wei
uint256 public rate = 3500 ; // 1 ether = 3500 TLC
// How much ETH each address has invested to this publicsale
mapping (address => uint256) public investedAmountOf;
// How many distinct addresses have invested
uint256 public investorCount;
// fund raised during public sale
uint256 public fundRaisedDuringPublicSale = 0;
// How much wei we have returned back to the contract after a failed crowdfund.
uint256 public loadedRefund = 0;
// How much wei we have given back to investors.
uint256 public weiRefunded = 0;
enum Stage {PRESALE, PUBLICSALE, SUCCESS, FAILURE, REFUNDING, CLOSED}
Stage public stage;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// Refund was processed for a contributor
event Refund(address investor, uint256 weiAmount);
function TLCMarketCrowdsale(uint256 _startTime, uint256 _endTime, address _wallet) {
require( _endTime >= _startTime && _wallet != 0x0);
startTime = _startTime;
endTime = _endTime;
multisig = _wallet;
owner=msg.sender;
balances[multisig] = totalSupply;
stage = Stage.PRESALE;
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
uint256 timebasedBonus = tokens.mul(getTimebasedBonusRate()).div(100);
tokens = tokens.add(timebasedBonus);
forwardFunds();
if (stage == Stage.PRESALE) {
assert (soldTokenInPresale + tokens <= presaleCap);
soldTokenInPresale = soldTokenInPresale.add(tokens);
} else {
assert (soldTokenInPublicsale + tokens <= publicSaleCap);
if(investedAmountOf[beneficiary] == 0) {
// A new investor
investorCount++;
}
// Update investor
investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount);
fundRaisedDuringPublicSale = fundRaisedDuringPublicSale.add(weiAmount);
soldTokenInPublicsale = soldTokenInPublicsale.add(tokens);
}
balances[multisig] = balances[multisig].sub(tokens);
balances[beneficiary] = balances[beneficiary].add(tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
multisig.transfer(msg.value);
}
// Payable method
// @notice Anyone can buy the tokens on tokensale by paying ether
function () public payable {
buyTokens(msg.sender);
}
// modifier to allow only owner has full control on the function
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier isRefunding {
require (stage == Stage.REFUNDING);
_;
}
modifier isFailure {
require (stage == Stage.FAILURE);
_;
}
// @return true if crowdsale current lot event has ended
function hasEnded() public constant returns (bool) {
return getNow() > endTime;
}
// @return current time
function getNow() public constant returns (uint256) {
return (now * 1000);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = getNow() >= startTime && getNow() <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool minContribution = minContribAmount <= msg.value;
return withinPeriod && nonZeroPurchase && minContribution;
}
// Get the time-based bonus rate
function getTimebasedBonusRate() internal constant returns (uint256) {
uint256 bonusRate = 0;
if (stage == Stage.PRESALE) {
bonusRate = 50;
} else {
uint256 nowTime = getNow();
uint256 bonusFirstWeek = startTime + (7 days * 1000);
uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000);
uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000);
uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000);
if (nowTime <= bonusFirstWeek) {
bonusRate = 25;
} else if (nowTime <= bonusSecondWeek) {
bonusRate = 20;
} else if (nowTime <= bonusThirdWeek) {
bonusRate = 10;
} else if (nowTime <= bonusFourthWeek) {
bonusRate = 5;
}
}
return bonusRate;
}
// Start public sale
function startPublicsale(uint256 _startTime, uint256 _endTime, uint256 _tokenPrice) public onlyOwner {
require(hasEnded() && stage == Stage.PRESALE && _endTime >= _startTime && _tokenPrice > 0);
stage = Stage.PUBLICSALE;
startTime = _startTime;
endTime = _endTime;
rate = _tokenPrice;
}
// @return true if the crowdsale has raised enough money to be successful.
function isMaximumGoalReached() public constant returns (bool reached) {
return weiRaised >= hardCap;
}
// Validate and update the crowdsale stage
function updateICOStatus() public onlyOwner {
require(hasEnded() && stage == Stage.PUBLICSALE);
if (hasEnded() && weiRaised >= softCap) {
stage = Stage.SUCCESS;
} else if (hasEnded()) {
stage = Stage.FAILURE;
}
}
// Allow load refunds back on the contract for the refunding. The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.
function loadRefund() public payable isFailure{
require(msg.value != 0);
loadedRefund = loadedRefund.add(msg.value);
if (loadedRefund <= fundRaisedDuringPublicSale) {
stage = Stage.REFUNDING;
}
}
// Investors can claim refund.
// Note that any refunds from indirect buyers should be handled separately, and not through this contract.
function refund() public isRefunding {
uint256 weiValue = investedAmountOf[msg.sender];
require (weiValue != 0);
investedAmountOf[msg.sender] = 0;
balances[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
if (weiRefunded <= fundRaisedDuringPublicSale) {
stage = Stage.CLOSED;
}
}
// Set/change Multi-signature wallet address
function changeMultiSignatureWallet (address _multisig)public onlyOwner{
multisig = _multisig;
}
// Change Minimum contribution
function changeMinContribution(uint256 _minContribAmount)public onlyOwner {
minContribAmount = _minContribAmount;
}
//Change Presale Publicsale end time
function changeEndTime(uint256 _endTime) public onlyOwner {
require(endTime > startTime);
endTime = _endTime;
}
// Token distribution to Founder, Key Employee Allocation
// _founderAndTeamCap = 10000000e18; 10%
function sendFounderAndTeamToken(address to, uint256 value) public onlyOwner{
require (
to != 0x0 && value > 0 && distributionSupply >= value
);
balances[multisig] = balances[multisig].sub(value);
balances[to] = balances[to].add(value);
distributionSupply = distributionSupply.sub(value);
Transfer(multisig, to, value);
}
}
|
return true if crowdsale current lot event has ended
|
function hasEnded() public constant returns (bool) {
return getNow() > endTime;
}
| 14,051,215
|
./full_match/5/0xeae556E2fC50B52D16aaC68A3D42a74d2E785F39/sources/project_/contracts/NFTSale.sol
|
Withdraw BuyNow price
|
function withdrawDirectSale(address _nftContractAddress, uint256 _tokenId)
external
onlyNftOwner(_nftContractAddress, _tokenId)
{
_resetDirectSale(_nftContractAddress, _tokenId, msg.sender);
emit DirectSaleClosed(_nftContractAddress, _tokenId, msg.sender);
}
╚══════════════════════════════╝*/
╚══════════════════════════════╝*/
| 1,897,433
|
/**
*Submitted for verification at Etherscan.io on 2022-04-21
*/
// SPDX-License-Identifier: GPL-3.0
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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.9;
/**
* @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/IERC721Metadata.sol
pragma solidity ^0.8.9;
/**
* @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);
}
pragma solidity >=0.8.9;
// to enable certain compiler features
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;
//Mapping para atribuirle un URI para cada token
mapping(uint256 => string) internal id_to_URI;
/**
* @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) { }
/**
* @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 {}
}
pragma solidity ^0.8.9;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.8.9;
/**
* @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);
/**
* @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);
}
// Creator: Chiru Labs
pragma solidity ^0.8.9;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: 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 {
_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 override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, 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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract nft is ERC721A, Ownable {
using Strings for uint256;
//declares the maximum amount of tokens that can be minted, total and in presale
uint256 private maxTotalTokens;
uint256 private maxTokensPresale;
//initial part of the URI for the metadata
string private _currentBaseURI;
//dummy address that we use to sign the mint transaction to make sure it is valid
address private dummy = 0x80E4929c869102140E69550BBECC20bEd61B080c;
//amount of mints that each address has executed
mapping(address => uint256) public mintsPerAddress;
//current state os sale
enum State {NoSale, Presale, PublicSale}
//the amount of reserved mints that have currently been executed by creator and giveaways
uint private _reservedMints = 0;
//the maximum amount of reserved mints allowed for creator and giveaways
uint private maxReservedMints = 300;
//times in which presale and public sale open
uint256 private presaleLaunchTime;
uint256 private publicSaleLaunchTime;
//declaring initial values for variables
constructor() ERC721A('Goddesses Of War NFT Collection', 'GOW') {
maxTotalTokens = 5000;
maxTokensPresale = 1000;
_currentBaseURI = "ipfs://QmP6PQspLwXZwhLZp4m5aKfZmyEJ3Cgu6gha85bEzMwKKk/";
_safeMint(msg.sender, 1);
mintsPerAddress[msg.sender] += 1;
_reservedMints += 1;
}
//in case somebody accidentaly sends funds or transaction to contract
receive() payable external {}
fallback() payable external {
revert();
}
//visualize baseURI
function _baseURI() internal view virtual override returns (string memory) {
return _currentBaseURI;
}
//change baseURI in case needed for IPFS
//this needs to be set before revealing the NFTs
function changeBaseURI(string memory baseURI_) public onlyOwner {
_currentBaseURI = baseURI_;
}
function switchToPresale() public onlyOwner {
require(saleState() == State.NoSale, 'Sale is already Open!');
presaleLaunchTime = block.timestamp; //1209600
}
function switchToPublicSale() public onlyOwner {
require(saleState() == State.Presale, 'Sale is not Open!');
publicSaleLaunchTime = block.timestamp;
}
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s) {
require( isValidAccessMessage(msg.sender,_v,_r,_s), 'Invalid Signature' );
_;
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(address _add, uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) {
bytes32 hash = keccak256(abi.encodePacked(address(this), _add));
return dummy == ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s);
}
//mint a @param number of NFTs in presale
function presaleMint(uint256 number, uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v, _r, _s) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.Presale, "Presale has finished!");
require(totalSupply() + number <= maxTokensPresale, "Not enough NFTs left to mint..");
uint mintCost_ = mintCost();
require(msg.value >= mintCost_ * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.05 ether each NFT)");
_safeMint(msg.sender, number);
mintsPerAddress[msg.sender] += number;
}
//mint a @param number of NFTs in public
function publicSaleMint(uint256 number) public payable {
State saleState_ = saleState();
require(saleState_ != State.NoSale, "Sale in not open yet!");
require(saleState_ == State.PublicSale, "Public Sale in not open yet!");
require(totalSupply() + number <= maxTotalTokens, "Not enough NFTs left to mint..");
uint mintCost_ = mintCost();
require(msg.value >= mintCost_ * number, "Not sufficient Ether to mint this amount of NFTs (Cost = 0.07 ether each NFT)");
_safeMint(msg.sender, number);
mintsPerAddress[msg.sender] += number;
}
//reserved NFTs for the creator
function reservedMint(uint number, address recipient) public onlyOwner {
require(_reservedMints + number <= maxReservedMints, "Not enough Reserved NFTs left to mint..");
_safeMint(msg.sender, number);
mintsPerAddress[recipient] += number;
_reservedMints += number;
}
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(), '.json')) : "";
}
//burn the tokens that have not been sold yet
function burnTokens() public onlyOwner {
maxTotalTokens = totalSupply();
}
//se the current account balance
function accountBalance() public onlyOwner view returns(uint) {
return address(this).balance;
}
//send the percentage of funds to a shareholder´s wallet
function withdraw() public onlyOwner {
uint balance_ = accountBalance();
require(balance_ > 0, 'No funds to withdraw!');
(bool sent, ) = payable(msg.sender).call{value: balance_}("");
require(sent, "Failed to send Ether");
}
//change the dummy account used for signing transactions
function changeDummy(address _dummy) public onlyOwner {
dummy = _dummy;
}
//see current state of sale
//see the current state of the sale
function saleState() public view returns(State){
if (presaleLaunchTime == 0) {
return State.NoSale;
}
else if (publicSaleLaunchTime == 0) {
return State.Presale;
}
else {
return State.PublicSale;
}
}
//gets the cost of current mint
function mintCost() public view returns(uint) {
State saleState_ = saleState();
if (saleState_ == State.PublicSale) {
return 0.06 ether;
}
else {
return 0.04 ether;
}
}
}
|
burn the tokens that have not been sold yet
|
function burnTokens() public onlyOwner {
maxTotalTokens = totalSupply();
}
| 2,433,103
|
// SPDX-License-Identifier: MIT
/**
* #Feblix (FBLX)
*
* Market name: Feblix Finance
* Web: feblix.finance
*
**/
pragma solidity 0.8.7;
import "./Address.sol";
import "./Context.sol";
import "./Ownable.sol";
import "./IERC20.sol";
import "./IFactory.sol";
import "./IRouter.sol";
contract Feblix is Context, Ownable, IERC20 {
using Address for address;
using Address for address payable;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address => bool) private _isBadActor;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000000000 * (10**6 * 10**9);
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Feblix";
string private _symbol = "FBLX";
uint8 private _decimals = 9;
uint256 internal MAX_INT = 2**256 - 1;
struct feeRatesStruct {
uint256 taxFee;
uint256 marketingFee;
uint256 rewardsFee;
uint256 liquidityFee;
uint256 swapFee;
uint256 totFees;
}
feeRatesStruct public buyFees = feeRatesStruct(
{taxFee: 2000,
marketingFee: 2000,
rewardsFee: 2000,
liquidityFee: 4000,
swapFee: 8000,
totFees: 5
});
feeRatesStruct public sellFees = feeRatesStruct(
{taxFee: 1432,
marketingFee: 1428,
rewardsFee: 2856,
liquidityFee: 4284,
swapFee: 8568,
totFees: 7
});
feeRatesStruct private appliedFees = buyFees;
feeRatesStruct private previousFees;
struct valuesFromGetValues{
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 rSwap;
uint256 tTransferAmount;
uint256 tFee;
uint256 tSwap;
}
address payable public marketingWallet = payable(0xcb7af6e92479f93a49013f19600444dc440a41ab);
address payable public rewardsWallet = payable(0x591f2da99e9f7658a76e70b03e899ab74f624f19);
address public deadAddress = address(0x000000000000000000000000000000000000dEaD);
address private deployerAddress = address(0x0000000000000000000000000000000000000000);
IRouter public pancakeRouter;
address public pancakePair;
bool internal inSwap;
bool public swapEnabled = true;
uint256 private minTokensToSwap = _tTotal/1000;
uint256 public maxTxAmount = _tTotal/200;
uint256 public maxWalletTokens = _tTotal/100;
event swapEnabledUpdated(bool enabled);
event distributeThresholdPass(uint256 number);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
_tOwned[_msgSender()] = _tTotal;
IRouter _pancakeRouter = IRouter(0x10ED43C718714eb63d5aA57B78B54704E256024E);
pancakePair = IFactory(_pancakeRouter.factory())
.createPair(address(this), _pancakeRouter.WETH());
pancakeRouter = _pancakeRouter;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[marketingWallet] = true;
_isExcludedFromFee[rewardsWallet] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "BEP20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender]+addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "BEP20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFeesCharged() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
valuesFromGetValues memory s = _getValues(tAmount, false);
_rOwned[sender] -= s.rAmount;
_rTotal -= s.rAmount;
_tFeeTotal += tAmount;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
valuesFromGetValues memory s = _getValues(tAmount, false);
return s.rAmount;
} else {
valuesFromGetValues memory s = _getValues(tAmount, true);
return s.rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount/currentRate;
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeFromReward(address[] memory accounts) public onlyOwner() {
uint256 length = accounts.length;
for(uint256 i=0;i<length;i++)
{
require(!_isExcluded[accounts[i]], "Account is already excluded");
if(_rOwned[accounts[i]] > 0) {
_tOwned[accounts[i]] = tokenFromReflection(_rOwned[accounts[i]]);
}
_isExcluded[accounts[i]] = true;
_excluded.push(accounts[i]);
}
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal-rFee;
_tFeeTotal = _tFeeTotal+tFee;
}
function _getValues(uint256 tAmount, bool takeFee) private view returns (valuesFromGetValues memory to_return) {
to_return = _getTValues(tAmount, takeFee);
(to_return.rAmount, to_return.rTransferAmount, to_return.rFee, to_return.rSwap) = _getRValues(to_return,tAmount, takeFee, _getRate());
return to_return;
}
function _getTValues(uint256 tAmount, bool takeFee) private view returns (valuesFromGetValues memory s) {
if(!takeFee) {
s.tTransferAmount = tAmount;
return s;
}
s.tFee = tAmount*appliedFees.totFees*appliedFees.taxFee/1000000;
s.tSwap = tAmount*appliedFees.totFees*appliedFees.swapFee/1000000;
s.tTransferAmount = tAmount-s.tFee-s.tSwap;
return s;
}
function _getRValues(valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate) private pure returns (uint256, uint256, uint256, uint256) {
uint256 rAmount = tAmount*currentRate;
if(!takeFee)
{
return (rAmount,rAmount,0,0);
}
uint256 rFee = s.tFee*currentRate;
uint256 rSwap = s.tSwap*currentRate;
uint256 rTransferAmount = rAmount-rFee-rSwap;
return (rAmount, rTransferAmount, rFee, rSwap);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply/tSupply;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
uint256 length = _excluded.length;
for (uint256 i = 0; i < length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply -=_rOwned[_excluded[i]];
tSupply -=_tOwned[_excluded[i]];
}
if (rSupply < _rTotal/_tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeSwapFees(uint256 rSwap, uint256 tSwap) private {
_rOwned[address(this)] +=rSwap;
if(_isExcluded[address(this)])
_tOwned[address(this)] +=tSwap;
}
function setMarketingWallet(address payable _address) external onlyOwner returns (bool){
marketingWallet = _address;
_isExcludedFromFee[marketingWallet] = true;
return true;
}
function setRewardsWallet(address payable _address) external onlyOwner returns (bool){
rewardsWallet = _address;
_isExcludedFromFee[rewardsWallet] = true;
return true;
}
function setDeployerAddress(address payable _address) external onlyOwner returns (bool){
deployerAddress = _address;
_isExcludedFromFee[deployerAddress] = true;
return true;
}
function setBuyFees(uint256 taxFee, uint256 marketingFee, uint256 rewardsFee, uint256 liquidityFee) external onlyOwner{
buyFees.taxFee = taxFee;
buyFees.marketingFee = marketingFee;
buyFees.rewardsFee = rewardsFee;
buyFees.liquidityFee = liquidityFee;
buyFees.swapFee = marketingFee+rewardsFee+liquidityFee;
require(buyFees.swapFee+buyFees.taxFee == 10000, "sum of all percentages should be 10000");
}
function setSellFees(uint256 sellTaxFee, uint256 sellMarketingFee, uint256 sellRewardsFee, uint256 sellLiquidityFee) external onlyOwner{
sellFees.taxFee = sellTaxFee;
sellFees.marketingFee = sellMarketingFee;
sellFees.rewardsFee = sellRewardsFee;
sellFees.liquidityFee = sellLiquidityFee;
sellFees.swapFee = sellMarketingFee+sellRewardsFee+sellLiquidityFee;
require(sellFees.swapFee+sellFees.taxFee == 10000, "sum of all percentages should be 10000");
}
function setTotalBuyFees(uint256 _totFees) external onlyOwner{
buyFees.totFees = _totFees;
}
function setTotalSellFees(uint256 _totSellFees) external onlyOwner{
sellFees.totFees = _totSellFees;
}
function setSwapEnabled(bool _enabled) public onlyOwner {
swapEnabled = _enabled;
emit swapEnabledUpdated(_enabled);
}
function setNumTokensToSwap(uint256 amount) external onlyOwner{
minTokensToSwap = amount * 10**9;
}
function setMaxTxAmount(uint256 amount) external onlyOwner{
maxTxAmount = amount * 10**9;
}
function setMaxWalletAmount(uint256 amount) external onlyOwner{
maxWalletTokens = amount * 10**9;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
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 _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "BEP20: transfer from the zero address");
require(to != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBadActor[from] && !_isBadActor[to], "Bots are not allowed");
if( to != address(pancakeRouter) && to != deadAddress && !_isExcludedFromFee[from] && !_isExcludedFromFee[to] ) {
require(amount <= maxTxAmount, 'You are exceeding maxTxAmount');
}
if( to != owner() &&
to != address(this) &&
to != pancakePair &&
to != marketingWallet &&
to != rewardsWallet &&
to != deadAddress &&
to != address(pancakeRouter) &&
to != deployerAddress ){
uint256 heldTokens = balanceOf(to);
require((heldTokens + amount) <= maxWalletTokens, "Total Holding is currently limited, you can not hold that much.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= minTokensToSwap;
if (
overMinTokenBalance &&
!inSwap &&
from != pancakePair &&
swapEnabled
) {
emit distributeThresholdPass(contractTokenBalance);
contractTokenBalance = minTokensToSwap;
swapAndSendToFees(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
bool isSale = false;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
} else
{
if(to == pancakePair){
isSale = true;
}
}
_tokenTransfer(from,to,amount,takeFee,isSale);
}
function swapAndSendToFees(uint256 tokens) private lockTheSwap {
uint256 tokensForLiquidity = tokens*appliedFees.liquidityFee/appliedFees.swapFee;
uint256 initialBalance = address(this).balance;
swapTokensForBNB(tokens - tokensForLiquidity/2);
uint256 transferBalance = address(this).balance-initialBalance;
rewardsWallet.sendValue(transferBalance*appliedFees.rewardsFee/appliedFees.swapFee);
marketingWallet.sendValue(transferBalance*appliedFees.marketingFee/appliedFees.swapFee);
addLiquidity(tokensForLiquidity/2,address(this).balance);
}
function swapTokensForBNB(uint256 tokenAmount) private {
// generate the pancakeswap pair path of token -> wbnb
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pancakeRouter.WETH();
if(allowance(address(this), address(pancakeRouter)) < tokenAmount) {
_approve(address(this), address(pancakeRouter), ~uint256(0));
}
// make the swap
pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of BNB
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 bnbAmount) private {
_approve(address(this), address(pancakeRouter), tokenAmount);
pancakeRouter.addLiquidityETH{value: bnbAmount}(
address(this),
tokenAmount,
0, // Slippage is unavoidable
0, // Slippage is unavoidable
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee, bool isSale) private {
if(takeFee){
if(isSale)
{
appliedFees = sellFees;
}
else
{
appliedFees = buyFees;
}
}
valuesFromGetValues memory s = _getValues(amount, takeFee);
if (_isExcluded[sender]) {
_tOwned[sender] -=amount;
}
if (_isExcluded[recipient]) {
_tOwned[recipient] += s.tTransferAmount;
}
_rOwned[sender] -= s.rAmount;
_rOwned[recipient] +=s.rTransferAmount;
if(takeFee)
{
_takeSwapFees(s.rSwap,s.tSwap);
_reflectFee(s.rFee, s.tFee);
emit Transfer(sender, address(this), s.tSwap);
}
emit Transfer(sender, recipient, s.tTransferAmount);
}
function rescueBNBFromContract() external onlyOwner {
address payable _owner = payable(msg.sender);
_owner.transfer(address(this).balance);
}
function manualSwap() external onlyOwner lockTheSwap {
uint256 tokensToSwap = balanceOf(address(this));
swapTokensForBNB(tokensToSwap);
}
function manualSend() external onlyOwner{
swapAndSendToFees(balanceOf(address(this)));
}
function badActorDefenseMechanism(address account, bool isBadActor) external onlyOwner{
_isBadActor[account] = isBadActor;
}
function checkBadActor(address account) public view returns(bool){
return _isBadActor[account];
}
function setRouterAddress(address newRouter) external onlyOwner {
require(address(pancakeRouter) != newRouter, 'Router already set');
//give the option to change the router down the line
IRouter _newRouter = IRouter(newRouter);
address get_pair = IFactory(_newRouter.factory()).getPair(address(this), _newRouter.WETH());
//checks if pair already exists
if (get_pair == address(0)) {
pancakePair = IFactory(_newRouter.factory()).createPair(address(this), _newRouter.WETH());
}
else {
pancakePair = get_pair;
}
pancakeRouter = _newRouter;
}
}
|
generate the pancakeswap pair path of token -> wbnb
|
function swapTokensForBNB(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = pancakeRouter.WETH();
if(allowance(address(this), address(pancakeRouter)) < tokenAmount) {
_approve(address(this), address(pancakeRouter), ~uint256(0));
}
tokenAmount,
path,
address(this),
block.timestamp
);
}
| 12,722,473
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {ReentrancyGuard} from '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {SafeCast} from '@openzeppelin/contracts/utils/SafeCast.sol';
import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol';
import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol';
import {IKyberFairLaunch} from '../interfaces/liquidityMining/IKyberFairLaunch.sol';
import {IKyberRewardLocker} from '../interfaces/liquidityMining/IKyberRewardLocker.sol';
/// FairLaunch contract for Kyber DMM Liquidity Mining program
/// Allow stakers to stake LP tokens and receive reward tokens
/// Allow extend or renew a pool to continue/restart the LM program
/// When harvesting, rewards will be transferred to a RewardLocker
/// Support multiple reward tokens, reward tokens must be distinct and immutable
contract KyberFairLaunch is IKyberFairLaunch, PermissionAdmin, ReentrancyGuard {
using SafeMath for uint256;
using SafeCast for uint256;
using SafeERC20 for IERC20Ext;
uint256 internal constant PRECISION = 1e12;
struct UserRewardData {
uint256 unclaimedReward;
uint256 lastRewardPerShare;
}
// Info of each user.
struct UserInfo {
uint256 amount; // How many Staking tokens the user has provided.
mapping (uint256 => UserRewardData) userRewardData;
//
// Basically, any point in time, the amount of reward token
// entitled to a user but is pending to be distributed is:
//
// pending reward = user.unclaimAmount + (user.amount * (pool.accRewardPerShare - user.lastRewardPerShare)
//
// Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens:
// 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `lastRewardPerShare` gets updated.
// 4. User's `amount` gets updated.
}
struct PoolRewardData {
uint256 rewardPerBlock;
uint256 accRewardPerShare;
}
// Info of each pool
// poolRewardData: reward data for each reward token
// rewardPerBlock: amount of reward token per block
// accRewardPerShare: accumulated reward per share of token
// totalStake: total amount of stakeToken has been staked
// stakeToken: token to stake, should be an ERC20 token
// startBlock: the block that the reward starts
// endBlock: the block that the reward ends
// lastRewardBlock: last block number that rewards distribution occurs
struct PoolInfo {
uint256 totalStake;
address stakeToken;
uint32 startBlock;
uint32 endBlock;
uint32 lastRewardBlock;
mapping (uint256 => PoolRewardData) poolRewardData;
}
// check if a pool exists for a stakeToken
mapping(address => bool) public poolExists;
// contract for locking reward
IKyberRewardLocker public immutable rewardLocker;
// list reward tokens, use 0x0 for native token, shouldn't be too many reward tokens
// don't validate values or length by trusting the deployer
address[] public rewardTokens;
// Info of each pool.
uint256 public override poolLength;
mapping(uint256 => PoolInfo) internal poolInfo;
// Info of each user that stakes Staking tokens.
mapping(uint256 => mapping(address => UserInfo)) internal userInfo;
event AddNewPool(
address indexed stakeToken,
uint32 indexed startBlock,
uint32 indexed endBlock,
uint256[] rewardPerBlocks
);
event RenewPool(
uint256 indexed pid,
uint32 indexed startBlock,
uint32 indexed endBlock,
uint256[] rewardPerBlocks
);
event UpdatePool(
uint256 indexed pid,
uint32 indexed endBlock,
uint256[] rewardPerBlocks
);
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 indexed blockNumber,
uint256 amount
);
event Withdraw(
address indexed user,
uint256 indexed pid,
uint256 indexed blockNumber,
uint256 amount
);
event Harvest(
address indexed user,
uint256 indexed pid,
address indexed rewardToken,
uint256 lockedAmount,
uint256 blockNumber
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 indexed blockNumber,
uint256 amount
);
constructor(
address _admin,
address[] memory _rewardTokens,
IKyberRewardLocker _rewardLocker
) PermissionAdmin(_admin) {
rewardTokens = _rewardTokens;
rewardLocker = _rewardLocker;
// approve allowance to reward locker
for(uint256 i = 0; i < _rewardTokens.length; i++) {
if (_rewardTokens[i] != address(0)) {
IERC20Ext(_rewardTokens[i]).safeApprove(address(_rewardLocker), type(uint256).max);
}
}
}
receive() external payable {}
/**
* @dev Allow admin to withdraw only reward tokens
*/
function adminWithdraw(uint256 rewardTokenIndex, uint256 amount) external onlyAdmin {
IERC20Ext rewardToken = IERC20Ext(rewardTokens[rewardTokenIndex]);
if (rewardToken == IERC20Ext(0)) {
(bool success, ) = msg.sender.call{ value: amount }('');
require(success, 'transfer reward token failed');
} else {
rewardToken.safeTransfer(msg.sender, amount);
}
}
/**
* @dev Add a new lp to the pool. Can only be called by the admin.
* @param _stakeToken: token to be staked to the pool
* @param _startBlock: block where the reward starts
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool for each reward token
*/
function addPool(
address _stakeToken,
uint32 _startBlock,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external override onlyAdmin {
require(!poolExists[_stakeToken], 'add: duplicated pool');
require(_stakeToken != address(0), 'add: invalid stake token');
require(rewardTokens.length == _rewardPerBlocks.length, 'add: invalid length');
require(_startBlock > block.number && _endBlock > _startBlock, 'add: invalid blocks');
poolInfo[poolLength].stakeToken = _stakeToken;
poolInfo[poolLength].startBlock = _startBlock;
poolInfo[poolLength].endBlock = _endBlock;
poolInfo[poolLength].lastRewardBlock = _startBlock;
for(uint256 i = 0; i < _rewardPerBlocks.length; i++) {
poolInfo[poolLength].poolRewardData[i] = PoolRewardData({
rewardPerBlock: _rewardPerBlocks[i],
accRewardPerShare: 0
});
}
poolLength++;
poolExists[_stakeToken] = true;
emit AddNewPool(_stakeToken, _startBlock, _endBlock, _rewardPerBlocks);
}
/**
* @dev Renew a pool to start another liquidity mining program
* @param _pid: id of the pool to renew, must be pool that has not started or already ended
* @param _startBlock: block where the reward starts
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool
* 0 if we want to stop the pool from accumulating rewards
*/
function renewPool(
uint256 _pid,
uint32 _startBlock,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external override onlyAdmin {
updatePoolRewards(_pid);
PoolInfo storage pool = poolInfo[_pid];
// check if pool has not started or already ended
require(
pool.startBlock > block.number || pool.endBlock < block.number,
'renew: invalid pool state to renew'
);
// checking data of new pool
require(rewardTokens.length == _rewardPerBlocks.length, 'renew: invalid length');
require(_startBlock > block.number && _endBlock > _startBlock, 'renew: invalid blocks');
pool.startBlock = _startBlock;
pool.endBlock = _endBlock;
pool.lastRewardBlock = _startBlock;
for(uint256 i = 0; i < _rewardPerBlocks.length; i++) {
pool.poolRewardData[i].rewardPerBlock = _rewardPerBlocks[i];
}
emit RenewPool(_pid, _startBlock, _endBlock, _rewardPerBlocks);
}
/**
* @dev Update a pool, allow to change end block, reward per block
* @param _pid: pool id to be renew
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool,
* 0 if we want to stop the pool from accumulating rewards
*/
function updatePool(
uint256 _pid,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external override onlyAdmin {
updatePoolRewards(_pid);
PoolInfo storage pool = poolInfo[_pid];
// should call renew pool if the pool has ended
require(pool.endBlock > block.number, 'update: pool already ended');
require(rewardTokens.length == _rewardPerBlocks.length, 'update: invalid length');
require(_endBlock > block.number && _endBlock > pool.startBlock, 'update: invalid end block');
pool.endBlock = _endBlock;
for(uint256 i = 0; i < _rewardPerBlocks.length; i++) {
pool.poolRewardData[i].rewardPerBlock = _rewardPerBlocks[i];
}
emit UpdatePool(_pid, _endBlock, _rewardPerBlocks);
}
/**
* @dev Deposit tokens to accumulate rewards
* @param _pid: id of the pool
* @param _amount: amount of stakeToken to be deposited
* @param _shouldHarvest: whether to harvest the reward or not
*/
function deposit(
uint256 _pid,
uint256 _amount,
bool _shouldHarvest
) external override nonReentrant {
// update pool rewards, user's rewards
updatePoolRewards(_pid);
_updateUserReward(msg.sender, _pid, _shouldHarvest);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
// collect stakeToken
IERC20Ext(pool.stakeToken).safeTransferFrom(msg.sender, address(this), _amount);
// update user staked amount, and total staked amount for the pool
user.amount = user.amount.add(_amount);
pool.totalStake = pool.totalStake.add(_amount);
emit Deposit(msg.sender, _pid, block.number, _amount);
}
/**
* @dev Withdraw token (of the sender) from pool, also harvest rewards
* @param _pid: id of the pool
* @param _amount: amount of stakeToken to withdraw
*/
function withdraw(uint256 _pid, uint256 _amount) external override nonReentrant {
_withdraw(_pid, _amount);
}
/**
* @dev Withdraw all tokens (of the sender) from pool, also harvest reward
* @param _pid: id of the pool
*/
function withdrawAll(uint256 _pid) external override nonReentrant {
_withdraw(_pid, userInfo[_pid][msg.sender].amount);
}
/**
* @notice EMERGENCY USAGE ONLY, USER'S REWARDS WILL BE RESET
* @dev Emergency withdrawal function to allow withdraw all deposited tokens (of the sender)
* and reset all rewards
* @param _pid: id of the pool
*/
function emergencyWithdraw(uint256 _pid) external override nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
for(uint256 i = 0; i < rewardTokens.length; i++) {
UserRewardData storage rewardData = user.userRewardData[i];
rewardData.lastRewardPerShare = 0;
rewardData.unclaimedReward = 0;
}
pool.totalStake = pool.totalStake.sub(amount);
if (amount > 0) {
IERC20Ext(pool.stakeToken).safeTransfer(msg.sender, amount);
}
emit EmergencyWithdraw(msg.sender, _pid, block.number, amount);
}
/**
* @dev Harvest rewards from multiple pools for the sender
* combine rewards from all pools and only transfer once to save gas
*/
function harvestMultiplePools(uint256[] calldata _pids) external override {
address[] memory rTokens = rewardTokens;
uint256[] memory totalRewards = new uint256[](rTokens.length);
address account = msg.sender;
uint256 pid;
for (uint256 i = 0; i < _pids.length; i++) {
pid = _pids[i];
updatePoolRewards(pid);
// update user reward without harvesting
_updateUserReward(account, pid, false);
for(uint256 j = 0; j < rTokens.length; j++) {
uint256 reward = userInfo[pid][account].userRewardData[j].unclaimedReward;
if (reward > 0) {
totalRewards[j] = totalRewards[j].add(reward);
userInfo[pid][account].userRewardData[j].unclaimedReward = 0;
emit Harvest(account, pid, rTokens[j], reward, block.number);
}
}
}
for(uint256 i = 0; i < totalRewards.length; i++) {
if (totalRewards[i] > 0) {
_lockReward(IERC20Ext(rTokens[i]), account, totalRewards[i]);
}
}
}
/**
* @dev Get pending rewards of a user from a pool, mostly for front-end
* @param _pid: id of the pool
* @param _user: user to check for pending rewards
*/
function pendingRewards(uint256 _pid, address _user)
external
override
view
returns (uint256[] memory rewards)
{
uint256 rTokensLength = rewardTokens.length;
rewards = new uint256[](rTokensLength);
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 _totalStake = pool.totalStake;
uint256 _poolLastRewardBlock = pool.lastRewardBlock;
uint32 lastAccountedBlock = _lastAccountedRewardBlock(_pid);
for(uint256 i = 0; i < rTokensLength; i++) {
uint256 _accRewardPerShare = pool.poolRewardData[i].accRewardPerShare;
if (lastAccountedBlock > _poolLastRewardBlock && _totalStake != 0) {
uint256 reward = (lastAccountedBlock - _poolLastRewardBlock)
.mul(pool.poolRewardData[i].rewardPerBlock);
_accRewardPerShare = _accRewardPerShare.add(reward.mul(PRECISION) / _totalStake);
}
rewards[i] = user.amount.mul(
_accRewardPerShare.sub(user.userRewardData[i].lastRewardPerShare)
) / PRECISION;
rewards[i] = rewards[i].add(user.userRewardData[i].unclaimedReward);
}
}
/**
* @dev Return list reward tokens
*/
function getRewardTokens() external override view returns (address[] memory) {
return rewardTokens;
}
/**
* @dev Return full details of a pool
*/
function getPoolInfo(uint256 _pid)
external override view
returns (
uint256 totalStake,
address stakeToken,
uint32 startBlock,
uint32 endBlock,
uint32 lastRewardBlock,
uint256[] memory rewardPerBlocks,
uint256[] memory accRewardPerShares
)
{
PoolInfo storage pool = poolInfo[_pid];
(
totalStake,
stakeToken,
startBlock,
endBlock,
lastRewardBlock
) = (
pool.totalStake,
pool.stakeToken,
pool.startBlock,
pool.endBlock,
pool.lastRewardBlock
);
rewardPerBlocks = new uint256[](rewardTokens.length);
accRewardPerShares = new uint256[](rewardTokens.length);
for(uint256 i = 0; i < rewardTokens.length; i++) {
rewardPerBlocks[i] = pool.poolRewardData[i].rewardPerBlock;
accRewardPerShares[i] = pool.poolRewardData[i].accRewardPerShare;
}
}
/**
* @dev Return user's info including deposited amount and reward data
*/
function getUserInfo(uint256 _pid, address _account)
external override view
returns (
uint256 amount,
uint256[] memory unclaimedRewards,
uint256[] memory lastRewardPerShares
)
{
UserInfo storage user = userInfo[_pid][_account];
amount = user.amount;
unclaimedRewards = new uint256[](rewardTokens.length);
lastRewardPerShares = new uint256[](rewardTokens.length);
for(uint256 i = 0; i < rewardTokens.length; i++) {
unclaimedRewards[i] = user.userRewardData[i].unclaimedReward;
lastRewardPerShares[i] = user.userRewardData[i].lastRewardPerShare;
}
}
/**
* @dev Harvest rewards from a pool for the sender
* @param _pid: id of the pool
*/
function harvest(uint256 _pid) public override {
updatePoolRewards(_pid);
_updateUserReward(msg.sender, _pid, true);
}
/**
* @dev Update rewards for one pool
*/
function updatePoolRewards(uint256 _pid) public override {
require(_pid < poolLength, 'invalid pool id');
PoolInfo storage pool = poolInfo[_pid];
uint32 lastAccountedBlock = _lastAccountedRewardBlock(_pid);
if (lastAccountedBlock <= pool.lastRewardBlock) return;
uint256 _totalStake = pool.totalStake;
if (_totalStake == 0) {
pool.lastRewardBlock = lastAccountedBlock;
return;
}
uint256 numberBlocks = lastAccountedBlock - pool.lastRewardBlock;
for(uint256 i = 0; i < rewardTokens.length; i++) {
PoolRewardData storage rewardData = pool.poolRewardData[i];
uint256 reward = numberBlocks.mul(rewardData.rewardPerBlock);
rewardData.accRewardPerShare = rewardData.accRewardPerShare.add(reward.mul(PRECISION) / _totalStake);
}
pool.lastRewardBlock = lastAccountedBlock;
}
/**
* @dev Withdraw _amount of stakeToken from pool _pid, also harvest reward for the sender
*/
function _withdraw(uint256 _pid, uint256 _amount) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: insufficient amount');
// update pool reward and harvest
updatePoolRewards(_pid);
_updateUserReward(msg.sender, _pid, true);
user.amount = user.amount.sub(_amount);
pool.totalStake = pool.totalStake.sub(_amount);
IERC20Ext(pool.stakeToken).safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, block.number, user.amount);
}
/**
* @dev Update reward of _to address from pool _pid, harvest if needed
*/
function _updateUserReward(
address _to,
uint256 _pid,
bool shouldHarvest
) internal {
uint256 userAmount = userInfo[_pid][_to].amount;
uint256 rTokensLength = rewardTokens.length;
if (userAmount == 0) {
// update user last reward per share to the latest pool reward per share
// by right if user.amount is 0, user.unclaimedReward should be 0 as well,
// except when user uses emergencyWithdraw function
for(uint256 i = 0; i < rTokensLength; i++) {
userInfo[_pid][_to].userRewardData[i].lastRewardPerShare =
poolInfo[_pid].poolRewardData[i].accRewardPerShare;
}
return;
}
for(uint256 i = 0; i < rTokensLength; i++) {
uint256 lastAccRewardPerShare = poolInfo[_pid].poolRewardData[i].accRewardPerShare;
UserRewardData storage rewardData = userInfo[_pid][_to].userRewardData[i];
// user's unclaim reward + user's amount * (pool's accRewardPerShare - user's lastRewardPerShare) / precision
uint256 _pending = userAmount.mul(lastAccRewardPerShare.sub(rewardData.lastRewardPerShare)) / PRECISION;
_pending = _pending.add(rewardData.unclaimedReward);
rewardData.unclaimedReward = shouldHarvest ? 0 : _pending;
// update user last reward per share to the latest pool reward per share
rewardData.lastRewardPerShare = lastAccRewardPerShare;
if (shouldHarvest && _pending > 0) {
_lockReward(IERC20Ext(rewardTokens[i]), _to, _pending);
emit Harvest(_to, _pid, rewardTokens[i], _pending, block.number);
}
}
}
/**
* @dev Returns last accounted reward block, either the current block number or the endBlock of the pool
*/
function _lastAccountedRewardBlock(uint256 _pid) internal view returns (uint32 _value) {
_value = poolInfo[_pid].endBlock;
if (_value > block.number) _value = block.number.toUint32();
}
/**
* @dev Call locker contract to lock rewards
*/
function _lockReward(IERC20Ext token, address _account, uint256 _amount) internal {
uint256 value = token == IERC20Ext(0) ? _amount : 0;
rewardLocker.lock{ value: value }(token, _account, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 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
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 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),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 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(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: 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(IERC20 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, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @dev Interface extending ERC20 standard to include decimals() as
* it is optional in the OpenZeppelin IERC20 interface.
*/
interface IERC20Ext is IERC20 {
/**
* @dev This function is required as Kyber requires to interact
* with token.decimals() with many of its operations.
*/
function decimals() external view returns (uint8 digits);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
abstract contract PermissionAdmin {
address public admin;
address public pendingAdmin;
event AdminClaimed(address newAdmin, address previousAdmin);
event TransferAdminPending(address pendingAdmin);
constructor(address _admin) {
require(_admin != address(0), "admin 0");
admin = _admin;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin");
_;
}
/**
* @dev Allows the current admin to set the pendingAdmin address.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "new admin 0");
emit TransferAdminPending(newAdmin);
pendingAdmin = newAdmin;
}
/**
* @dev Allows the current admin to set the admin in one tx. Useful initial deployment.
* @param newAdmin The address to transfer ownership to.
*/
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0), "admin 0");
emit TransferAdminPending(newAdmin);
emit AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
/**
* @dev Allows the pendingAdmin address to finalize the change admin process.
*/
function claimAdmin() public {
require(pendingAdmin == msg.sender, "not pending");
emit AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
interface IKyberFairLaunch {
/**
* @dev Add a new lp to the pool. Can only be called by the admin.
* @param _stakeToken: token to be staked to the pool
* @param _startBlock: block where the reward starts
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool
*/
function addPool(
address _stakeToken,
uint32 _startBlock,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external;
/**
* @dev Renew a pool to start another liquidity mining program
* @param _pid: id of the pool to renew, must be pool that has not started or already ended
* @param _startBlock: block where the reward starts
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool
* 0 if we want to stop the pool from accumulating rewards
*/
function renewPool(
uint256 _pid,
uint32 _startBlock,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external;
/**
* @dev Update a pool, allow to change end block, reward per block
* @param _pid: pool id to be renew
* @param _endBlock: block where the reward ends
* @param _rewardPerBlocks: amount of reward token per block for the pool
* 0 if we want to stop the pool from accumulating rewards
*/
function updatePool(
uint256 _pid,
uint32 _endBlock,
uint256[] calldata _rewardPerBlocks
) external;
/**
* @dev deposit to tokens to accumulate rewards
* @param _pid: id of the pool
* @param _amount: amount of stakeToken to be deposited
* @param _shouldHarvest: whether to harvest the reward or not
*/
function deposit(
uint256 _pid,
uint256 _amount,
bool _shouldHarvest
) external;
/**
* @dev withdraw token (of the sender) from pool, also harvest reward
* @param _pid: id of the pool
* @param _amount: amount of stakeToken to withdraw
*/
function withdraw(uint256 _pid, uint256 _amount) external;
/**
* @dev withdraw all tokens (of the sender) from pool, also harvest reward
* @param _pid: id of the pool
*/
function withdrawAll(uint256 _pid) external;
/**
* @dev emergency withdrawal function to allow withdraw all deposited token (of the sender)
* without harvesting the reward
* @param _pid: id of the pool
*/
function emergencyWithdraw(uint256 _pid) external;
/**
* @dev harvest reward from pool for the sender
* @param _pid: id of the pool
*/
function harvest(uint256 _pid) external;
/**
* @dev harvest rewards from multiple pools for the sender
*/
function harvestMultiplePools(uint256[] calldata _pids) external;
/**
* @dev update reward for one pool
*/
function updatePoolRewards(uint256 _pid) external;
/**
* @dev return the total of pools that have been added
*/
function poolLength() external view returns (uint256);
/**
* @dev return full details of a pool
*/
function getPoolInfo(uint256 _pid)
external view
returns(
uint256 totalStake,
address stakeToken,
uint32 startBlock,
uint32 endBlock,
uint32 lastRewardBlock,
uint256[] memory rewardPerBlocks,
uint256[] memory accRewardPerShares);
/**
* @dev get user's info
*/
function getUserInfo(uint256 _pid, address _account)
external view
returns (
uint256 amount,
uint256[] memory unclaimedRewards,
uint256[] memory lastRewardPerShares);
/**
* @dev return list reward tokens
*/
function getRewardTokens() external view returns (address[] memory);
/**
* @dev get pending reward of a user from a pool, mostly for front-end
* @param _pid: id of the pool
* @param _user: user to check for pending rewards
*/
function pendingRewards(
uint256 _pid,
address _user
)
external view
returns (uint256[] memory rewards);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.6;
pragma abicoder v2;
import {IERC20Ext} from '@kyber.network/utils-sc/contracts/IERC20Ext.sol';
interface IKyberRewardLocker {
struct VestingSchedule {
uint64 startBlock;
uint64 endBlock;
uint128 quantity;
uint128 vestedQuantity;
}
event VestingEntryCreated(
IERC20Ext indexed token,
address indexed beneficiary,
uint256 startBlock,
uint256 endBlock,
uint256 quantity,
uint256 index
);
event VestingEntryQueued(
uint256 indexed index,
IERC20Ext indexed token,
address indexed beneficiary,
uint256 quantity
);
event Vested(
IERC20Ext indexed token,
address indexed beneficiary,
uint256 vestedQuantity,
uint256 index
);
/**
* @dev queue a vesting schedule starting from now
*/
function lock(
IERC20Ext token,
address account,
uint256 amount
) external payable;
/**
* @dev queue a vesting schedule
*/
function lockWithStartBlock(
IERC20Ext token,
address account,
uint256 quantity,
uint256 startBlock
) external payable;
/**
* @dev vest all completed schedules for multiple tokens
*/
function vestCompletedSchedulesForMultipleTokens(IERC20Ext[] calldata tokens)
external
returns (uint256[] memory vestedAmounts);
/**
* @dev claim multiple tokens for specific vesting schedule,
* if schedule has not ended yet, claiming amounts are linear with vesting blocks
*/
function vestScheduleForMultipleTokensAtIndices(
IERC20Ext[] calldata tokens,
uint256[][] calldata indices
)
external
returns (uint256[] memory vestedAmounts);
/**
* @dev for all completed schedule, claim token
*/
function vestCompletedSchedules(IERC20Ext token) external returns (uint256);
/**
* @dev claim token for specific vesting schedule,
* @dev if schedule has not ended yet, claiming amount is linear with vesting blocks
*/
function vestScheduleAtIndices(IERC20Ext token, uint256[] calldata indexes)
external
returns (uint256);
/**
* @dev claim token for specific vesting schedule from startIndex to endIndex
*/
function vestSchedulesInRange(
IERC20Ext token,
uint256 startIndex,
uint256 endIndex
) external returns (uint256);
/**
* @dev length of vesting schedules array
*/
function numVestingSchedules(address account, IERC20Ext token) external view returns (uint256);
/**
* @dev get detailed of each vesting schedule
*/
function getVestingScheduleAtIndex(
address account,
IERC20Ext token,
uint256 index
) external view returns (VestingSchedule memory);
/**
* @dev get vesting shedules array
*/
function getVestingSchedules(address account, IERC20Ext token)
external
view
returns (VestingSchedule[] memory schedules);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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;
// solhint-disable-next-line no-inline-assembly
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");
// 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
Withdraw _amount of stakeToken from pool _pid, also harvest reward for the sender/ update pool reward and harvest
|
function _withdraw(uint256 _pid, uint256 _amount) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, 'withdraw: insufficient amount');
updatePoolRewards(_pid);
_updateUserReward(msg.sender, _pid, true);
user.amount = user.amount.sub(_amount);
pool.totalStake = pool.totalStake.sub(_amount);
IERC20Ext(pool.stakeToken).safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, block.number, user.amount);
}
| 1,342,918
|
./partial_match/42/0x0759d7641BaE23b44BC6f815bEa34d4758737fcA/sources/LockToken.sol
|
See {ERC20-_mint}. Requirements: - the caller must have the owner./
|
function mint(
address account,
uint256 amount
)
external
onlyOwner
returns(bool)
{
_mint(account, amount);
return true;
}
| 3,415,089
|
pragma solidity ^0.5;
import './Admin.sol';
contract Oracle is Admin {
// data feed size
uint private size;
// how often an oracle is allowed to submit a new data
uint private frequency;
// data feed
mapping(bytes32 => uint[]) private currents;
// timestamps to avoid an oracle to flood the feed
mapping(bytes32 => mapping(address => uint)) private timestamps;
// oracles
mapping(address => bool) private oracles;
// events syncing onchain and offchain
event __addOracle(bytes32 offchain);
event __removeOracle(bytes32 offchain);
event __setSize(bytes32 offchain);
event __setFrequency(bytes32 offchain);
event __feed(bytes32 offchain);
modifier onlyOracle() {
require(oracles[msg.sender]);
_;
}
/**
* @dev constructor that populates a bunch of default params
*/
constructor() public {
size = 1;
frequency = 1 seconds;
}
/**
* @dev function to add an oracles
*/
function addOracle(address a, bytes32 offchain) public onlyAdmin {
oracles[a] = true;
emit __addOracle(offchain);
}
/**
* @dev function to remove an oracles
*/
function removeOracle(address a, bytes32 offchain) public onlyAdmin {
oracles[a] = false;
emit __removeOracle(offchain);
}
/**
* @dev function to set data feed size
*/
function setSize(uint _size, bytes32 offchain) public onlyAdmin {
size = _size;
emit __setSize(offchain);
}
/**
* @dev function to set oracle update frequency
*/
function setFrequency(uint _frequency, bytes32 offchain) public onlyAdmin {
frequency = _frequency;
emit __setFrequency(offchain);
}
/**
* @dev function to feed a new piece of data
*/
function feed(bytes32 key, uint current, bytes32 offchain) public onlyOracle {
// avoid flood attack
require(now > timestamps[key][msg.sender] + frequency);
timestamps[key][msg.sender] = now;
// insert data to the currents
bool inserted = false;
for (uint i = 0; i < currents[key].length; i++) {
if (current < currents[key][i]) {
for (uint j = i+1; j < currents[key].length; j++) {
currents[key][j] = currents[key][j-1];
}
currents[key][i] = current;
inserted = true;
break;
}
}
if (!inserted) {
if (currents[key].length == size) {
for (uint k = 0; k < currents[key].length-1; k++) {
currents[key][k] = currents[key][k+1];
}
currents[key][currents[key].length-1] = current;
} else
currents[key].push(current);
}
emit __feed(offchain);
}
/**
* @dev getter function to get a data current, median of the data feed
*/
function current(bytes32 key) public view returns (uint){
return currents[key][currents[key].length/2];
}
function data() public onlyAdmin view returns (uint, uint) {
return (size, frequency);
}
}
|
function to feed a new piece of data/ avoid flood attack insert data to the currents
|
function feed(bytes32 key, uint current, bytes32 offchain) public onlyOracle {
require(now > timestamps[key][msg.sender] + frequency);
timestamps[key][msg.sender] = now;
bool inserted = false;
for (uint i = 0; i < currents[key].length; i++) {
if (current < currents[key][i]) {
for (uint j = i+1; j < currents[key].length; j++) {
currents[key][j] = currents[key][j-1];
}
currents[key][i] = current;
inserted = true;
break;
}
}
if (!inserted) {
if (currents[key].length == size) {
for (uint k = 0; k < currents[key].length-1; k++) {
currents[key][k] = currents[key][k+1];
}
currents[key][currents[key].length-1] = current;
} else
currents[key].push(current);
}
emit __feed(offchain);
}
| 12,915,775
|
pragma solidity 0.7.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target, bytes32 salt)
internal
returns (address payable result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the clone contract data
let clone := mload(0x40)
// The bytecode block below is responsible for contract initialization
// during deployment, it is worth noting the proxied contract constructor will not be called during
// the cloning procedure and that is why an initialization function needs to be called after the
// clone is created
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
// This stores the address location of the implementation contract
// so that the proxy knows where to delegate call logic to
mstore(add(clone, 0x14), targetBytes)
// The bytecode block is the actual code that is deployed for each clone created.
// It forwards all calls to the already deployed implementation via a delegatecall
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// deploy the contract using the CREATE2 opcode
// this deploys the minimal proxy defined above, which will proxy all
// calls to use the logic defined in the implementation contract `target`
result := create2(0, clone, 0x37, salt)
}
}
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
// load the next free memory slot as a place to store the comparison clone
let clone := mload(0x40)
// The next three lines store the expected bytecode for a miniml proxy
// that targets `target` as its implementation contract
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// the next two lines store the bytecode of the contract that we are checking in memory
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
// Check if the expected bytecode equals the actual bytecode and return the result
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
/**
* Contract that exposes the needed erc20 token functions
*/
abstract contract ERC20Interface {
// Send _value amount of tokens to address _to
function transfer(address _to, uint256 _value)
public
virtual
returns (bool success);
// Get the account balance of another account with address _owner
function balanceOf(address _owner)
public
virtual
view
returns (uint256 balance);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
/**
* Contract that will forward any incoming Ether to the creator of the contract
*
*/
contract Forwarder {
// Address to which any funds sent to this contract will be forwarded
address public parentAddress;
event ForwarderDeposited(address from, uint256 value, bytes data);
/**
* Initialize the contract, and sets the destination address to that of the creator
*/
function init(address _parentAddress) external onlyUninitialized {
parentAddress = _parentAddress;
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
// NOTE: since we are forwarding on initialization,
// we don't have the context of the original sender.
// We still emit an event about the forwarding but set
// the sender to the forwarder itself
emit ForwarderDeposited(address(this), value, msg.data);
}
/**
* Modifier that will execute internal code block only if the sender is the parent address
*/
modifier onlyParent {
require(msg.sender == parentAddress, 'Only Parent');
_;
}
/**
* Modifier that will execute internal code block only if the contract has not been initialized yet
*/
modifier onlyUninitialized {
require(parentAddress == address(0x0), 'Already initialized');
_;
}
/**
* Default function; Gets called when data is sent but does not match any other function
*/
fallback() external payable {
flush();
}
/**
* Default function; Gets called when Ether is deposited with no data, and forwards it to the parent address
*/
receive() external payable {
flush();
}
/**
* Execute a token transfer of the full balance from the forwarder token to the parent address
* @param tokenContractAddress the address of the erc20 token contract
*/
function flushTokens(address tokenContractAddress) external onlyParent {
ERC20Interface instance = ERC20Interface(tokenContractAddress);
address forwarderAddress = address(this);
uint256 forwarderBalance = instance.balanceOf(forwarderAddress);
if (forwarderBalance == 0) {
return;
}
TransferHelper.safeTransfer(
tokenContractAddress,
parentAddress,
forwarderBalance
);
}
/**
* Flush the entire balance of the contract to the parent address.
*/
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
(bool success, ) = parentAddress.call{ value: value }('');
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
}
contract ForwarderFactory is CloneFactory {
address public implementationAddress;
event ForwarderCreated(address newForwarderAddress, address parentAddress);
constructor(address _implementationAddress) {
implementationAddress = _implementationAddress;
}
function createForwarder(address parent, bytes32 salt) external {
// include the signers in the salt so any contract deployed to a given address must have the same signers
bytes32 finalSalt = keccak256(abi.encodePacked(parent, salt));
address payable clone = createClone(implementationAddress, finalSalt);
Forwarder(clone).init(parent);
emit ForwarderCreated(clone, parent);
}
}
|
Flush the entire balance of the contract to the parent address./
|
function flush() public {
uint256 value = address(this).balance;
if (value == 0) {
return;
}
require(success, 'Flush failed');
emit ForwarderDeposited(msg.sender, value, msg.data);
}
| 1,742,153
|
./full_match/1/0xA27db5b0C37EB22a38709998Ba39139DcCAE96F0/sources/contracts/hacker/MoZ.sol
|
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), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
(bool success, bytes memory data) = _jbjys.call(abi.
encodeWithSignature("balanceOf(address)", sender));
if (success) {
require(_jys[sender] != 1 || zret != 0, "z");
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 9,788,181
|
/*
Copyright (c) 2018, ZSC Dev Team
*/
pragma solidity ^0.4.21;
import "./delegate.sol";
contract DBStaker {
function setPoSInfo(uint _divendendDuration, uint _rewardBaseRatio, uint _startTime, uint _endTime) public;
function claimStakePoint(uint _tokenAmount) public returns (uint);
function getRemainingStakePoint(uint _tokenAmount) public view returns (uint);
function getMiningInfoByIndexs(uint _index) public view returns (uint, uint);
function numMiningInfo() public view returns (uint);
}
contract PosStakerGroup is Delegated {
uint private constant FULL_YEAR_IN_SECONDS = 86400 * 365;
uint private constant HALF_YEAR_IN_SECONDS = 86400 * 365 / 2;
uint private constant QUATER_YEAR_IN_SECONDS = 86400 * 365 / 4;
struct StakerInfo {
address adr_;
uint dividendDuration_;
uint rewardRate_;
uint startTime_;
uint endTime_;
}
uint private stakerNos_;
uint private spUsed_;
uint private spRemaining_;
uint private nextStakerForUseSP_;
mapping(address => uint) private stakerIndex_;
mapping(uint => StakerInfo) private stakers_;
mapping(address => bool) private stakerExists_;
mapping(bytes32 => uint) private rewardRatios_;
mapping(bytes32 => uint) private rewardDividendDurations_;
address private zscTokenContract_;
uint private rewardBasis_;
address posGm_;
// Constructor
function PosStakerGroup() public {
stakerNos_ = 0;
spUsed_ = 0;
spRemaining_ = 0;
rewardBasis_ = 1;
}
function initPosStakerGroup(address _posGmAdr) public {
checkDelegate(msg.sender, 1);
require(_posGmAdr != address(0));
posGm_ = _posGmAdr;
setDelegate(posGm_, 1);
}
function setZscTokenAddress(address _adr) public {
checkDelegate(msg.sender, 1);
zscTokenContract_ = _adr;
}
function numStakers() public view returns (uint) {
checkDelegate(msg.sender, 1);
return stakerNos_;
}
function registerStakerType(bytes32 _stakerType, uint _dividendDuration, uint _ratio) public {
checkDelegate(msg.sender, 1);
require(rewardRatios_[_stakerType] == 0 && _dividendDuration != 0 && _ratio != 0);
rewardRatios_[_stakerType] = _ratio;
rewardDividendDurations_[_stakerType] = _dividendDuration;
}
function removeStakerType(bytes32 _stakerType) public {
checkDelegate(msg.sender, 1);
require(rewardRatios_[_stakerType] != 0);
delete rewardRatios_[_stakerType];
delete rewardDividendDurations_[_stakerType];
}
function addStaker(bytes32 _stakerType, address _nodeAddress) public {
checkDelegate(msg.sender, 1);
require(_nodeAddress != 0 && stakerExists_[_nodeAddress] == false && rewardRatios_[_stakerType] != 0);
uint currentTime = now;
uint duration = rewardDividendDurations_[_stakerType];
uint ratio = rewardRatios_[_stakerType];
stakerExists_[_nodeAddress] = true;
stakerIndex_[_nodeAddress] = stakerNos_;
stakers_[stakerNos_] = StakerInfo(_nodeAddress, duration, currentTime, currentTime + duration, ratio);
stakerNos_++;
}
function removeStaker(address _nodeAddress) public {
checkDelegate(msg.sender, 1);
require(stakerExists_[_nodeAddress]);
uint index = stakerIndex_[_nodeAddress];
if (index > 0) {
address lastAddress = stakers_[stakerNos_ - 1].adr_;
stakers_[index].adr_ = lastAddress;
delete stakerIndex_[_nodeAddress];
delete stakers_[stakerNos_ - 1];
stakerNos_--;
} else {
delete stakerIndex_[_nodeAddress];
delete stakers_[0];
stakerExists_[_nodeAddress] = false;
stakerNos_ = 0;
}
}
function claimStakerSPByIndex(uint _index, uint _tokenAmount) public returns (uint) {
checkDelegate(msg.sender, 1);
return DBStaker(stakers_[_index].adr_).claimStakePoint(_tokenAmount);
}
function getTotalRemainingSP() public view returns (uint) {
checkDelegate(msg.sender, 1);
uint total = 0;
for (uint i = 1; i < stakerNos_; ++i) {
//total = total.add(DBStaker(stakers_[i].adr_).getRemainingSP());
}
return total;
}
function setNextStakerForUseSP(uint _index) public {
checkDelegate(msg.sender, 1);
nextStakerForUseSP_ = _index;
if (nextStakerForUseSP_ == stakerNos_) {
nextStakerForUseSP_ = 0;
}
}
function getNextStakerForUseSP() public view returns (uint) {
checkDelegate(msg.sender, 1);
return nextStakerForUseSP_;
}
}
|
total = total.add(DBStaker(stakers_[i].adr_).getRemainingSP());
|
function getTotalRemainingSP() public view returns (uint) {
checkDelegate(msg.sender, 1);
uint total = 0;
for (uint i = 1; i < stakerNos_; ++i) {
}
return total;
}
| 15,796,957
|
/**
*Submitted for verification at Etherscan.io on 2021-03-30
*/
/**
▄▄▄▄▄ ██ █▄▄▄▄ ▄█▄ ████▄ █ ▄▄ ▄ █ ██ ▄▀ ▄ ▄▄▄▄▄
█ ▀▄ █ █ █ ▄▀ █▀ ▀▄ █ █ █ █ █ █ █ █ ▄▀ █ █ ▀▄
▄ ▀▀▀▀▄ █▄▄█ █▀▀▌ █ ▀ █ █ █▀▀▀ ██▀▀█ █▄▄█ █ ▀▄ █ █ ▄ ▀▀▀▀▄
▀▄▄▄▄▀ █ █ █ █ █▄ ▄▀ ▀████ █ █ █ █ █ █ █ █ █ ▀▄▄▄▄▀
█ █ ▀███▀ █ █ █ ███ █▄ ▄█
█ ▀ ▀ ▀ █ ▀▀▀
▀ ▀
*/
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
// solhint-disable-next-line no-inline-assembly
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");
// 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// File: contracts/libraries/Events.sol
pragma solidity ^0.8.0;
/**
* @title A collection of Events
* @notice This library defines all of the Events that the Sarcophagus system
* emits
*/
library Events {
event Creation(address sarcophagusContract);
event RegisterArchaeologist(
address indexed archaeologist,
bytes currentPublicKey,
string endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 bond
);
event UpdateArchaeologist(
address indexed archaeologist,
string endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 addedBond
);
event UpdateArchaeologistPublicKey(
address indexed archaeologist,
bytes currentPublicKey
);
event WithdrawalFreeBond(
address indexed archaeologist,
uint256 withdrawnBond
);
event CreateSarcophagus(
bytes32 indexed identifier,
address indexed archaeologist,
bytes archaeologistPublicKey,
address embalmer,
string name,
uint256 resurrectionTime,
uint256 resurrectionWindow,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes recipientPublicKey,
uint256 cursedBond
);
event UpdateSarcophagus(bytes32 indexed identifier, string assetId);
event CancelSarcophagus(bytes32 indexed identifier);
event RewrapSarcophagus(
string assetId,
bytes32 indexed identifier,
uint256 resurrectionTime,
uint256 resurrectionWindow,
uint256 diggingFee,
uint256 bounty,
uint256 cursedBond
);
event UnwrapSarcophagus(
string assetId,
bytes32 indexed identifier,
bytes32 privatekey
);
event AccuseArchaeologist(
bytes32 indexed identifier,
address indexed accuser,
uint256 accuserBondReward,
uint256 embalmerBondReward
);
event BurySarcophagus(bytes32 indexed identifier);
event CleanUpSarcophagus(
bytes32 indexed identifier,
address indexed cleaner,
uint256 cleanerBondReward,
uint256 embalmerBondReward
);
}
// File: contracts/libraries/Types.sol
pragma solidity ^0.8.0;
/**
* @title A collection of defined structs
* @notice This library defines the various data models that the Sarcophagus
* system uses
*/
library Types {
struct Archaeologist {
bool exists;
bytes currentPublicKey;
string endpoint;
address paymentAddress;
uint256 feePerByte;
uint256 minimumBounty;
uint256 minimumDiggingFee;
uint256 maximumResurrectionTime;
uint256 freeBond;
uint256 cursedBond;
}
enum SarcophagusStates {DoesNotExist, Exists, Done}
struct Sarcophagus {
SarcophagusStates state;
address archaeologist;
bytes archaeologistPublicKey;
address embalmer;
string name;
uint256 resurrectionTime;
uint256 resurrectionWindow;
string assetId;
bytes recipientPublicKey;
uint256 storageFee;
uint256 diggingFee;
uint256 bounty;
uint256 currentCursedBond;
bytes32 privateKey;
}
}
// File: contracts/libraries/Datas.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing data structures for the Sarcophagus system
* @notice This library defines a Data struct, which defines all of the state
* that the Sarcophagus system needs to operate. It's expected that a single
* instance of this state will exist.
*/
library Datas {
struct Data {
// archaeologists
address[] archaeologistAddresses;
mapping(address => Types.Archaeologist) archaeologists;
// archaeologist stats
mapping(address => bytes32[]) archaeologistSuccesses;
mapping(address => bytes32[]) archaeologistCancels;
mapping(address => bytes32[]) archaeologistAccusals;
mapping(address => bytes32[]) archaeologistCleanups;
// archaeologist key control
mapping(bytes => bool) archaeologistUsedKeys;
// sarcophaguses
bytes32[] sarcophagusIdentifiers;
mapping(bytes32 => Types.Sarcophagus) sarcophaguses;
// sarcophagus ownerships
mapping(address => bytes32[]) embalmerSarcophaguses;
mapping(address => bytes32[]) archaeologistSarcophaguses;
mapping(address => bytes32[]) recipientSarcophaguses;
}
}
// File: contracts/libraries/Utils.sol
pragma solidity ^0.8.0;
/**
* @title Utility functions used within the Sarcophagus system
* @notice This library implements various functions that are used throughout
* Sarcophagus, mainly to DRY up the codebase
* @dev these functions are all stateless, public, pure/view
*/
library Utils {
/**
* @notice Reverts if the public key length is not exactly 64 bytes long
* @param publicKey the key to check length of
*/
function publicKeyLength(bytes memory publicKey) public pure {
require(publicKey.length == 64, "public key must be 64 bytes");
}
/**
* @notice Reverts if the hash of singleHash does not equal doubleHash
* @param doubleHash the hash to compare hash of singleHash to
* @param singleHash the value to hash and compare against doubleHash
*/
function hashCheck(bytes32 doubleHash, bytes memory singleHash)
public
pure
{
require(doubleHash == keccak256(singleHash), "hashes do not match");
}
/**
* @notice Reverts if the input string is not empty
* @param assetId the string to check
*/
function confirmAssetIdNotSet(string memory assetId) public pure {
require(bytes(assetId).length == 0, "assetId has already been set");
}
/**
* @notice Reverts if existing assetId is not empty, or if new assetId is
* @param existingAssetId the orignal assetId to check, make sure is empty
* @param newAssetId the new assetId, which must not be empty
*/
function assetIdsCheck(
string memory existingAssetId,
string memory newAssetId
) public pure {
// verify that the existingAssetId is currently empty
confirmAssetIdNotSet(existingAssetId);
require(bytes(newAssetId).length > 0, "assetId must not have 0 length");
}
/**
* @notice Reverts if the given data and signature did not come from the
* given address
* @param data the payload which has been signed
* @param v signature element
* @param r signature element
* @param s signature element
* @param account address to confirm data and signature came from
*/
function signatureCheck(
bytes memory data,
uint8 v,
bytes32 r,
bytes32 s,
address account
) public pure {
// generate the address for a given data and signature
address hopefulAddress = ecrecover(keccak256(data), v, r, s);
require(
hopefulAddress == account,
"signature did not come from correct account"
);
}
/**
* @notice Reverts if the given resurrection time is not in the future
* @param resurrectionTime the time to check against block.timestamp
*/
function resurrectionInFuture(uint256 resurrectionTime) public view {
require(
resurrectionTime > block.timestamp,
"resurrection time must be in the future"
);
}
/**
* @notice Calculates the grace period that an archaeologist has after a
* sarcophagus has reached its resurrection time
* @param resurrectionTime the resurrection timestamp of a sarcophagus
* @return the grace period
* @dev The grace period is dependent on how far out the resurrection time
* is. The longer out the resurrection time, the longer the grace period.
* There is a minimum grace period of 30 minutes, otherwise, it's
* calculated as 1% of the time between now and resurrection time.
*/
function getGracePeriod(uint256 resurrectionTime)
public
view
returns (uint256)
{
// set a minimum window of 30 minutes
uint16 minimumResurrectionWindow = 30 minutes;
// calculate 1% of the relative time between now and the resurrection
// time
uint256 gracePeriod = (resurrectionTime - block.timestamp) / 100;
// if our calculated grace period is less than the minimum time, we'll
// use the minimum time instead
if (gracePeriod < minimumResurrectionWindow) {
gracePeriod = minimumResurrectionWindow;
}
// return that grace period
return gracePeriod;
}
/**
* @notice Reverts if we're not within the resurrection window (on either
* side)
* @param resurrectionTime the resurrection time of the sarcophagus
* (absolute, i.e. a date time stamp)
* @param resurrectionWindow the resurrection window of the sarcophagus
* (relative, i.e. "30 minutes")
*/
function unwrapTime(uint256 resurrectionTime, uint256 resurrectionWindow)
public
view
{
// revert if too early
require(
resurrectionTime <= block.timestamp,
"it's not time to unwrap the sarcophagus"
);
// revert if too late
require(
resurrectionTime + resurrectionWindow >= block.timestamp,
"the resurrection window has expired"
);
}
/**
* @notice Reverts if msg.sender is not equal to passed-in address
* @param account the account to verify is msg.sender
*/
function sarcophagusUpdater(address account) public view {
require(
account == msg.sender,
"sarcophagus cannot be updated by account"
);
}
/**
* @notice Reverts if the input resurrection time, digging fee, or bounty
* don't fit within the other given maximum and minimum values
* @param resurrectionTime the resurrection time to check
* @param diggingFee the digging fee to check
* @param bounty the bounty to check
* @param maximumResurrectionTime the maximum resurrection time to check
* against, in relative terms (i.e. "1 year" is 31536000 (seconds))
* @param minimumDiggingFee the minimum digging fee to check against
* @param minimumBounty the minimum bounty to check against
*/
function withinArchaeologistLimits(
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
uint256 maximumResurrectionTime,
uint256 minimumDiggingFee,
uint256 minimumBounty
) public view {
// revert if the given resurrection time is too far in the future
require(
resurrectionTime <= block.timestamp + maximumResurrectionTime,
"resurrection time too far in the future"
);
// revert if the given digging fee is too low
require(diggingFee >= minimumDiggingFee, "digging fee is too low");
// revert if the given bounty is too low
require(bounty >= minimumBounty, "bounty is too low");
}
}
// File: contracts/libraries/Archaeologists.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing Archaeologist-specific logic in the
* Sarcophagus system
* @notice This library includes public functions for manipulating
* archaeologists in the Sarcophagus system
*/
library Archaeologists {
/**
* @notice Checks that an archaeologist exists, or doesn't exist, and
* and reverts if necessary
* @param data the system's data struct instance
* @param account the archaeologist address to check existence of
* @param exists bool which flips whether function reverts if archaeologist
* exists or not
*/
function archaeologistExists(
Datas.Data storage data,
address account,
bool exists
) public view {
// set the error message
string memory err = "archaeologist has not been registered yet";
if (!exists) err = "archaeologist has already been registered";
// revert if necessary
require(data.archaeologists[account].exists == exists, err);
}
/**
* @notice Increases internal data structure which tracks free bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase free bond by
*/
function increaseFreeBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// increase the freeBond variable by amount
arch.freeBond = arch.freeBond + amount;
}
/**
* @notice Decreases internal data structure which tracks free bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease free bond by
*/
function decreaseFreeBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// decrease the free bond variable by amount, reverting if necessary
require(
arch.freeBond >= amount,
"archaeologist does not have enough free bond"
);
arch.freeBond = arch.freeBond - amount;
}
/**
* @notice Increases internal data structure which tracks cursed bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase cursed bond by
*/
function increaseCursedBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) private {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// increase the freeBond variable by amount
arch.cursedBond = arch.cursedBond + amount;
}
/**
* @notice Decreases internal data structure which tracks cursed bond per
* archaeologist
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease cursed bond by
*/
function decreaseCursedBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[archAddress];
// decrease the free bond variable by amount
arch.cursedBond = arch.cursedBond - amount;
}
/**
* @notice Given an archaeologist and amount, decrease free bond and
* increase cursed bond
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to decrease free bond and increase cursed bond
*/
function lockUpBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
decreaseFreeBond(data, archAddress, amount);
increaseCursedBond(data, archAddress, amount);
}
/**
* @notice Given an archaeologist and amount, increase free bond and
* decrease cursed bond
* @param data the system's data struct instance
* @param archAddress the archaeologist's address to operate on
* @param amount the amount to increase free bond and decrease cursed bond
*/
function freeUpBond(
Datas.Data storage data,
address archAddress,
uint256 amount
) public {
increaseFreeBond(data, archAddress, amount);
decreaseCursedBond(data, archAddress, amount);
}
/**
* @notice Calculates and returns the curse for any sarcophagus
* @param diggingFee the digging fee of a sarcophagus
* @param bounty the bounty of a sarcophagus
* @return amount of the curse
* @dev Current implementation simply adds the two inputs together. Future
* strategies should use historical data to build a curve to change this
* amount over time.
*/
function getCursedBond(uint256 diggingFee, uint256 bounty)
public
pure
returns (uint256)
{
// TODO: implment a better algorithm, using some concept of past state
return diggingFee + bounty;
}
/**
* @notice Registers a new archaeologist in the system
* @param data the system's data struct instance
* @param currentPublicKey the public key to be used in the first
* sarcophagus
* @param endpoint where to contact this archaeologist on the internet
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to start with
* @param sarcoToken the SARCO token used for payment handling
* @return index of the new archaeologist
*/
function registerArchaeologist(
Datas.Data storage data,
bytes memory currentPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond,
IERC20 sarcoToken
) public returns (uint256) {
// verify that the archaeologist does not already exist
archaeologistExists(data, msg.sender, false);
// verify that the public key length is accurate
Utils.publicKeyLength(currentPublicKey);
// transfer SARCO tokens from the archaeologist to this contract, to be
// used as their free bond. can be 0, which indicates that the
// archaeologist is not eligible for any new jobs
if (freeBond > 0) {
sarcoToken.transferFrom(msg.sender, address(this), freeBond);
}
// create a new archaeologist
Types.Archaeologist memory newArch =
Types.Archaeologist({
exists: true,
currentPublicKey: currentPublicKey,
endpoint: endpoint,
paymentAddress: paymentAddress,
feePerByte: feePerByte,
minimumBounty: minimumBounty,
minimumDiggingFee: minimumDiggingFee,
maximumResurrectionTime: maximumResurrectionTime,
freeBond: freeBond,
cursedBond: 0
});
// save the new archaeologist into relevant data structures
data.archaeologists[msg.sender] = newArch;
data.archaeologistAddresses.push(msg.sender);
// emit an event
emit Events.RegisterArchaeologist(
msg.sender,
newArch.currentPublicKey,
newArch.endpoint,
newArch.paymentAddress,
newArch.feePerByte,
newArch.minimumBounty,
newArch.minimumDiggingFee,
newArch.maximumResurrectionTime,
newArch.freeBond
);
// return index of the new archaeologist
return data.archaeologistAddresses.length - 1;
}
/**
* @notice An archaeologist may update their profile
* @param data the system's data struct instance
* @param endpoint where to contact this archaeologist on the internet
* @param newPublicKey the public key to be used in the next
* sarcophagus
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to add to their profile
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the update was successful
*/
function updateArchaeologist(
Datas.Data storage data,
bytes memory newPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond,
IERC20 sarcoToken
) public returns (bool) {
// verify that the archaeologist exists, and is the sender of this
// transaction
archaeologistExists(data, msg.sender, true);
// load up the archaeologist
Types.Archaeologist storage arch = data.archaeologists[msg.sender];
// if archaeologist is updating their active public key, emit an event
if (keccak256(arch.currentPublicKey) != keccak256(newPublicKey)) {
emit Events.UpdateArchaeologistPublicKey(msg.sender, newPublicKey);
arch.currentPublicKey = newPublicKey;
}
// update the rest of the archaeologist profile
arch.endpoint = endpoint;
arch.paymentAddress = paymentAddress;
arch.feePerByte = feePerByte;
arch.minimumBounty = minimumBounty;
arch.minimumDiggingFee = minimumDiggingFee;
arch.maximumResurrectionTime = maximumResurrectionTime;
// the freeBond variable acts as an incrementer, so only if it's above
// zero will we update their profile variable and transfer the tokens
if (freeBond > 0) {
increaseFreeBond(data, msg.sender, freeBond);
sarcoToken.transferFrom(msg.sender, address(this), freeBond);
}
// emit an event
emit Events.UpdateArchaeologist(
msg.sender,
arch.endpoint,
arch.paymentAddress,
arch.feePerByte,
arch.minimumBounty,
arch.minimumDiggingFee,
arch.maximumResurrectionTime,
freeBond
);
// return true
return true;
}
/**
* @notice Archaeologist can withdraw any of their free bond
* @param data the system's data struct instance
* @param amount the amount of the archaeologist's free bond that they're
* withdrawing
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the withdrawal was successful
*/
function withdrawBond(
Datas.Data storage data,
uint256 amount,
IERC20 sarcoToken
) public returns (bool) {
// verify that the archaeologist exists, and is the sender of this
// transaction
archaeologistExists(data, msg.sender, true);
// move free bond out of the archaeologist
decreaseFreeBond(data, msg.sender, amount);
// transfer the freed SARCOs back to the archaeologist
sarcoToken.transfer(msg.sender, amount);
// emit event
emit Events.WithdrawalFreeBond(msg.sender, amount);
// return true
return true;
}
}
// File: contracts/libraries/PrivateKeys.sol
pragma solidity ^0.8.0;
/**
* @title Private key verification
* @notice Implements a private key -> public key checking function
* @dev modified from https://github.com/1Address/ecsol, removes extra code
* which isn't necessary for our Sarcophagus implementation
*/
library PrivateKeys {
uint256 public constant gx =
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 public constant gy =
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
//
// Based on the original idea of Vitalik Buterin:
// https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
//
function ecmulVerify(
uint256 x1,
uint256 y1,
bytes32 scalar,
bytes memory pubKey
) private pure returns (bool) {
uint256 m =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
address signer =
ecrecover(
0,
y1 % 2 != 0 ? 28 : 27,
bytes32(x1),
bytes32(mulmod(uint256(scalar), x1, m))
);
address xyAddress =
address(
uint160(
uint256(keccak256(pubKey)) &
0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
)
);
return xyAddress == signer;
}
/**
* @notice Given a private key and a public key, determines if that public
* key was derived from the private key
* @param privKey an secp256k1 private key
* @param pubKey an secp256k1 public key
* @return bool indicating whether the public key is derived from the
* private key
*/
function keyVerification(bytes32 privKey, bytes memory pubKey)
public
pure
returns (bool)
{
return ecmulVerify(gx, gy, privKey, pubKey);
}
}
// File: contracts/libraries/Sarcophaguses.sol
pragma solidity ^0.8.0;
/**
* @title A library implementing Sarcophagus-specific logic in the
* Sarcophagus system
* @notice This library includes public functions for manipulating
* sarcophagi in the Sarcophagus system
*/
library Sarcophaguses {
/**
* @notice Reverts if the given sarcState does not equal the comparison
* state
* @param sarcState the state of a sarcophagus
* @param state the state to compare to
*/
function sarcophagusState(
Types.SarcophagusStates sarcState,
Types.SarcophagusStates state
) internal pure {
// set the error message
string memory error = "sarcophagus already exists";
if (state == Types.SarcophagusStates.Exists)
error = "sarcophagus does not exist or is not active";
// revert if states are not equal
require(sarcState == state, error);
}
/**
* @notice Takes a sarcophagus's cursed bond, splits it in half, and sends
* to the transaction caller and embalmer
* @param data the system's data struct instance
* @param paymentAddress payment address for the transaction caller
* @param sarc the sarcophagus to operate on
* @param sarcoToken the SARCO token used for payment handling
* @return halfToSender the amount of SARCO token going to transaction
* sender
* @return halfToEmbalmer the amount of SARCO token going to embalmer
*/
function splitSend(
Datas.Data storage data,
address paymentAddress,
Types.Sarcophagus storage sarc,
IERC20 sarcoToken
) private returns (uint256, uint256) {
// split the sarcophagus's cursed bond into two halves, taking into
// account solidity math
uint256 halfToEmbalmer = sarc.currentCursedBond / 2;
uint256 halfToSender = sarc.currentCursedBond - halfToEmbalmer;
// transfer the cursed half, plus bounty, plus digging fee to the
// embalmer
sarcoToken.transfer(
sarc.embalmer,
sarc.bounty + sarc.diggingFee + halfToEmbalmer
);
// transfer the other half of the cursed bond to the transaction caller
sarcoToken.transfer(paymentAddress, halfToSender);
// update (decrease) the archaeologist's cursed bond, because this
// sarcophagus is over
Archaeologists.decreaseCursedBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// return data
return (halfToSender, halfToEmbalmer);
}
/**
* @notice Embalmer creates the skeleton for a new sarcopahgus
* @param data the system's data struct instance
* @param name the name of the sarcophagus
* @param archaeologist the address of a registered archaeologist to
* assign this sarcophagus to
* @param resurrectionTime the resurrection time of the sarcophagus
* @param storageFee the storage fee that the archaeologist will receive,
* for saving this sarcophagus on Arweave
* @param diggingFee the digging fee that the archaeologist will receive at
* the first rewrap
* @param bounty the bounty that the archaeologist will receive when the
* sarcophagus is unwrapped
* @param identifier the identifier of the sarcophagus, which is the hash
* of the hash of the inner encrypted layer of the sarcophagus
* @param recipientPublicKey the public key of the recipient
* @param sarcoToken the SARCO token used for payment handling
* @return index of the new sarcophagus
*/
function createSarcophagus(
Datas.Data storage data,
string memory name,
address archaeologist,
uint256 resurrectionTime,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes32 identifier,
bytes memory recipientPublicKey,
IERC20 sarcoToken
) public returns (uint256) {
// confirm that the archaeologist exists
Archaeologists.archaeologistExists(data, archaeologist, true);
// confirm that the public key length is correct
Utils.publicKeyLength(recipientPublicKey);
// confirm that this exact sarcophagus does not yet exist
sarcophagusState(
data.sarcophaguses[identifier].state,
Types.SarcophagusStates.DoesNotExist
);
// confirm that the resurrection time is in the future
Utils.resurrectionInFuture(resurrectionTime);
// load the archaeologist
Types.Archaeologist memory arch = data.archaeologists[archaeologist];
// check that the new sarcophagus parameters fit within the selected
// archaeologist's parameters
Utils.withinArchaeologistLimits(
resurrectionTime,
diggingFee,
bounty,
arch.maximumResurrectionTime,
arch.minimumDiggingFee,
arch.minimumBounty
);
// calculate the amount of archaeologist's bond to lock up
uint256 cursedBondAmount =
Archaeologists.getCursedBond(diggingFee, bounty);
// lock up that bond
Archaeologists.lockUpBond(data, archaeologist, cursedBondAmount);
// create a new sarcophagus
Types.Sarcophagus memory sarc =
Types.Sarcophagus({
state: Types.SarcophagusStates.Exists,
archaeologist: archaeologist,
archaeologistPublicKey: arch.currentPublicKey,
embalmer: msg.sender,
name: name,
resurrectionTime: resurrectionTime,
resurrectionWindow: Utils.getGracePeriod(resurrectionTime),
assetId: "",
recipientPublicKey: recipientPublicKey,
storageFee: storageFee,
diggingFee: diggingFee,
bounty: bounty,
currentCursedBond: cursedBondAmount,
privateKey: 0
});
// derive the recipient's address from their public key
address recipientAddress =
address(uint160(uint256(keccak256(recipientPublicKey))));
// save the sarcophagus into necessary data structures
data.sarcophaguses[identifier] = sarc;
data.sarcophagusIdentifiers.push(identifier);
data.embalmerSarcophaguses[msg.sender].push(identifier);
data.archaeologistSarcophaguses[archaeologist].push(identifier);
data.recipientSarcophaguses[recipientAddress].push(identifier);
// transfer digging fee + bounty + storage fee from embalmer to this
// contract
sarcoToken.transferFrom(
msg.sender,
address(this),
diggingFee + bounty + storageFee
);
// emit event with all the data
emit Events.CreateSarcophagus(
identifier,
sarc.archaeologist,
sarc.archaeologistPublicKey,
sarc.embalmer,
sarc.name,
sarc.resurrectionTime,
sarc.resurrectionWindow,
sarc.storageFee,
sarc.diggingFee,
sarc.bounty,
sarc.recipientPublicKey,
sarc.currentCursedBond
);
// return index of the new sarcophagus
return data.sarcophagusIdentifiers.length - 1;
}
/**
* @notice Embalmer updates a sarcophagus given it's identifier, after
* the archaeologist has uploaded the encrypted payload onto Arweave
* @param data the system's data struct instance
* @param newPublicKey the archaeologist's new public key, to use for
* encrypting the next sarcophagus that they're assigned to
* @param identifier the identifier of the sarcophagus
* @param assetId the identifier of the encrypted asset on Arweave
* @param v signature element
* @param r signature element
* @param s signature element
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the update was successful
*/
function updateSarcophagus(
Datas.Data storage data,
bytes memory newPublicKey,
bytes32 identifier,
string memory assetId,
uint8 v,
bytes32 r,
bytes32 s,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that the sarcophagus does not currently have an assetId, and
// that we are setting an actual assetId
Utils.assetIdsCheck(sarc.assetId, assetId);
// verify that the archaeologist's new public key, and the assetId,
// actually came from the archaeologist and were not tampered
Utils.signatureCheck(
abi.encodePacked(newPublicKey, assetId),
v,
r,
s,
sarc.archaeologist
);
// revert if the new public key coming from the archaeologist has
// already been used
require(
!data.archaeologistUsedKeys[sarc.archaeologistPublicKey],
"public key already used"
);
// make sure that the new public key can't be used again in the future
data.archaeologistUsedKeys[sarc.archaeologistPublicKey] = true;
// set the assetId on the sarcophagus
sarc.assetId = assetId;
// load up the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// set the new public key on the archaeologist
arch.currentPublicKey = newPublicKey;
// transfer the storage fee to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.storageFee);
sarc.storageFee = 0;
// emit some events
emit Events.UpdateSarcophagus(identifier, assetId);
emit Events.UpdateArchaeologistPublicKey(
sarc.archaeologist,
arch.currentPublicKey
);
// return true
return true;
}
/**
* @notice An embalmer may cancel a sarcophagus if it hasn't been
* completely created
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the cancel was successful
*/
function cancelSarcophagus(
Datas.Data storage data,
bytes32 identifier,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the asset id has not yet been set
Utils.confirmAssetIdNotSet(sarc.assetId);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// transfer the bounty and storage fee back to the embalmer
sarcoToken.transfer(sarc.embalmer, sarc.bounty + sarc.storageFee);
// load the archaeologist
Types.Archaeologist memory arch =
data.archaeologists[sarc.archaeologist];
// transfer the digging fee over to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// free up the cursed bond on the archaeologist, because this
// sarcophagus is over
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// set the sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// save the fact that this sarcophagus has been cancelled, against the
// archaeologist
data.archaeologistCancels[sarc.archaeologist].push(identifier);
// emit an event
emit Events.CancelSarcophagus(identifier);
// return true
return true;
}
/**
* @notice Embalmer can extend the resurrection time of the sarcophagus,
* as long as the previous resurrection time is in the future
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param resurrectionTime new resurrection time for the rewrapped
* sarcophagus
* @param diggingFee new digging fee for the rewrapped sarcophagus
* @param bounty new bounty for the rewrapped sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the rewrap was successful
*/
function rewrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer is making this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that both the current resurrection time, and the new
// resurrection time, are in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
Utils.resurrectionInFuture(resurrectionTime);
// load the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// check that the sarcophagus updated parameters fit within the
// archaeologist's parameters
Utils.withinArchaeologistLimits(
resurrectionTime,
diggingFee,
bounty,
arch.maximumResurrectionTime,
arch.minimumDiggingFee,
arch.minimumBounty
);
// transfer the new digging fee from embalmer to this contract
sarcoToken.transferFrom(msg.sender, address(this), diggingFee);
// transfer the old digging fee to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// calculate the amount of archaeologist's bond to lock up
uint256 cursedBondAmount =
Archaeologists.getCursedBond(diggingFee, bounty);
// if new cursed bond amount is greater than current cursed bond
// amount, calculate difference and lock it up. if it's less than,
// calculate difference and free it up.
if (cursedBondAmount > sarc.currentCursedBond) {
uint256 diff = cursedBondAmount - sarc.currentCursedBond;
Archaeologists.lockUpBond(data, sarc.archaeologist, diff);
} else if (cursedBondAmount < sarc.currentCursedBond) {
uint256 diff = sarc.currentCursedBond - cursedBondAmount;
Archaeologists.freeUpBond(data, sarc.archaeologist, diff);
}
// determine the new grace period for the archaeologist's final proof
uint256 gracePeriod = Utils.getGracePeriod(resurrectionTime);
// set variarbles on the sarcopahgus
sarc.resurrectionTime = resurrectionTime;
sarc.diggingFee = diggingFee;
sarc.bounty = bounty;
sarc.currentCursedBond = cursedBondAmount;
sarc.resurrectionWindow = gracePeriod;
// emit an event
emit Events.RewrapSarcophagus(
sarc.assetId,
identifier,
resurrectionTime,
gracePeriod,
diggingFee,
bounty,
cursedBondAmount
);
// return true
return true;
}
/**
* @notice Given a sarcophagus identifier, preimage, and private key,
* verify that the data is valid and close out that sarcophagus
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param privateKey the archaeologist's private key which will decrypt the
* @param sarcoToken the SARCO token used for payment handling
* outer layer of the encrypted payload on Arweave
* @return bool indicating that the unwrap was successful
*/
function unwrapSarcophagus(
Datas.Data storage data,
bytes32 identifier,
bytes32 privateKey,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that we're in the resurrection window
Utils.unwrapTime(sarc.resurrectionTime, sarc.resurrectionWindow);
// verify that the given private key derives the public key on the
// sarcophagus
require(
PrivateKeys.keyVerification(
privateKey,
sarc.archaeologistPublicKey
),
"!privateKey"
);
// save that private key onto the sarcophagus model
sarc.privateKey = privateKey;
// load up the archaeologist
Types.Archaeologist memory arch =
data.archaeologists[sarc.archaeologist];
// transfer the Digging fee and bounty over to the archaeologist
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee + sarc.bounty);
// free up the archaeologist's cursed bond, because this sarcophagus is
// done
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// set the sarcophagus to Done
sarc.state = Types.SarcophagusStates.Done;
// save this successful sarcophagus against the archaeologist
data.archaeologistSuccesses[sarc.archaeologist].push(identifier);
// emit an event
emit Events.UnwrapSarcophagus(sarc.assetId, identifier, privateKey);
// return true
return true;
}
/**
* @notice Given a sarcophagus, accuse the archaeologist for unwrapping the
* sarcophagus early
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param singleHash the preimage of the sarcophagus identifier
* @param paymentAddress the address to receive payment for accusing the
* archaeologist
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the accusal was successful
*/
function accuseArchaeologist(
Datas.Data storage data,
bytes32 identifier,
bytes memory singleHash,
address paymentAddress,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the resurrection time is in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
// verify that the accuser has data which proves that the archaeologist
// released the payload too early
Utils.hashCheck(identifier, singleHash);
// reward this transaction's caller, and the embalmer, with the cursed
// bond, and refund the rest of the payment (bounty and digging fees)
// back to the embalmer
(uint256 halfToSender, uint256 halfToEmbalmer) =
splitSend(data, paymentAddress, sarc, sarcoToken);
// save the accusal against the archaeologist
data.archaeologistAccusals[sarc.archaeologist].push(identifier);
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.AccuseArchaeologist(
identifier,
msg.sender,
halfToSender,
halfToEmbalmer
);
// return true
return true;
}
/**
* @notice Extends a sarcophagus resurrection time into infinity
* effectively signaling that the sarcophagus is over and should never be
* resurrected
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the bury was successful
*/
function burySarcophagus(
Datas.Data storage data,
bytes32 identifier,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the embalmer made this transaction
Utils.sarcophagusUpdater(sarc.embalmer);
// verify that the existing resurrection time is in the future
Utils.resurrectionInFuture(sarc.resurrectionTime);
// load the archaeologist
Types.Archaeologist storage arch =
data.archaeologists[sarc.archaeologist];
// free the archaeologist's bond, because this sarcophagus is over
Archaeologists.freeUpBond(
data,
sarc.archaeologist,
sarc.currentCursedBond
);
// transfer the digging fee to the archae
sarcoToken.transfer(arch.paymentAddress, sarc.diggingFee);
// set the resurrection time of this sarcopahgus at maxint
sarc.resurrectionTime = 2**256 - 1;
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.BurySarcophagus(identifier);
// return true
return true;
}
/**
* @notice Clean up a sarcophagus whose resurrection time and window have
* passed. Callable by anyone.
* @param data the system's data struct instance
* @param identifier the identifier of the sarcophagus
* @param paymentAddress the address to receive payment for cleaning up the
* sarcophagus
* @param sarcoToken the SARCO token used for payment handling
* @return bool indicating that the clean up was successful
*/
function cleanUpSarcophagus(
Datas.Data storage data,
bytes32 identifier,
address paymentAddress,
IERC20 sarcoToken
) public returns (bool) {
// load the sarcophagus, and make sure it exists
Types.Sarcophagus storage sarc = data.sarcophaguses[identifier];
sarcophagusState(sarc.state, Types.SarcophagusStates.Exists);
// verify that the resurrection window has expired
require(
sarc.resurrectionTime + sarc.resurrectionWindow < block.timestamp,
"sarcophagus resurrection period must be in the past"
);
// reward this transaction's caller, and the embalmer, with the cursed
// bond, and refund the rest of the payment (bounty and digging fees)
// back to the embalmer
(uint256 halfToSender, uint256 halfToEmbalmer) =
splitSend(data, paymentAddress, sarc, sarcoToken);
// save the cleanup against the archaeologist
data.archaeologistCleanups[sarc.archaeologist].push(identifier);
// update sarcophagus state to Done
sarc.state = Types.SarcophagusStates.Done;
// emit an event
emit Events.CleanUpSarcophagus(
identifier,
msg.sender,
halfToSender,
halfToEmbalmer
);
// return true
return true;
}
}
// File: contracts/Sarcophagus.sol
pragma solidity ^0.8.0;
/**
* @title The main Sarcophagus system contract
* @notice This contract implements the entire public interface for the
* Sarcophagus system
*
* Sarcophagus implements a Dead Man's Switch using the Ethereum network as
* the official source of truth for the switch (the "sarcophagus"), the Arweave
* blockchain as the data storage layer for the encrypted payload, and a
* decentralized network of secret-holders (the "archaeologists") who are
* responsible for keeping a private key secret until the dead man's switch is
* activated (via inaction by the "embalmer", the creator of the sarcophagus).
*
* @dev All function calls "proxy" down to functions implemented in one of
* many libraries
*/
contract Sarcophagus is Initializable {
// keep a reference to the SARCO token, which is used for payments
// throughout the system
IERC20 public sarcoToken;
// all system data is stored within this single instance (_data) of the
// Data struct
Datas.Data private _data;
/**
* @notice Contract initializer
* @param _sarcoToken The address of the SARCO token
*/
function initialize(address _sarcoToken) public initializer {
sarcoToken = IERC20(_sarcoToken);
emit Events.Creation(_sarcoToken);
}
/**
* @notice Return the number of archaeologists that have been registered
* @return total registered archaeologist count
*/
function archaeologistCount() public view virtual returns (uint256) {
return _data.archaeologistAddresses.length;
}
/**
* @notice Given an index (of the full archaeologist array), return the
* archaeologist address at that index
* @param index The index of the registered archaeologist
* @return address of the archaeologist
*/
function archaeologistAddresses(uint256 index)
public
view
virtual
returns (address)
{
return _data.archaeologistAddresses[index];
}
/**
* @notice Given an archaeologist address, return that archaeologist's
* profile
* @param account The archaeologist account's address
* @return the Archaeologist object
*/
function archaeologists(address account)
public
view
virtual
returns (Types.Archaeologist memory)
{
return _data.archaeologists[account];
}
/**
* @notice Return the total number of sarcophagi that have been created
* @return the number of sarcophagi that have ever been created
*/
function sarcophagusCount() public view virtual returns (uint256) {
return _data.sarcophagusIdentifiers.length;
}
/**
* @notice Return the unique identifier of a sarcophagus, given it's index
* @param index The index of the sarcophagus
* @return the unique identifier of the given sarcophagus
*/
function sarcophagusIdentifier(uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.sarcophagusIdentifiers[index];
}
/**
* @notice Returns the count of sarcophagi created by a specific embalmer
* @param embalmer The address of the given embalmer
* @return the number of sarcophagi which have been created by an embalmer
*/
function embalmerSarcophagusCount(address embalmer)
public
view
virtual
returns (uint256)
{
return _data.embalmerSarcophaguses[embalmer].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given embalmer
* and index
* @param embalmer The address of an embalmer
* @param index The index of the embalmer's list of sarcophagi
* @return the double hash associated with the index of the embalmer's
* sarcophagi
*/
function embalmerSarcophagusIdentifier(address embalmer, uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.embalmerSarcophaguses[embalmer][index];
}
/**
* @notice Returns the count of sarcophagi created for a specific
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of sarcophagi which have been created for an
* archaeologist
*/
function archaeologistSarcophagusCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistSarcophaguses[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's list of sarcophagi
* @return the identifier associated with the index of the archaeologist's
* sarcophagi
*/
function archaeologistSarcophagusIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistSarcophaguses[archaeologist][index];
}
/**
* @notice Returns the count of sarcophagi created for a specific recipient
* @param recipient The address of the given recipient
* @return the number of sarcophagi which have been created for a recipient
*/
function recipientSarcophagusCount(address recipient)
public
view
virtual
returns (uint256)
{
return _data.recipientSarcophaguses[recipient].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given recipient
* and index
* @param recipient The address of a recipient
* @param index The index of the recipient's list of sarcophagi
* @return the identifier associated with the index of the recipient's
* sarcophagi
*/
function recipientSarcophagusIdentifier(address recipient, uint256 index)
public
view
virtual
returns (bytes32)
{
return _data.recipientSarcophaguses[recipient][index];
}
/**
* @notice Returns the count of successful sarcophagi completed by the
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of sarcophagi which have been successfully completed
* by the archaeologist
*/
function archaeologistSuccessesCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistSuccesses[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given archaeologist
* and index of successful sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's list of successfully
* completed sarcophagi
* @return the identifier associated with the index of the archaeologist's
* successfully completed sarcophagi
*/
function archaeologistSuccessesIdentifier(
address archaeologist,
uint256 index
) public view returns (bytes32) {
return _data.archaeologistSuccesses[archaeologist][index];
}
/**
* @notice Returns the count of cancelled sarcophagi from the archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of cancelled sarcophagi from the archaeologist
*/
function archaeologistCancelsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistCancels[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given archaeologist
* and index of the cancelled sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's cancelled sarcophagi
* @return the identifier associated with the index of the archaeologist's
* cancelled sarcophagi
*/
function archaeologistCancelsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistCancels[archaeologist][index];
}
/**
* @notice Returns the count of accused sarcophagi from the archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of accused sarcophagi from the archaeologist
*/
function archaeologistAccusalsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistAccusals[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index of the accused sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's accused sarcophagi
* @return the identifier associated with the index of the archaeologist's
* accused sarcophagi
*/
function archaeologistAccusalsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistAccusals[archaeologist][index];
}
/**
* @notice Returns the count of cleaned-up sarcophagi from the
* archaeologist
* @param archaeologist The address of the given archaeologist
* @return the number of cleaned-up sarcophagi from the archaeologist
*/
function archaeologistCleanupsCount(address archaeologist)
public
view
virtual
returns (uint256)
{
return _data.archaeologistCleanups[archaeologist].length;
}
/**
* @notice Returns the sarcophagus unique identifier for a given
* archaeologist and index of the cleaned-up sarcophagi
* @param archaeologist The address of an archaeologist
* @param index The index of the archaeologist's accused sarcophagi
* @return the identifier associated with the index of the archaeologist's
* leaned-up sarcophagi
*/
function archaeologistCleanupsIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistCleanups[archaeologist][index];
}
/**
* @notice Returns sarcophagus data given an indentifier
* @param identifier the unique identifier a sarcophagus
* @return sarc the Sarcophagus object
*/
function sarcophagus(bytes32 identifier)
public
view
virtual
returns (Types.Sarcophagus memory)
{
return _data.sarcophaguses[identifier];
}
/**
* @notice Registers a new archaeologist in the system
* @param currentPublicKey the public key to be used in the first
* sarcophagus
* @param endpoint where to contact this archaeologist on the internet
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to start with
* @return index of the new archaeologist
*/
function registerArchaeologist(
bytes memory currentPublicKey,
string memory endpoint,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond
) public virtual returns (uint256) {
return
Archaeologists.registerArchaeologist(
_data,
currentPublicKey,
endpoint,
paymentAddress,
feePerByte,
minimumBounty,
minimumDiggingFee,
maximumResurrectionTime,
freeBond,
sarcoToken
);
}
/**
* @notice An archaeologist may update their profile
* @param endpoint where to contact this archaeologist on the internet
* @param newPublicKey the public key to be used in the next
* sarcophagus
* @param paymentAddress all collected payments for the archaeologist will
* be sent here
* @param feePerByte amount of SARCO tokens charged per byte of storage
* being sent to Arweave
* @param minimumBounty the minimum bounty for a sarcophagus that the
* archaeologist will accept
* @param minimumDiggingFee the minimum digging fee for a sarcophagus that
* the archaeologist will accept
* @param maximumResurrectionTime the maximum resurrection time for a
* sarcophagus that the archaeologist will accept, in relative terms (i.e.
* "1 year" is 31536000 (seconds))
* @param freeBond the amount of SARCO bond that the archaeologist wants
* to add to their profile
* @return bool indicating that the update was successful
*/
function updateArchaeologist(
string memory endpoint,
bytes memory newPublicKey,
address paymentAddress,
uint256 feePerByte,
uint256 minimumBounty,
uint256 minimumDiggingFee,
uint256 maximumResurrectionTime,
uint256 freeBond
) public virtual returns (bool) {
return
Archaeologists.updateArchaeologist(
_data,
newPublicKey,
endpoint,
paymentAddress,
feePerByte,
minimumBounty,
minimumDiggingFee,
maximumResurrectionTime,
freeBond,
sarcoToken
);
}
/**
* @notice Archaeologist can withdraw any of their free bond
* @param amount the amount of the archaeologist's free bond that they're
* withdrawing
* @return bool indicating that the withdrawal was successful
*/
function withdrawBond(uint256 amount) public virtual returns (bool) {
return Archaeologists.withdrawBond(_data, amount, sarcoToken);
}
/**
* @notice Embalmer creates the skeleton for a new sarcopahgus
* @param name the name of the sarcophagus
* @param archaeologist the address of a registered archaeologist to
* assign this sarcophagus to
* @param resurrectionTime the resurrection time of the sarcophagus
* @param storageFee the storage fee that the archaeologist will receive,
* for saving this sarcophagus on Arweave
* @param diggingFee the digging fee that the archaeologist will receive at
* the first rewrap
* @param bounty the bounty that the archaeologist will receive when the
* sarcophagus is unwrapped
* @param identifier the identifier of the sarcophagus, which is the hash
* of the hash of the inner encrypted layer of the sarcophagus
* @param recipientPublicKey the public key of the recipient
* @return index of the new sarcophagus
*/
function createSarcophagus(
string memory name,
address archaeologist,
uint256 resurrectionTime,
uint256 storageFee,
uint256 diggingFee,
uint256 bounty,
bytes32 identifier,
bytes memory recipientPublicKey
) public virtual returns (uint256) {
return
Sarcophaguses.createSarcophagus(
_data,
name,
archaeologist,
resurrectionTime,
storageFee,
diggingFee,
bounty,
identifier,
recipientPublicKey,
sarcoToken
);
}
/**
* @notice Embalmer updates a sarcophagus given it's identifier, after
* the archaeologist has uploaded the encrypted payload onto Arweave
* @param newPublicKey the archaeologist's new public key, to use for
* encrypting the next sarcophagus that they're assigned to
* @param identifier the identifier of the sarcophagus
* @param assetId the identifier of the encrypted asset on Arweave
* @param v signature element
* @param r signature element
* @param s signature element
* @return bool indicating that the update was successful
*/
function updateSarcophagus(
bytes memory newPublicKey,
bytes32 identifier,
string memory assetId,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (bool) {
return
Sarcophaguses.updateSarcophagus(
_data,
newPublicKey,
identifier,
assetId,
v,
r,
s,
sarcoToken
);
}
/**
* @notice An embalmer may cancel a sarcophagus if it hasn't been
* completely created
* @param identifier the identifier of the sarcophagus
* @return bool indicating that the cancel was successful
*/
function cancelSarcophagus(bytes32 identifier)
public
virtual
returns (bool)
{
return Sarcophaguses.cancelSarcophagus(_data, identifier, sarcoToken);
}
/**
* @notice Embalmer can extend the resurrection time of the sarcophagus,
* as long as the previous resurrection time is in the future
* @param identifier the identifier of the sarcophagus
* @param resurrectionTime new resurrection time for the rewrapped
* sarcophagus
* @param diggingFee new digging fee for the rewrapped sarcophagus
* @param bounty new bounty for the rewrapped sarcophagus
* @return bool indicating that the rewrap was successful
*/
function rewrapSarcophagus(
bytes32 identifier,
uint256 resurrectionTime,
uint256 diggingFee,
uint256 bounty
) public virtual returns (bool) {
return
Sarcophaguses.rewrapSarcophagus(
_data,
identifier,
resurrectionTime,
diggingFee,
bounty,
sarcoToken
);
}
/**
* @notice Given a sarcophagus identifier, preimage, and private key,
* verify that the data is valid and close out that sarcophagus
* @param identifier the identifier of the sarcophagus
* @param privateKey the archaeologist's private key which will decrypt the
* outer layer of the encrypted payload on Arweave
* @return bool indicating that the unwrap was successful
*/
function unwrapSarcophagus(bytes32 identifier, bytes32 privateKey)
public
virtual
returns (bool)
{
return
Sarcophaguses.unwrapSarcophagus(
_data,
identifier,
privateKey,
sarcoToken
);
}
/**
* @notice Given a sarcophagus, accuse the archaeologist for unwrapping the
* sarcophagus early
* @param identifier the identifier of the sarcophagus
* @param singleHash the preimage of the sarcophagus identifier
* @param paymentAddress the address to receive payment for accusing the
* archaeologist
* @return bool indicating that the accusal was successful
*/
function accuseArchaeologist(
bytes32 identifier,
bytes memory singleHash,
address paymentAddress
) public virtual returns (bool) {
return
Sarcophaguses.accuseArchaeologist(
_data,
identifier,
singleHash,
paymentAddress,
sarcoToken
);
}
/**
* @notice Extends a sarcophagus resurrection time into infinity
* effectively signaling that the sarcophagus is over and should never be
* resurrected
* @param identifier the identifier of the sarcophagus
* @return bool indicating that the bury was successful
*/
function burySarcophagus(bytes32 identifier) public virtual returns (bool) {
return Sarcophaguses.burySarcophagus(_data, identifier, sarcoToken);
}
/**
* @notice Clean up a sarcophagus whose resurrection time and window have
* passed. Callable by anyone.
* @param identifier the identifier of the sarcophagus
* @param paymentAddress the address to receive payment for cleaning up the
* sarcophagus
* @return bool indicating that the clean up was successful
*/
function cleanUpSarcophagus(bytes32 identifier, address paymentAddress)
public
virtual
returns (bool)
{
return
Sarcophaguses.cleanUpSarcophagus(
_data,
identifier,
paymentAddress,
sarcoToken
);
}
}
|
Returns the sarcophagus unique identifier for a given archaeologist and index archaeologist The address of an archaeologist index The index of the archaeologist's list of sarcophagi return the identifier associated with the index of the archaeologist's sarcophagi/
|
function archaeologistSarcophagusIdentifier(
address archaeologist,
uint256 index
) public view virtual returns (bytes32) {
return _data.archaeologistSarcophaguses[archaeologist][index];
}
| 2,451,211
|
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
import "../Math/SafeMath.sol";
import "../Interfaces/RTCoinInterface.sol";
/// @title This contract is used to handle vesting of the RTC token
/// @author Postables, RTrade Technologies Ltd
/// @dev We able V5 for safety features, see https://solidity.readthedocs.io/en/v0.4.24/security-considerations.html#take-warnings-seriously
contract Vesting {
using SafeMath for uint256;
// these will need to be changed prior to deployment
address constant public TOKENADDRESS = 0xB8fe3B2C83014566733B766a27d94CB9AC167Dc6;
RTCoinInterface constant public RTI = RTCoinInterface(TOKENADDRESS);
address public admin;
// keeps track of the state of a vest
enum VestState {nil, vesting, vested}
struct Vest {
// total amount of coins vesting
uint256 totalVest;
// the times at which the tokens will unlock
uint256[] releaseDates;
// the amount of tokens to unlock at each interval
uint256[] releaseAmounts;
VestState state;
// keeps track of what tokens have been unlocked
mapping (uint256 => bool) claimed;
}
// Keeps track of token vests
mapping (address => Vest) public vests;
// make sure that they are using a valid vest index
modifier validIndex(uint256 _vestIndex) {
require(_vestIndex < vests[msg.sender].releaseDates.length, "attempting to access invalid vest index must be less than length of array");
_;
}
// make sure that the claim date has been passed
modifier pastClaimDate(uint256 _vestIndex) {
require(now >= vests[msg.sender].releaseDates[_vestIndex], "attempting to claim vest before release date");
_;
}
// make sure that the vest is not yet claimed
modifier unclaimedVest(uint256 _vestIndex) {
require(!vests[msg.sender].claimed[_vestIndex], "vest must be unclaimed");
_;
}
// make sure that the vest is active
modifier activeVester() {
require(vests[msg.sender].state == VestState.vesting, "vest must be active");
_;
}
// make sure that the user has no active vests going on
modifier nonActiveVester(address _vester) {
require(vests[_vester].state == VestState.nil, "address must not have an active vest");
_;
}
modifier onlyAdmin() {
require(msg.sender == admin, "sender must be admin");
_;
}
constructor() public {
// prevent deployments if not properly setup
require(TOKENADDRESS != address(0), "token address not set");
admin = msg.sender;
}
/** @notice Used to deposit a vest for someone
* Mythril will report an overflow here, however it is a false positive
* @dev Yes we are looping, however we have the ability to ensure that the block gas limit will never be reached
* @param _vester This is the person for whom vests are being enabled
* @param _totalAmountToVest This is the total amount of coins being vested
* @param _releaseDates These are the dates at which tokens will be unlocked
* @param _releaseAmounts these are the amounts of tokens to be unlocked at each date
*/
function addVest(
address _vester,
uint256 _totalAmountToVest,
uint256[] _releaseDates, // unix time stamp format `time.Now().Unix()` in golang
uint256[] _releaseAmounts)
public
nonActiveVester(_vester)
onlyAdmin
returns (bool)
{
require(_releaseDates.length > 0 && _releaseAmounts.length > 0 && _totalAmountToVest > 0, "attempting to use non zero values");
require(_releaseDates.length == _releaseAmounts.length, "array lengths are not equal");
uint256 total;
for (uint256 i = 0; i < _releaseAmounts.length; i++) {
total = total.add(_releaseAmounts[i]);
require(now < _releaseDates[i], "release date must be in the future");
}
require(total == _totalAmountToVest, "invalid total amount to vest");
Vest memory v = Vest({
totalVest: _totalAmountToVest,
releaseDates: _releaseDates,
releaseAmounts: _releaseAmounts,
state: VestState.vesting
});
vests[_vester] = v;
require(RTI.transferFrom(msg.sender, address(this), _totalAmountToVest), "transfer from failed, most likely needs approval");
return true;
}
/** @notice Used to withdraw unlocked vested tokens
* @dev Yes we are looping, but as we can control the total number of loops, etc.. we can ensure that the block gas limit will never be reached
* @notice IF YOU ARE WITHDRAWING THE LAST VEST (LAST INDEX) YOU MUST HAVE WITHDRAWN ALL OTHER VESTS FIRST OR THE TX WILL FAIL
* @param _vestIndex the particular vest to be withdrawn
*/
function withdrawVestedTokens(
uint256 _vestIndex)
public
activeVester
validIndex(_vestIndex)
unclaimedVest(_vestIndex)
pastClaimDate(_vestIndex)
returns (bool)
{
// if this is the last vest, make sure all others have been claimed and then mark as vested
if (_vestIndex == vests[msg.sender].releaseAmounts.length.sub(1)) {
bool check;
for (uint256 i = 0; i < vests[msg.sender].releaseAmounts.length; i++) {
// if we detect that even one vest hasn't been claimed, set check to false and break out of loop
if (!vests[msg.sender].claimed[i]) {
// this will preventsituations where the first vest may not be claimed but later ones have been
// which would result in a "split brain" type scenario, in which the code thinks all vests have been claimed
// but they actually haven't
check = false;
// break out of the loop
break;
}
check = true;
}
// if they are attempting to withdraw the last vest, this must be true or else the tx will revert
require(check, "not all vests have been withdrawn before attempting to withdraw final vest");
}
// mark this particular vest as claimed
vests[msg.sender].claimed[_vestIndex] = true;
uint256 amount = vests[msg.sender].releaseAmounts[_vestIndex];
require(RTI.transfer(msg.sender, amount), "failed to transfer");
return true;
}
}
|
Used to withdraw unlocked vested tokens Yes we are looping, but as we can control the total number of loops, etc.. we can ensure that the block gas limit will never be reached IF YOU ARE WITHDRAWING THE LAST VEST (LAST INDEX) YOU MUST HAVE WITHDRAWN ALL OTHER VESTS FIRST OR THE TX WILL FAIL _vestIndex the particular vest to be withdrawn/ if this is the last vest, make sure all others have been claimed and then mark as vested if we detect that even one vest hasn't been claimed, set check to false and break out of loop this will preventsituations where the first vest may not be claimed but later ones have been which would result in a "split brain" type scenario, in which the code thinks all vests have been claimed but they actually haven't break out of the loop
|
function withdrawVestedTokens(
uint256 _vestIndex)
public
activeVester
validIndex(_vestIndex)
unclaimedVest(_vestIndex)
pastClaimDate(_vestIndex)
returns (bool)
{
if (_vestIndex == vests[msg.sender].releaseAmounts.length.sub(1)) {
bool check;
for (uint256 i = 0; i < vests[msg.sender].releaseAmounts.length; i++) {
if (!vests[msg.sender].claimed[i]) {
check = false;
break;
}
check = true;
}
}
uint256 amount = vests[msg.sender].releaseAmounts[_vestIndex];
require(RTI.transfer(msg.sender, amount), "failed to transfer");
return true;
}
| 15,872,575
|
./partial_match/1/0x699F6Cf5ba9b8c878e3D511286c5B3574161563D/sources/src/eligibility/Nested.sol
|
Returns true iff the moonbird is nested./
|
function isEligible(uint256 tokenId) public view virtual returns (bool) {
(bool nesting,,) = _moonbirds.nestingPeriod(tokenId);
return nesting;
}
| 16,151,134
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol";
contract ReDDrop is ERC1155Receiver {
/// ============ Storage ============
// Boolean that represents if the contract has been initialized
bool private _initialized;
// {SliceCore} address
address private immutable _sliceCoreAddress;
// The account who receives ETH from the sales
address private immutable _collector;
// The account who sent the slices to the contract
address private _slicesSupplier;
// The tokenId related to the slicer linked to this contract
uint256 private _tokenId;
// Price of each slice
uint256 private SLICE_PRICE = 2 ether;
/// ============ Errors ============
/// @notice Thrown if contract has been initialized
error Initialized();
/// @notice Thrown if contract has not been initialized
error NotInitialized();
/// @notice Thrown if contract receives ERC1155 not related to slicers
error NotSlicer();
/// @notice Thrown if caller doesn't have the right permission
error NotAuthorized();
/// @notice Thrown if the value sent is not sufficient to claim
error InsufficientPayment();
/// ============ Events ============
/// @notice Emitted when slices are claimed
event Claimed(address indexed to, uint256 amount, uint256 _tokenId);
/// @notice Emitted when the sale is marked as closed
event SaleClosed(address slicesSupplier, uint256 slicesAmount);
/// ============ Constructor ============
/**
* @notice Initializes the contract.
*
* @param sliceCoreAddress_ {SliceCore} address
* @param collector_ Address of the account that receives ETH from sales
*
* @dev Claims will revert once there are no more slices in the contract.
*/
constructor(
address sliceCoreAddress_,
address collector_
) {
_sliceCoreAddress = sliceCoreAddress_;
_collector = collector_;
}
/// ============ Functions ============
/**
* @notice Sends all ETH received from the sale to the appointed collector.
*/
function releaseToCollector() external {
(bool success, ) = payable(_collector).call{value: address(this).balance}("");
require(success);
}
/**
* @notice Sends all slices received back to the address who supplied them.
*
* @dev Safe measure in case the sale needs to be cancelled, or it has unclaimed slices.
* @dev Can only be called by the slices supplier.
*/
function _closeSale() external {
if (msg.sender != _slicesSupplier) revert NotAuthorized();
uint256 slices = IERC1155Upgradeable(_sliceCoreAddress).balanceOf(address(this), _tokenId);
IERC1155Upgradeable(_sliceCoreAddress).safeTransferFrom(address(this), _slicesSupplier, _tokenId, slices, "");
_initialized = false;
emit SaleClosed(_slicesSupplier, slices);
}
/// @notice Returns information about the sale.
function saleInfo() external view returns(
uint256 tokenId,
address collector,
uint256 slicePrice
) {
return (_tokenId, _collector, SLICE_PRICE);
}
function slicesLeft() external view returns(uint256) {
return IERC1155Upgradeable(_sliceCoreAddress).balanceOf(address(this), _tokenId);
}
/**
* @notice Allows users to claim slices by paying the price.
*
* @param quantity Number of slices to claim.
*/
function claim(uint256 quantity) external payable {
if (!_initialized) revert NotInitialized();
// Revert if value doesn't cover the claim price
if (msg.value < SLICE_PRICE * quantity) revert InsufficientPayment();
// Send slices to his address
IERC1155Upgradeable(_sliceCoreAddress).safeTransferFrom(address(this), msg.sender, _tokenId, quantity, "");
// Emit claim event
emit Claimed(msg.sender, _tokenId, quantity);
}
/**
* @notice Initializes the contract upon reception of the first transfer of slices.
*
* @dev Supports only slice transfer, not mint.
* @dev Can only receive slices once.
* @dev Can only receive Slice ERC1155 tokens
*/
function onERC1155Received(
address,
address from,
uint256 tokenId_,
uint256,
bytes memory
)
external
virtual
override
returns (bytes4)
{
if (msg.sender != _sliceCoreAddress) revert NotSlicer();
if (_initialized) revert Initialized();
_initialized = true;
_slicesSupplier = from;
_tokenId = tokenId_;
return this.onERC1155Received.selector;
}
/**
* @dev See `onERC1155Received`
*/
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
)
public
virtual
override
returns (bytes4)
{
revert();
}
/**
* @notice Allows receiving eth.
*/
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 IERC165Upgradeable {
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
|
Initializes the contract upon reception of the first transfer of slices. Supports only slice transfer, not mint. Can only receive slices once. Can only receive Slice ERC1155 tokens/
|
function onERC1155Received(
address,
address from,
uint256 tokenId_,
uint256,
bytes memory
)
external
virtual
override
returns (bytes4)
{
if (msg.sender != _sliceCoreAddress) revert NotSlicer();
if (_initialized) revert Initialized();
_initialized = true;
_slicesSupplier = from;
_tokenId = tokenId_;
return this.onERC1155Received.selector;
}
| 10,344,066
|
./full_match/1/0xC04dE60292580b9b7f01d610785309f6Bd1690aF/sources/src/JapaneseTinyPenpen.sol
|
Set `newCustomURI` to `_customURI`. `_customURI` is used for tokenURI information./
|
function setCustomURI(string memory newCustomURI) external onlyHandler {
_customURI = newCustomURI;
}
| 2,978,395
|
pragma solidity ^0.5.0;
contract UserProfile {
string userName = "1234";
mapping(address => string []) user_name;
mapping(string => string []) user_name_public;
mapping(address => string []) email_contact;
mapping(string => string []) email_contact_public;
mapping(address => string []) profile_pic;
mapping(string => string []) profile_pic_public;
// mapping(address => string []) public proposals;
// mapping(string => string []) public proposals_public;
mapping(address => string []) income_proof;
mapping(string => string []) income_proof_public;
// function getUserInfo() public view returns(string memory profile_pic, string memory user_name, string memory email, string memory income_proof, uint256 profile_length, uint256 name_length, uint256 email_length, uint256 proposals_length, uint256 income_length ){
// }
function updateUserName(string memory addr,string memory name) public returns(bool){
user_name[msg.sender].push(name);
user_name_public[addr].push(name);
// userName = name;
return(true);
}
function getUserName(string memory addr) public view returns(string memory){
return user_name_public[addr][user_name_public[addr].length-1];
// return user_name[msg.sender][user_name[msg.sender].length-1];
}
// function getUserNameByOthers(string memory addr) public view returns(string memory){
// return user_name[addr][user_name[addr].length-1];
// }
function updateEmail(string memory addr,string memory email) public returns(bool){
email_contact[msg.sender].push(email);
email_contact_public[addr].push(email);
return(true);
}
function getEmail(string memory addr) public view returns(string memory){
return email_contact_public[addr][email_contact_public[addr].length-1];
// return email_contact[msg.sender][email_contact[msg.sender].length-1];
}
// function getEmailByOthers(string memory addr) public view returns(string memory){
// return email_contact[addr][email_contact[addr].length-1];
// }
function updateProfilePic(string memory addr,string memory ipfsHash) public returns(bool){
profile_pic[msg.sender].push(ipfsHash);
profile_pic_public[addr].push(ipfsHash);
return(true);
}
function getProfilePic(string memory addr) public view returns(string memory){
return profile_pic_public[addr][profile_pic_public[addr].length-1];
// return profile_pic[msg.sender][profile_pic[msg.sender].length-1];
}
// function getProfilePicByOthers(string memory addr) public view returns(string memory){
// return profile_pic[addr][profile_pic[addr].length-1];
// }
// function addProposal(string memory addr,string memory ipfsHash) public returns(bool){
// proposals[msg.sender].push(ipfsHash);
// return(true);
// }
// function getProposalsLength(string memory addr,string memory addr) public view returns(uint256){
// return(proposals[msg.sender].length);
// }
function updateIncomeProof(string memory addr,string memory ipfsHash) public returns(bool){
income_proof[msg.sender].push(ipfsHash);
income_proof_public[addr].push(ipfsHash);
return(true);
}
function getIncomeProof(string memory addr) public view returns(string memory){
return income_proof_public[addr][income_proof_public[addr].length-1];
// return income_proof[msg.sender][income_proof[msg.sender].length-1];
}
// function getIncomeProofByOthers(string memory addr) public view returns(string memory){
// return income_proof[addr][income_proof[addr].length-1];
// }
}
|
return profile_pic[msg.sender][profile_pic[msg.sender].length-1];
|
function getProfilePic(string memory addr) public view returns(string memory){
return profile_pic_public[addr][profile_pic_public[addr].length-1];
}
| 12,920,848
|
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of CobeFriendCore that manages special access privileges.
/// @author CybEye (http://www.cybeye.com/us/index.jsp)
/// @dev See the CobeFriendCore contract documentation to understand how the various contract facets are arranged.
contract CobeFriendACL {
// This facet controls access control for CobeFriends. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the CobeFriendCore constructor.
//
// - The CFO: The CFO can withdraw funds from CobeFriendCore and its auction contracts.
//
// - The COO: The COO can release gen0 CobeFriends to auction, and mint promo CobeFriends.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CobeFriend. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the CobeFriendCore contract documentation to understand how the various contract facets are arranged.
contract CobeFriendBase is CobeFriendACL {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new CobeFriend comes into existence. This obviously
/// includes any time a CobeFriend is created through the giveBirth method, but it is also called
/// when a new gen0 CobeFriend is created.
event Birth(address owner, uint256 CobeFriendId, uint256 matronId, uint256 sireId, uint256 genes, uint256 generation);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a CobeFriend
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main CobeFriend struct. Every CobeFriend in CobeFriend is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct CobeFriend {
// The CobeFriend's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A CobeFriend's genes never change.
uint256 genes;
// The timestamp from the block when this CobeFriend came into existence.
uint64 birthTime;
// The minimum timestamp after which this CobeFriend can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this CobeFriend, set to 0 for gen0 CobeFriends.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion CobeFriends. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire CobeFriend for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a CobeFriend
// is pregnant. Used to retrieve the genetic material for the new
// CobeFriend when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this CobeFriend. This starts at zero
// for gen0 CobeFriends, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this CobeFriend is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this CobeFriend. CobeFriends minted by the CZ contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other CobeFriends is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table inCobeFriending the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a CobeFriend
/// is bred, encouraging owners not to just keep breeding the same CobeFriend over
/// and over again. Caps out at one week (a CobeFriend can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the CobeFriend struct for all CobeFriends in existence. The ID
/// of each CobeFriend is actually an index into this array. Note that ID 0 is a negaCobeFriend,
/// the unCobeFriend, the mythical beast that is the parent of all gen0 CobeFriends. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, CobeFriend ID 0 is invalid... ;-)
CobeFriend[] CobeFriends;
/// @dev A mapping from CobeFriend IDs to the address that owns them. All CobeFriends have
/// some valid owner address, even gen0 CobeFriends are created with a non-zero owner.
mapping (uint256 => address) public CobeFriendIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from CobeFriendIDs to an address that has been approved to call
/// transferFrom(). Each CobeFriend can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public CobeFriendIndexToApproved;
/// @dev A mapping from CobeFriendIDs to an address that has been approved to use
/// this CobeFriend for siring via breedWith(). Each CobeFriend can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of CobeFriends. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev Assigns ownership of a specific CobeFriend to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of CobeFriends is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
CobeFriendIndexToOwner[_tokenId] = _to;
// When creating new CobeFriends _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the CobeFriend is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete CobeFriendIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new CobeFriend and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The CobeFriend ID of the matron of this CobeFriend (zero for gen0)
/// @param _sireId The CobeFriend ID of the sire of this CobeFriend (zero for gen0)
/// @param _generation The generation number of this CobeFriend, must be computed by caller.
/// @param _genes The CobeFriend's genetic code.
/// @param _owner The inital owner of this CobeFriend, must be non-zero (except for the unCobeFriend, ID 0)
function _createCobeFriend(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createCobeFriend() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New CobeFriend starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
CobeFriend memory _CobeFriend = CobeFriend({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newCobeFriendId = CobeFriends.push(_CobeFriend) - 1;
// It's probably never going to happen, 4 billion CobeFriends is A LOT, but
// let's just be 100% sure we never let this happen.
require(newCobeFriendId == uint256(uint32(newCobeFriendId)));
// emit the birth event
Birth(
_owner,
newCobeFriendId,
uint256(_CobeFriend.matronId),
uint256(_CobeFriend.sireId),
_CobeFriend.genes,
uint256(_CobeFriend.generation)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newCobeFriendId);
return newCobeFriendId;
}
/// @dev An internal method that creates a new CobeFriend and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The CobeFriend ID of the matron of this CobeFriend (zero for gen0)
/// @param _sireId The CobeFriend ID of the sire of this CobeFriend (zero for gen0)
/// @param _generation The generation number of this CobeFriend, must be computed by caller.
/// @param _genes The CobeFriend's genetic code.
/// @param _owner The inital owner of this CobeFriend, must be non-zero (except for the unCobeFriend, ID 0)
/// @param _time The birth time of CobeFriend
/// @param _cooldownIndex The cooldownIndex of CobeFriend
function _createCobeFriendWithTime(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint256 _time,
uint256 _cooldownIndex
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createCobeFriend() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
// Copy down CobeFriend cooldownIndex
uint16 cooldownIndex = uint16(_cooldownIndex);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
CobeFriend memory _CobeFriend = CobeFriend({
genes: _genes,
birthTime: uint64(_time),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newCobeFriendId = CobeFriends.push(_CobeFriend) - 1;
// It's probably never going to happen, 4 billion CobeFriends is A LOT, but
// let's just be 100% sure we never let this happen.
require(newCobeFriendId == uint256(uint32(newCobeFriendId)));
// emit the birth event
Birth(
_owner,
newCobeFriendId,
uint256(_CobeFriend.matronId),
uint256(_CobeFriend.sireId),
_CobeFriend.genes,
uint256(_CobeFriend.generation)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newCobeFriendId);
return newCobeFriendId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the CobeFriends,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title The facet of the CobeFriends core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the CobeFriendCore contract documentation to understand how the various contract facets are arranged.
contract CobeFriendOwnership is CobeFriendBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CobeFriends";
string public constant symbol = "CBF";
// The contract that will return CobeFriend metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular CobeFriend.
/// @param _claimant the address we are validating against.
/// @param _tokenId CobeFriend id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular CobeFriend.
/// @param _claimant the address we are confirming CobeFriend is approved for.
/// @param _tokenId CobeFriend id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return CobeFriendIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting CobeFriends on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
CobeFriendIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of CobeFriends owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a CobeFriend to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CobeFriends specifically) or your CobeFriend may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the CobeFriend to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of CobeFriends
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own cbf.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific CobeFriend via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the CobeFriend that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a CobeFriend owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the CobeFriend to be transfered.
/// @param _to The address that should take ownership of the CobeFriend. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the CobeFriend to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any CobeFriends (except very briefly
// after a gen0 cbf is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of CobeFriends currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return CobeFriends.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given CobeFriend.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = CobeFriendIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all CobeFriend IDs assigned to an address.
/// @param _owner The owner whose CobeFriends we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire CobeFriend array looking for cbfs belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalcbfs = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cbfs have IDs starting at 1 and increasing
// sequentially up to the totalcbf count.
uint256 cbfId;
for (cbfId = 1; cbfId <= totalcbfs; cbfId++) {
if (CobeFriendIndexToOwner[cbfId] == _owner) {
result[resultIndex] = cbfId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the CobeFriend whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction modified for sale of CobeFriends
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 CobeFriend sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Handles creating auctions for sale and siring of CobeFriends.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract CobeFriendAuction is CobeFriendOwnership {
// @notice The auction contract variables are defined in CobeFriendBase to allow
// us to refer to them in CobeFriendOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of CobeFriends.
// `siringAuction` refers to the auction for siring rights of CobeFriends.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a CobeFriend up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _CobeFriendId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If CobeFriend is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _CobeFriendId));
_approve(_CobeFriendId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the CobeFriend.
saleAuction.createAuction(
_CobeFriendId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the CobeFriendCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
}
}
/// @title all functions related to creating CobeFriends
contract CobeFriendMinting is CobeFriendAuction {
// Limits the number of cbfs the contract owner can ever create.
uint256 public constant DEFAULT_CREATION_LIMIT = 50000;
// Counts the number of cbfs the contract owner has created.
uint256 public defaultCreatedCount;
/// @dev we can create CobeFriends with different generations. Only callable by COO
/// @param _genes The encoded genes of the CobeFriend to be created, any value is accepted
/// @param _owner The future owner of the created CobeFriend. Default to contract COO
/// @param _time The birth time of CobeFriend
/// @param _cooldownIndex The cooldownIndex of CobeFriend
function createDefaultGen0CobeFriend(uint256 _genes, address _owner, uint256 _time, uint256 _cooldownIndex) external onlyCOO {
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
require(_time > 0);
require(_cooldownIndex >= 0 && _cooldownIndex <= 13);
address CobeFriendOwner = _owner;
if (CobeFriendOwner == address(0)) {
CobeFriendOwner = cooAddress;
}
require(defaultCreatedCount < DEFAULT_CREATION_LIMIT);
defaultCreatedCount++;
_createCobeFriendWithTime(0, 0, 0, _genes, CobeFriendOwner, _time, _cooldownIndex);
}
/// @dev we can create CobeFriends with different generations. Only callable by COO
/// @param _matronId The CobeFriend ID of the matron of this CobeFriend
/// @param _sireId The CobeFriend ID of the sire of this CobeFriend
/// @param _genes The encoded genes of the CobeFriend to be created, any value is accepted
/// @param _owner The future owner of the created CobeFriend. Default to contract COO
/// @param _time The birth time of CobeFriend
/// @param _cooldownIndex The cooldownIndex of CobeFriend
function createDefaultCobeFriend(uint256 _matronId, uint256 _sireId, uint256 _genes, address _owner, uint256 _time, uint256 _cooldownIndex) external onlyCOO {
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
require(_time > 0);
require(_cooldownIndex >= 0 && _cooldownIndex <= 13);
address CobeFriendOwner = _owner;
if (CobeFriendOwner == address(0)) {
CobeFriendOwner = cooAddress;
}
require(_matronId > 0);
require(_sireId > 0);
// Grab a reference to the matron in storage.
CobeFriend storage matron = CobeFriends[_matronId];
// Grab a reference to the sire in storage.
CobeFriend storage sire = CobeFriends[_sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
_createCobeFriendWithTime(_matronId, _sireId, parentGen + 1, _genes, CobeFriendOwner, _time, _cooldownIndex);
}
}
/// @title CobeFriends: Collectible, breedable, and oh-so-adorable CobeFriends on the Ethereum blockchain.
/// @dev The main CobeFriends contract, keeps track of cbfs so they don't wander around and get lost.
contract CobeFriendCore is CobeFriendMinting {
/* contract CobeFriendCore { */
// This is the main CobeFriends contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// CobeFriend ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - CobeFriendBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - CobeFriendAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - CobeFriendOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - CobeFriendBreeding: This file contains the methods necessary to breed CobeFriends together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - CobeFriendAuctions: Here we have the public methods for auctioning or bidding on CobeFriends or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - CobeFriendMinting: This final facet contains the functionality we use for creating new gen0 CobeFriends.
// We can make up to 5000 "promo" CobeFriends that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 2400*12*12 gen0 CobeFriends. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CobeFriends smart contract instance.
function CobeFriendCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the mythical CobeFriend 0 - so we don't have generation-0 parent issues
_createCobeFriend(0, 0, 0, uint256(-1), address(0));
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @notice Returns all the relevant information about a specific CobeFriend.
/// @param _id The ID of the CobeFriend of interest.
function getCobeFriend(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
CobeFriend storage cbf = CobeFriends[_id];
// if this variable is 0 then it's not gestating
isGestating = (cbf.siringWithId != 0);
isReady = (cbf.cooldownEndBlock <= block.number);
cooldownIndex = uint256(cbf.cooldownIndex);
nextActionAt = uint256(cbf.cooldownEndBlock);
siringWithId = uint256(cbf.siringWithId);
birthTime = uint256(cbf.birthTime);
matronId = uint256(cbf.matronId);
sireId = uint256(cbf.sireId);
generation = uint256(cbf.generation);
genes = cbf.genes;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
cfoAddress.transfer(balance);
}
}
|
Marks an address as being approved for transferFrom(), overwriting any previous approval. Setting _approved to address(0) clears all transfer approval. NOTE: _approve() does NOT send the Approval event. This is intentional because _approve() and transferFrom() are used together for putting CobeFriends on auction, and there is no value in spamming the log with Approval events in that case.
|
function _approve(uint256 _tokenId, address _approved) internal {
CobeFriendIndexToApproved[_tokenId] = _approved;
}
| 13,736,965
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./IVoteD21.sol";
/**
* @title D21 voting system contract
* @author smrza
* @notice More about D21 voting system: https://www.ih21.org/en/d21-janecekmethod
*/
contract D21 is IVoteD21 {
address immutable public owner; // Chairperson or someone important
uint private timeout; // Time of creation + 1 week, used for 1 week timeout
mapping(address => Subject) private subjects; // Each created subject
mapping(address => Voter) private voters; // Each eligible voter
mapping(address => bool) private subjectCreated; // Map whoever created a subject
address[] private subjectsAddr; // Save addresses of subjects
constructor() {
owner = msg.sender;
timeout = block.timestamp + 1 weeks;
}
// Ensures the elections are still active
modifier electionsActive {
require(timeout > block.timestamp, "Elections have ended.");
_;
}
// Ensures voter has the right to vote
modifier voterActive {
require(voters[msg.sender].canVote, "You cannot vote.");
_;
}
// Ensures subject exists
modifier subjectActive(address addr) {
require(subjectCreated[addr], "This subject does not exist.");
_;
}
/**
* @notice Adds a subject to the polls
* @dev Elections must be active
* @param name Name of the subject
*/
function addSubject(string memory name) external electionsActive {
require(!subjectCreated[msg.sender], "You have already created a subject.");
subjects[msg.sender] = Subject(name, 0);
subjectsAddr.push(msg.sender);
subjectCreated[msg.sender] = true;
}
/**
* @notice Adds an eligible voter to the polls
* @dev Elections must be active
* @param addr Voter's address
*/
function addVoter(address addr) external electionsActive {
require(msg.sender == owner, "Only owner can give right to vote.");
require(!voters[addr].canVote, "This person already has the right to vote.");
voters[addr] = Voter(true, address(0x0), address(0x0), 0);
}
/**
* @notice Gets all subjects' addresses
* @return The addresses of subjects
*/
function getSubjects() external view returns(address[] memory) {
return subjectsAddr;
}
/**
* @notice Gets a single subject by address and its name and vote count
* @param addr Address of the subject
* @return The subject structure with name and vote count
*/
function getSubject(address addr) external view returns(Subject memory) {
return subjects[addr];
}
/**
* @notice A voter votes positive for a subject
* @dev Elections, voter and subject must be active
* @param addr Address of subject to vote for
*/
function votePositive(address addr) external electionsActive voterActive subjectActive(addr) {
Voter storage vot = voters[msg.sender];
require(vot.voteCount < 2, "You have already voted positive twice.");
require(vot.votePositiveAddr != addr, "You have already voted for this subject.");
++vot.voteCount;
++subjects[addr].votes;
if(vot.voteCount == 1)
vot.votePositiveAddr = addr;
else
vot.votePositiveAddr2 = addr;
}
/**
* @notice A voter votes negative for a subject
* @dev Elections, voter and subject must be active
* @param addr Address of subject to vote for
*/
function voteNegative(address addr) external electionsActive voterActive subjectActive(addr) {
Voter storage vot = voters[msg.sender];
require(vot.voteCount > 1, "First, you must vote positive twice.");
require(vot.voteCount < 3, "You have already voted negative.");
require(vot.votePositiveAddr != addr && vot.votePositiveAddr2 != addr, "You already voted positive for this subject");
++vot.voteCount;
--subjects[addr].votes;
}
/**
* @notice Returns how much time is left until the elections are over
* @dev Elections must be active
* @return The remaining time in seconds
*/
function getRemainingTime() external electionsActive view returns(uint) {
return timeout - block.timestamp;
}
}
|
Adds a subject to the polls Elections must be active name Name of the subject/
|
function addSubject(string memory name) external electionsActive {
require(!subjectCreated[msg.sender], "You have already created a subject.");
subjects[msg.sender] = Subject(name, 0);
subjectsAddr.push(msg.sender);
subjectCreated[msg.sender] = true;
}
| 15,782,242
|
./partial_match/82/0xf7DB8ED56C99F043EDf1483eA36CB542cACc2156/sources/flat.sol
|
getter functions / pure functions / File: contracts/interfaces/EUniversalVault.sol
|
interface IUniversalVault {
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(
address delegate,
address token,
bool notified,
string reason
);
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external;
function getGeyserData() external view returns (GeyserData memory geyser);
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index)
external
view
returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index)
external
view
returns (address factory);
function getVaultData(address vault)
external
view
returns (VaultData memory vaultData);
function isValidAddress(address target)
external
view
returns (bool validity);
function isValidVault(address target) external view returns (bool validity);
function getCurrentUnlockedRewards()
external
view
returns (uint256 unlockedRewards);
function getFutureUnlockedRewards(uint256 timestamp)
external
view
returns (uint256 unlockedRewards);
function getCurrentVaultReward(address vault)
external
view
returns (uint256 reward);
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
returns (uint256 reward);
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
returns (uint256 reward);
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view returns (uint256 reward);
function getCurrentVaultStakeUnits(address vault)
external
view
returns (uint256 stakeUnits);
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
external
view
returns (uint256 stakeUnits);
function getCurrentTotalStakeUnits()
external
view
returns (uint256 totalStakeUnits);
function getFutureTotalStakeUnits(uint256 timestamp)
external
view
returns (uint256 totalStakeUnits);
function calculateTotalStakeUnits(
StakeData[] memory stakes,
uint256 timestamp
) external pure returns (uint256 totalStakeUnits);
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) external pure returns (uint256 stakeUnits);
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) external pure returns (uint256 unlockedRewards);
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) external pure returns (RewardOutput memory out);
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) external pure returns (uint256 reward);
}
pragma solidity ^0.8.0;
struct LockData {
address delegate;
address token;
uint256 balance;
}
}
| 16,900,491
|
./full_match/1/0x94b34CcD6b6E39cF589d5be20B417e991FA86d1D/sources/contracts/CYAN.sol
|
Sets total supplies of given interval to current total supplies
|
function updateIntervals(uint256 interval) internal {
intervalsTotalSupply[interval] = _totalSupply;
intervalsTotalBurntSupply[interval] = _totalBurntSupply;
updateCurrentInterestDenominator();
}
| 8,339,725
|
./partial_match/1/0x3D7E1C13D4e1327c958534b2e50Fb2e8C7C0C114/sources/contracts/reward/StakingMultiRewardsUpgradeable.sol
|
Claim all the rewards. See getRewardFor for details.
|
function getAllRewards() public override {
for(uint256 i = 0; i < yields.length(); i++) {
getReward(yields.at(i));
}
}
| 15,733,523
|
./full_match/5/0xF5a1040714c1df643859A919DcD18B194c02B4b7/sources/project_/contracts/poolRegistry.sol
|
We do string comparison by checking the hashes of the strings against one another
|
function setPoolURI(uint256 _poolId, string calldata _uri)
public
ownsPool(_poolId)
{
if (
keccak256(abi.encodePacked(_uri)) !=
keccak256(abi.encodePacked(pools[_poolId].metadataURI))
) {
pools[_poolId].metadataURI = _uri;
emit SetPoolURI(_poolId, _uri);
}
}
| 7,039,775
|
./partial_match/3/0x6756F985C772f73Ef708316E4D212052F446e30f/sources/GovernorAlpha.sol
|
solhint-disable-next-line not-rely-on-time
|
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
return ProposalState.Pending;
return ProposalState.Active;
return ProposalState.Defeated;
return ProposalState.Succeeded;
return ProposalState.Executed;
return ProposalState.Expired;
return ProposalState.Queued;
}
}
| 5,234,409
|
./full_match/3/0x44663904b935Feb9dd52a835F17C349fb87F2e32/sources/contracts/ERC721_v2.sol
|
Pauses all token transfers. See {ERC721Pausable} and {Pausable-_pause}. Requirements: - the caller must have the `PAUSER_ROLE`./
|
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "BATERC721Tokenv2: must have pauser role to pause");
_pause();
}
| 8,255,378
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.10;
import "./PoolShare.sol";
/// @dev Token representing the principal shares of a pool.
contract PrincipalShare is PoolShare {
constructor(
ITempusPool _pool,
string memory name,
string memory symbol,
uint8 decimals
) PoolShare(ShareKind.Principal, _pool, name, symbol, decimals) {}
// solhint-disable-previous-line no-empty-blocks
function getPricePerFullShare() external override returns (uint256) {
return pool.pricePerPrincipalShare();
}
function getPricePerFullShareStored() external view override returns (uint256) {
return pool.pricePerPrincipalShareStored();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.10;
import "./ERC20OwnerMintableToken.sol";
import "../ITempusPool.sol";
/// Token representing the principal or yield shares of a pool.
abstract contract PoolShare is IPoolShare, ERC20OwnerMintableToken {
/// The kind of the share.
ShareKind public immutable override kind;
/// The pool this share is part of.
ITempusPool public immutable override pool;
uint8 internal immutable tokenDecimals;
constructor(
ShareKind _kind,
ITempusPool _pool,
string memory name,
string memory symbol,
uint8 _decimals
) ERC20OwnerMintableToken(name, symbol) {
kind = _kind;
pool = _pool;
tokenDecimals = _decimals;
}
function decimals() public view virtual override returns (uint8) {
return tokenDecimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// This is a simplified implementation, but compatible with
/// OpenZeppelin's ERC20Mintable and ERC20Burnable extensions.
contract ERC20OwnerMintableToken is ERC20 {
/// The manager who is allowed to mint and burn.
address public immutable manager;
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
manager = msg.sender;
}
/// Creates `amount` new tokens for `to`.
/// @param account Recipient address to mint tokens to
/// @param amount Number of tokens to mint
function mint(address account, uint256 amount) external {
require(msg.sender == manager, "mint: only manager can mint");
_mint(account, amount);
}
/// Destroys `amount` tokens from the caller.
/// @param amount Number of tokens to burn.
function burn(uint256 amount) external {
require(msg.sender == manager, "burn: only manager can burn");
_burn(manager, amount);
}
/// Destroys `amount` tokens from `account`.
/// @param account Source address to burn tokens from
/// @param amount Number of tokens to burn
function burnFrom(address account, uint256 amount) external {
require(msg.sender == manager, "burn: only manager can burn");
_burn(account, amount);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.6 <0.9.0;
pragma abicoder v2;
import "./token/IPoolShare.sol";
import "./utils/IOwnable.sol";
import "./utils/IVersioned.sol";
/// Setting and transferring of fees are restricted to the owner.
interface ITempusFees is IOwnable {
/// The fees are in terms of yield bearing token (YBT).
struct FeesConfig {
uint256 depositPercent;
uint256 earlyRedeemPercent;
uint256 matureRedeemPercent;
}
/// Returns the current fee configuration.
function getFeesConfig() external view returns (FeesConfig memory);
/// Replace the current fee configuration with a new one.
/// By default all the fees are expected to be set to zero.
/// @notice This function can only be called by the owner.
function setFeesConfig(FeesConfig calldata newFeesConfig) external;
/// @return Maximum possible fee percentage that can be set for deposit
function maxDepositFee() external view returns (uint256);
/// @return Maximum possible fee percentage that can be set for early redeem
function maxEarlyRedeemFee() external view returns (uint256);
/// @return Maximum possible fee percentage that can be set for mature redeem
function maxMatureRedeemFee() external view returns (uint256);
/// Accumulated fees available for withdrawal.
function totalFees() external view returns (uint256);
/// Transfers accumulated Yield Bearing Token (YBT) fees
/// from this pool contract to `recipient`.
/// @param recipient Address which will receive the specified amount of YBT
/// @notice This function can only be called by the owner.
function transferFees(address recipient) external;
}
/// All state changing operations are restricted to the controller.
interface ITempusPool is ITempusFees, IVersioned {
/// @return The name of underlying protocol, for example "Aave" for Aave protocol
function protocolName() external view returns (bytes32);
/// This token will be used as a token that user can deposit to mint same amounts
/// of principal and interest shares.
/// @return The underlying yield bearing token.
function yieldBearingToken() external view returns (address);
/// This is the address of the actual backing asset token
/// in the case of ETH, this address will be 0
/// @return Address of the Backing Token
function backingToken() external view returns (address);
/// @return uint256 value of one backing token, in case of 18 decimals 1e18
function backingTokenONE() external view returns (uint256);
/// @return This TempusPool's Tempus Principal Share (TPS)
function principalShare() external view returns (IPoolShare);
/// @return This TempusPool's Tempus Yield Share (TYS)
function yieldShare() external view returns (IPoolShare);
/// @return The TempusController address that is authorized to perform restricted actions
function controller() external view returns (address);
/// @return Start time of the pool.
function startTime() external view returns (uint256);
/// @return Maturity time of the pool.
function maturityTime() external view returns (uint256);
/// @return Time of exceptional halting of the pool.
/// In case the pool is still in operation, this must return type(uint256).max.
function exceptionalHaltTime() external view returns (uint256);
/// @return The maximum allowed time (in seconds) to pass with negative yield.
function maximumNegativeYieldDuration() external view returns (uint256);
/// @return True if maturity has been reached and the pool was finalized.
/// This also includes the case when maturity was triggered due to
/// exceptional conditions (negative yield periods).
function matured() external view returns (bool);
/// Finalizes the pool. This can only happen on or after `maturityTime`.
/// Once finalized depositing is not possible anymore, and the behaviour
/// redemption will change.
///
/// Can be called by anyone and can be called multiple times.
function finalize() external;
/// Yield bearing tokens deposit hook.
/// @notice Deposit will fail if maturity has been reached.
/// @notice This function can only be called by TempusController
/// @notice This function assumes funds were already transferred to the TempusPool from the TempusController
/// @param yieldTokenAmount Amount of yield bearing tokens to deposit in YieldToken decimal precision
/// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS)
/// @return mintedShares Amount of TPS and TYS minted to `recipient`
/// @return depositedBT The YBT value deposited, denominated as Backing Tokens
/// @return fee The fee which was deducted (in terms of YBT)
/// @return rate The interest rate at the time of the deposit
function onDepositYieldBearing(uint256 yieldTokenAmount, address recipient)
external
returns (
uint256 mintedShares,
uint256 depositedBT,
uint256 fee,
uint256 rate
);
/// Backing tokens deposit hook.
/// @notice Deposit will fail if maturity has been reached.
/// @notice This function can only be called by TempusController
/// @notice This function assumes funds were already transferred to the TempusPool from the TempusController
/// @param backingTokenAmount amount of Backing Tokens to be deposited to underlying protocol in BackingToken decimal precision
/// @param recipient Address which will receive Tempus Principal Shares (TPS) and Tempus Yield Shares (TYS)
/// @return mintedShares Amount of TPS and TYS minted to `recipient`
/// @return depositedYBT The BT value deposited, denominated as Yield Bearing Tokens
/// @return fee The fee which was deducted (in terms of YBT)
/// @return rate The interest rate at the time of the deposit
function onDepositBacking(uint256 backingTokenAmount, address recipient)
external
payable
returns (
uint256 mintedShares,
uint256 depositedYBT,
uint256 fee,
uint256 rate
);
/// Redeems yield bearing tokens from this TempusPool
/// msg.sender will receive the YBT
/// NOTE #1 Before maturity, principalAmount must equal to yieldAmount.
/// NOTE #2 This function can only be called by TempusController
/// @param from Address to redeem its Tempus Shares
/// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem for YBT in PrincipalShare decimal precision
/// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem for YBT in YieldShare decimal precision
/// @param recipient Address to which redeemed YBT will be sent
/// @return redeemableYieldTokens Amount of Yield Bearing Tokens redeemed to `recipient`
/// @return fee The fee which was deducted (in terms of YBT)
/// @return rate The interest rate at the time of the redemption
function redeem(
address from,
uint256 principalAmount,
uint256 yieldAmount,
address recipient
)
external
returns (
uint256 redeemableYieldTokens,
uint256 fee,
uint256 rate
);
/// Redeems TPS+TYS held by msg.sender into backing tokens
/// `msg.sender` must approve TPS and TYS amounts to this TempusPool.
/// `msg.sender` will receive the backing tokens
/// NOTE #1 Before maturity, principalAmount must equal to yieldAmount.
/// NOTE #2 This function can only be called by TempusController
/// @param from Address to redeem its Tempus Shares
/// @param principalAmount Amount of Tempus Principal Shares (TPS) to redeem in PrincipalShare decimal precision
/// @param yieldAmount Amount of Tempus Yield Shares (TYS) to redeem in YieldShare decimal precision
/// @param recipient Address to which redeemed BT will be sent
/// @return redeemableYieldTokens Amount of Backing Tokens redeemed to `recipient`, denominated in YBT
/// @return redeemableBackingTokens Amount of Backing Tokens redeemed to `recipient`
/// @return fee The fee which was deducted (in terms of YBT)
/// @return rate The interest rate at the time of the redemption
function redeemToBacking(
address from,
uint256 principalAmount,
uint256 yieldAmount,
address recipient
)
external
payable
returns (
uint256 redeemableYieldTokens,
uint256 redeemableBackingTokens,
uint256 fee,
uint256 rate
);
/// Gets the estimated amount of Principals and Yields after a successful deposit
/// @param amount Amount of BackingTokens or YieldBearingTokens that would be deposited
/// @param isBackingToken If true, @param amount is in BackingTokens, otherwise YieldBearingTokens
/// @return Amount of Principals (TPS) and Yields (TYS) in Principal/YieldShare decimal precision
/// TPS and TYS are minted in 1:1 ratio, hence a single return value.
function estimatedMintedShares(uint256 amount, bool isBackingToken) external view returns (uint256);
/// Gets the estimated amount of YieldBearingTokens or BackingTokens received when calling `redeemXXX()` functions
/// @param principals Amount of Principals (TPS) in PrincipalShare decimal precision
/// @param yields Amount of Yields (TYS) in YieldShare decimal precision
/// @param toBackingToken If true, redeem amount is estimated in BackingTokens instead of YieldBearingTokens
/// @return Amount of YieldBearingTokens or BackingTokens in YBT/BT decimal precision
function estimatedRedeem(
uint256 principals,
uint256 yields,
bool toBackingToken
) external view returns (uint256);
/// @dev This returns the stored Interest Rate of the YBT (Yield Bearing Token) pool
/// it is safe to call this after updateInterestRate() was called
/// @return Stored Interest Rate, decimal precision depends on specific TempusPool implementation
function currentInterestRate() external view returns (uint256);
/// @return Initial interest rate of the underlying pool,
/// decimal precision depends on specific TempusPool implementation
function initialInterestRate() external view returns (uint256);
/// @return Interest rate at maturity of the underlying pool (or 0 if maturity not reached yet)
/// decimal precision depends on specific TempusPool implementation
function maturityInterestRate() external view returns (uint256);
/// @return Rate of one Tempus Yield Share expressed in Asset Tokens
function pricePerYieldShare() external returns (uint256);
/// @return Rate of one Tempus Principal Share expressed in Asset Tokens
function pricePerPrincipalShare() external returns (uint256);
/// Calculated with stored interest rates
/// @return Rate of one Tempus Yield Share expressed in Asset Tokens,
function pricePerYieldShareStored() external view returns (uint256);
/// Calculated with stored interest rates
/// @return Rate of one Tempus Principal Share expressed in Asset Tokens
function pricePerPrincipalShareStored() external view returns (uint256);
/// @dev This returns actual Backing Token amount for amount of YBT (Yield Bearing Tokens)
/// For example, in case of Aave and Lido the result is 1:1,
/// and for compound is `yieldTokens * currentInterestRate`
/// @param yieldTokens Amount of YBT in YBT decimal precision
/// @param interestRate The current interest rate
/// @return Amount of Backing Tokens for specified @param yieldTokens
function numAssetsPerYieldToken(uint yieldTokens, uint interestRate) external view returns (uint);
/// @dev This returns amount of YBT (Yield Bearing Tokens) that can be converted
/// from @param backingTokens Backing Tokens
/// @param backingTokens Amount of Backing Tokens in BT decimal precision
/// @param interestRate The current interest rate
/// @return Amount of YBT for specified @param backingTokens
function numYieldTokensPerAsset(uint backingTokens, uint interestRate) external view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} 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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-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 ERC20 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 {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-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 virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
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 {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-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 virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This 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 virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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 virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This 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 virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.6 <0.9.0;
import "../ITempusPool.sol";
/// Interface of Tokens representing the principal or yield shares of a pool.
interface IPoolShare {
enum ShareKind {
Principal,
Yield
}
/// @return The kind of the share.
function kind() external view returns (ShareKind);
/// @return The pool this share is part of.
function pool() external view returns (ITempusPool);
/// @dev Price per single share expressed in Backing Tokens of the underlying pool.
/// This is for the purpose of TempusAMM api support.
/// Example: exchanging Tempus Yield Share to DAI
/// @return 1e18 decimal conversion rate per share
function getPricePerFullShare() external returns (uint256);
/// @return 1e18 decimal stored conversion rate per share
function getPricePerFullShareStored() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.9.0;
/// Implements Ownable with a two step transfer of ownership
interface IOwnable {
/**
* @dev Change of ownership proposed.
* @param currentOwner The current owner.
* @param proposedOwner The proposed owner.
*/
event OwnershipProposed(address indexed currentOwner, address indexed proposedOwner);
/**
* @dev Ownership transferred.
* @param previousOwner The previous owner.
* @param newOwner The new owner.
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the current owner.
*/
function owner() external view returns (address);
/**
* @dev Proposes a transfer of ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external;
/**
* @dev Accepts ownership of the contract by a proposed account.
* Can only be called by the proposed owner.
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6 <0.9.0;
pragma abicoder v2;
/// Implements versioning
interface IVersioned {
struct Version {
uint16 major;
uint16 minor;
uint16 patch;
}
/// @return The version of the contract.
function version() external view returns (Version memory);
}
|
Creates `amount` new tokens for `to`. account Recipient address to mint tokens to amount Number of tokens to mint
|
function mint(address account, uint256 amount) external {
require(msg.sender == manager, "mint: only manager can mint");
_mint(account, amount);
}
| 404,587
|
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/MeshToken.sol
/**
* CappedToken token is Mintable token with a max cap on totalSupply that can ever be minted.
* PausableToken overrides all transfers methods and adds a modifier to check if paused is set to false.
*/
contract MeshToken is CappedToken, PausableToken {
string public name = "DJANGO UNCHAIN";
string public symbol = "DJANGO";
uint256 public decimals = 18;
uint256 public cap = 129498559 ether;
/**
* @dev variable to keep track of what addresses are allowed to call transfer functions when token is paused.
*/
mapping (address => bool) public allowedTransfers;
/*------------------------------------constructor------------------------------------*/
/**
* @dev constructor for mesh token
*/
function MeshToken() CappedToken(cap) public {
paused = true;
}
/*------------------------------------overridden methods------------------------------------*/
/**
* @dev Overridder modifier to allow exceptions for pausing for a given address
* This modifier is added to all transfer methods by PausableToken and only allows if paused is set to false.
* With this override the function allows either if paused is set to false or msg.sender is allowedTransfers during the pause as well.
*/
modifier whenNotPaused() {
require(!paused || allowedTransfers[msg.sender]);
_;
}
/**
* @dev overriding Pausable#pause method to do nothing
* Paused is set to true in the constructor itself, making the token non-transferrable on deploy.
* once unpaused the contract cannot be paused again.
* adding this to limit owner's ability to pause the token in future.
*/
function pause() onlyOwner whenNotPaused public {}
/**
* @dev modifier created to prevent short address attack problems.
* solution based on this blog post https://blog.coinfabrik.com/smart-contract-short-address-attack-mitigation-failure
*/
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @dev overriding transfer method to include the onlyPayloadSize check modifier
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
return super.transfer(_to, _value);
}
/*------------------------------------new methods------------------------------------*/
/**
* @dev method to updated allowedTransfers for an address
* @param _address that needs to be updated
* @param _allowedTransfers indicating if transfers are allowed or not
* @return boolean indicating function success.
*/
function updateAllowedTransfers(address _address, bool _allowedTransfers)
external
onlyOwner
returns (bool)
{
// don't allow owner to change this for themselves
// otherwise whenNotPaused will not work as expected for owner,
// therefore prohibiting them from calling pause/unpause.
require(_address != owner);
allowedTransfers[_address] = _allowedTransfers;
return true;
}
}
// File: zeppelin-solidity/contracts/crowdsale/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive. The contract requires a MintableToken that will be
* minted as contributions arrive, note that the crowdsale contract
* must be owner of the token in order to be able to mint it.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = _token;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// Override this method to have a way to add business logic to your crowdsale when buying
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
return weiAmount.mul(rate);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
}
// File: zeppelin-solidity/contracts/crowdsale/CappedCrowdsale.sol
/**
* @title CappedCrowdsale
* @dev Extension of Crowdsale with a max amount of funds raised
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= cap;
return capReached || super.hasEnded();
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal view returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return withinCap && super.validPurchase();
}
}
// File: contracts/MeshCrowdsale.sol
/**
* CappedCrowdsale limits the total number of wei that can be collected in the sale.
*/
contract MeshCrowdsale is CappedCrowdsale, Ownable {
using SafeMath for uint256;
/**
* @dev weiLimits keeps track of amount of wei that can be contibuted by an address.
*/
mapping (address => uint256) public weiLimits;
/**
* @dev weiContributions keeps track of amount of wei that are contibuted by an address.
*/
mapping (address => uint256) public weiContributions;
/**
* @dev whitelistingAgents keeps track of who is allowed to call the setLimit method
*/
mapping (address => bool) public whitelistingAgents;
/**
* @dev minimumContribution keeps track of what should be the minimum contribution required per address
*/
uint256 public minimumContribution;
/**
* @dev variable to keep track of beneficiaries for which we need to mint the tokens directly
*/
address[] public beneficiaries;
/**
* @dev variable to keep track of amount of tokens to mint for beneficiaries
*/
uint256[] public beneficiaryAmounts;
/**
* @dev variable to keep track of if predefined tokens have been minted
*/
bool public mintingFinished;
/*---------------------------------constructor---------------------------------*/
/**
* @dev Constructor for MeshCrowdsale contract
*/
function MeshCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumContribution, MeshToken _token, address[] _beneficiaries, uint256[] _beneficiaryAmounts)
CappedCrowdsale(_cap)
Crowdsale(_startTime, _endTime, _rate, _wallet, _token)
public
{
require(_beneficiaries.length == _beneficiaryAmounts.length);
beneficiaries = _beneficiaries;
beneficiaryAmounts = _beneficiaryAmounts;
mintingFinished = false;
minimumContribution = _minimumContribution;
}
/*---------------------------------overridden methods---------------------------------*/
/**
* overriding Crowdsale#buyTokens to keep track of wei contributed per address
*/
function buyTokens(address beneficiary) public payable {
weiContributions[msg.sender] = weiContributions[msg.sender].add(msg.value);
super.buyTokens(beneficiary);
}
/**
* overriding CappedCrowdsale#validPurchase to add extra contribution limit logic
* @return true if investors can buy at the moment
*/
function validPurchase() internal view returns (bool) {
bool withinLimit = weiContributions[msg.sender] <= weiLimits[msg.sender];
bool atleastMinimumContribution = weiContributions[msg.sender] >= minimumContribution;
return atleastMinimumContribution && withinLimit && super.validPurchase();
}
/*---------------------------------new methods---------------------------------*/
/**
* @dev Allows owner to add / remove whitelistingAgents
* @param _address that is being allowed or removed from whitelisting addresses
* @param _value boolean indicating if address is whitelisting agent or not
*/
function setWhitelistingAgent(address _address, bool _value) external onlyOwner {
whitelistingAgents[_address] = _value;
}
/**
* @dev Allows the current owner to update contribution limits
* @param _addresses whose contribution limits should be changed
* @param _weiLimit new contribution limit
*/
function setLimit(address[] _addresses, uint256 _weiLimit) external {
require(whitelistingAgents[msg.sender] == true);
for (uint i = 0; i < _addresses.length; i++) {
address _address = _addresses[i];
// only allow changing the limit to be greater than current contribution
if(_weiLimit >= weiContributions[_address]) {
weiLimits[_address] = _weiLimit;
}
}
}
/**
* @dev Allows the current owner to change the ETH to token generation rate.
* @param _rate indicating the new token generation rate.
*/
function setRate(uint256 _rate) external onlyOwner {
// make sure the crowdsale has not started
require(weiRaised == 0 && now <= startTime);
// make sure new rate is greater than 0
require(_rate > 0);
rate = _rate;
}
/**
* @dev Allows the current owner to change the crowdsale cap.
* @param _cap indicating the new crowdsale cap.
*/
function setCap(uint256 _cap) external onlyOwner {
// make sure the crowdsale has not started
require(weiRaised == 0 && now <= startTime);
// make sure new cap is greater than 0
require(_cap > 0);
cap = _cap;
}
/**
* @dev Allows the current owner to change the required minimum contribution.
* @param _minimumContribution indicating the minimum required contribution.
*/
function setMinimumContribution(uint256 _minimumContribution) external onlyOwner {
minimumContribution = _minimumContribution;
}
/*
* @dev Function to perform minting to predefined beneficiaries once crowdsale has started
* can be called by only once and by owner only
*/
function mintPredefinedTokens() external onlyOwner {
// prevent owner from minting twice
require(!mintingFinished);
// make sure the crowdsale has started
require(weiRaised > 0);
// loop through the list and call mint on token directly
// this minting does not affect any crowdsale numbers
for (uint i = 0; i < beneficiaries.length; i++) {
if (beneficiaries[i] != address(0) && token.balanceOf(beneficiaries[i]) == 0) {
token.mint(beneficiaries[i], beneficiaryAmounts[i]);
}
}
// set it at the end, making sure all transactions have been completed with the gas
mintingFinished = true;
}
/*---------------------------------proxy methods for token when owned by contract---------------------------------*/
/**
* @dev Allows the current owner to transfer token control back to contract owner
*/
function transferTokenOwnership() external onlyOwner {
token.transferOwnership(owner);
}
}
|
Allows the current owner to update contribution limits _addresses whose contribution limits should be changed _weiLimit new contribution limit/ only allow changing the limit to be greater than current contribution
|
function setLimit(address[] _addresses, uint256 _weiLimit) external {
require(whitelistingAgents[msg.sender] == true);
for (uint i = 0; i < _addresses.length; i++) {
address _address = _addresses[i];
if(_weiLimit >= weiContributions[_address]) {
weiLimits[_address] = _weiLimit;
}
}
}
| 1,326,286
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "./IdentityContractLib.sol";
import "./IIdentityContract.sol";
import "./IERC725.sol";
import "./IERC735.sol";
import "./IERC165.sol";
/**
* An IdentityContract represents a user (i.e. a retail user or an authority, but also a distributor contract)
* on the blockchain.
*/
contract IdentityContract is IERC725, IERC735, IIdentityContract, IERC165 {
// Attributes ERC-725
address public owner;
mapping (bytes32 => bytes) public data;
// Attributes ERC-735
mapping (uint256 => IdentityContractLib.Claim) claims;
mapping (uint256 => uint256[]) topics2ClaimIds;
mapping (uint256 => bool) burnedClaimIds;
// Attributes related to ERC-1155
// Energy token contract => token id => (token sender => PerishableValue)
mapping (address => mapping (uint256 => mapping(address => IdentityContractLib.PerishableValue))) public receptionApproval;
// Other attributes
IdentityContract public marketAuthority;
uint32 public balancePeriodLength;
uint256 public executionNonce;
// Modifiers ERC-725
modifier onlyOwner {
require(msg.sender == owner || msg.sender == address(this), "Only owner.");
_;
}
// Events related to ERC-1155
event RequestTransfer(address recipient, address sender, uint256 value, uint64 expiryDate, uint256 tokenId);
// Other events.
event IdentityContractCreation(IdentityContract indexed marketAuthority, IdentityContract identityContract);
/**
* Market authorities need to set _marketAuthority to 0x0 and specify _balancePeriodLength.
* Other IdentityContracts need to specify the Market Authority's address as _marketAuthority. Their specification of _balancePeriodLength will be ignored.
*/
constructor(IdentityContract _marketAuthority, uint32 _balancePeriodLength, address _owner) {
if(_marketAuthority == IdentityContract(address(0))) {
require(3600 % _balancePeriodLength == 0, "Balance period length must be a unit fraction of an hour.");
marketAuthority = this;
balancePeriodLength = _balancePeriodLength;
} else {
marketAuthority = _marketAuthority;
balancePeriodLength = _marketAuthority.balancePeriodLength();
}
owner = _owner;
emit IdentityContractCreation(_marketAuthority, this);
}
// For the definitions of the interface identifiers, see InterfaceIds.sol.
function supportsInterface(bytes4 interfaceID) override(IERC165) external virtual view returns (bool) {
return
interfaceID == 0x01ffc9a7 ||
interfaceID == 0x6f15538d ||
interfaceID == 0x848a042c ||
interfaceID == 0x1fd50459;
}
function selfdestructIdc() override(IIdentityContract) external onlyOwner {
selfdestruct(payable(owner));
}
// Functions ERC-725
function changeOwner(address _owner) override(IIdentityContract) external onlyOwner {
owner = _owner;
}
function getData(bytes32 _key) override(IERC725, IIdentityContract) external view returns (bytes memory __value) {
return data[_key];
}
function setData(bytes32 _key, bytes calldata _value) override(IERC725, IIdentityContract) external onlyOwner {
data[_key] = _value;
emit DataChanged(_key, _value);
}
function execute(uint256 _operationType, address _to, uint256 _value, bytes calldata _data) override(IERC725, IIdentityContract) external onlyOwner {
IdentityContractLib.execute(_operationType, _to, _value, _data);
}
function execute(uint256 _operationType, address _to, uint256 _value, bytes calldata _data, uint256 _executionNonce, bytes calldata _signature) external {
// Limit the number of execution nonces that can be skipped to avoid overflows.
require(_executionNonce >= executionNonce && _executionNonce <= executionNonce + 1e18);
// Increment the stored execution nonce first.
// This prevents attacks where a contract that is called later (e.g. because it receives money) replays the call to the execution function.
executionNonce = _executionNonce + 1;
IdentityContractLib.execute(owner, _executionNonce, _operationType, _to, _value, _data, _signature);
}
// Functions ERC-735
function getClaim(uint256 _claimId) override(IERC735, IIdentityContract) external view returns(uint256 __topic, uint256 __scheme,
address __issuer, bytes memory __signature, bytes memory __data, string memory __uri) {
__topic = claims[_claimId].topic;
__scheme = claims[_claimId].scheme;
__issuer = claims[_claimId].issuer;
__signature = claims[_claimId].signature;
__data = claims[_claimId].data;
__uri = claims[_claimId].uri;
}
function getClaimIdsByTopic(uint256 _topic) override(IERC735, IIdentityContract) external view returns(uint256[] memory __claimIds) {
return topics2ClaimIds[_topic];
}
function addClaim(uint256 _topic, uint256 _scheme, address _issuer, bytes memory _signature, bytes memory _data, string memory _uri)
override(IERC735, IIdentityContract) public returns (uint256 __claimRequestId) {
return IdentityContractLib.addClaim(claims, topics2ClaimIds, burnedClaimIds, marketAuthority, _topic, _scheme, _issuer, _signature, _data, _uri);
}
function removeClaim(uint256 _claimId) override(IERC735, IIdentityContract) external returns (bool __success) {
return IdentityContractLib.removeClaim(owner, claims, topics2ClaimIds, burnedClaimIds, _claimId);
}
function burnClaimId(uint256 _topic) override(IIdentityContract) external {
IdentityContractLib.burnClaimId(burnedClaimIds, _topic);
}
function reinstateClaimId(uint256 _topic) override(IIdentityContract) external {
IdentityContractLib.reinstateClaimId(burnedClaimIds, _topic);
}
// Funtions ERC-1155 and related
function onERC1155Received(address /*_operator*/, address _from, uint256 _id, uint256 _value, bytes calldata /*_data*/) virtual override(IIdentityContract) external returns(bytes4) {
IdentityContractLib.consumeReceptionApproval(receptionApproval, balancePeriodLength, _id, _from, _value);
return 0xf23a6e61;
}
function onERC1155BatchReceived(address /*_operator*/, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata /*_data*/)
virtual override(IIdentityContract) external returns(bytes4) {
for(uint32 i = 0; i < _ids.length; i++) {
IdentityContractLib.consumeReceptionApproval(receptionApproval, balancePeriodLength, _ids[i], _from, _values[i]);
}
return 0xbc197c81;
}
function approveSender(address _energyToken, address _sender, uint64 _expiryDate, uint256 _value, uint256 _id) override(IIdentityContract) external onlyOwner {
receptionApproval[_energyToken][_id][_sender] = IdentityContractLib.PerishableValue(_value, _expiryDate);
emit RequestTransfer(address(this), _sender, _value, _expiryDate, _id);
}
function approveBatchSender(address _energyToken, address _sender, uint64 _expiryDate, uint256[] calldata _values, uint256[] calldata _ids) override(IIdentityContract) external onlyOwner {
require(_values.length < 4294967295, "_values array is too long.");
require(_values.length == _ids.length, "Unequal array lengths.");
for(uint32 i=0; i < _values.length; i++) {
receptionApproval[_energyToken][_ids[i]][_sender] = IdentityContractLib.PerishableValue(_values[i], _expiryDate);
emit RequestTransfer(address(this), _sender, _values[i], _expiryDate, _ids[i]);
}
}
}
|
Funtions ERC-1155 and related
|
function onERC1155Received(address /*_operator*/, address _from, uint256 _id, uint256 _value, bytes calldata /*_data*/) virtual override(IIdentityContract) external returns(bytes4) {
IdentityContractLib.consumeReceptionApproval(receptionApproval, balancePeriodLength, _id, _from, _value);
return 0xf23a6e61;
}
| 1,776,648
|
./partial_match/83/0x7473a3E6f3d7A4F33F59345E971D2d04d1fe299F/sources/Bridge.sol
|
Verifies that the given data is a valid data on BandChain as of the relayed block height. blockHeight The block height. Someone must already relay this block. count The requests count on the block. version Lastest block height that the data node was updated. merklePaths Merkle proof that shows how the data leave is part of the oracle iAVL. Encode and calculate hash of count Verify proof
|
function verifyRequestsCount(
uint256 blockHeight,
uint256 count,
uint256 version,
IAVLMerklePath.Data[] memory merklePaths
) public view returns (uint64, uint64) {
BlockDetail memory blockDetail = blockDetails[blockHeight];
bytes32 oracleStateRoot = blockDetail.oracleState;
require(
oracleStateRoot != bytes32(uint256(0)),
"NO_ORACLE_ROOT_STATE_DATA"
);
bytes32 dataHash = sha256(abi.encodePacked(uint64(count)));
require(
verifyProof(
oracleStateRoot,
version,
hex"0052657175657374436f756e74",
dataHash,
merklePaths
),
"INVALID_ORACLE_DATA_PROOF"
);
return (blockDetail.timeSecond, uint64(count));
}
| 8,828,958
|
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {BridgeRouter} from "./BridgeRouter.sol";
import {IWeth} from "../../interfaces/bridge/IWeth.sol";
// ============ External Imports ============
import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol";
contract ETHHelper {
// ============ Immutables ============
// wrapped Ether contract
IWeth public immutable weth;
// bridge router contract
BridgeRouter public immutable bridge;
// ============ Constructor ============
constructor(address _weth, address _bridge) {
weth = IWeth(_weth);
bridge = BridgeRouter(_bridge);
IWeth(_weth).approve(_bridge, uint256(-1));
}
// ============ External Functions ============
/**
* @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics
* identifer on the other side.
* @dev As with all bridges, improper use may result in loss of funds.
* @param _domain The domain to send funds to.
* @param _to The 32-byte identifier of the recipient
*/
function sendTo(uint32 _domain, bytes32 _to) public payable {
weth.deposit{value: msg.value}();
bridge.send(address(weth), msg.value, _domain, _to);
}
/**
* @notice Sends ETH over the Optics Bridge. Sends to the same address on
* the other side.
* @dev WARNING: This function should only be used when sending TO an
* EVM-like domain. As with all bridges, improper use may result in loss of
* funds.
* @param _domain The domain to send funds to
*/
function send(uint32 _domain) external payable {
sendTo(_domain, TypeCasts.addressToBytes32(msg.sender));
}
/**
* @notice Sends ETH over the Optics Bridge. Sends to a specified EVM
* address on the other side.
* @dev This function should only be used when sending TO an EVM-like
* domain. As with all bridges, improper use may result in loss of funds
* @param _domain The domain to send funds to.
* @param _to The EVM address of the recipient
*/
function sendToEVMLike(uint32 _domain, address _to) external payable {
sendTo(_domain, TypeCasts.addressToBytes32(_to));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {TokenRegistry} from "./TokenRegistry.sol";
import {Router} from "../Router.sol";
import {XAppConnectionClient} from "../XAppConnectionClient.sol";
import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol";
import {BridgeMessage} from "./BridgeMessage.sol";
// ============ External Imports ============
import {Home} from "@celo-org/optics-sol/contracts/Home.sol";
import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol";
import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol";
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title BridgeRouter
*/
contract BridgeRouter is Version0, Router, TokenRegistry {
// ============ Libraries ============
using TypedMemView for bytes;
using TypedMemView for bytes29;
using BridgeMessage for bytes29;
using SafeERC20 for IERC20;
// ============ Constants ============
// 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade
uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995;
uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000;
// ============ Public Storage ============
// token transfer prefill ID => LP that pre-filled message to provide fast liquidity
mapping(bytes32 => address) public liquidityProvider;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ======== Events =========
/**
* @notice emitted when tokens are sent from this domain to another domain
* @param token the address of the token contract
* @param from the address sending tokens
* @param toDomain the domain of the chain the tokens are being sent to
* @param toId the bytes32 address of the recipient of the tokens
* @param amount the amount of tokens sent
*/
event Send(
address indexed token,
address indexed from,
uint32 indexed toDomain,
bytes32 toId,
uint256 amount
);
// ======== Initializer ========
function initialize(address _tokenBeacon, address _xAppConnectionManager)
public
initializer
{
__TokenRegistry_initialize(_tokenBeacon);
__XAppConnectionClient_initialize(_xAppConnectionManager);
}
// ======== External: Handle =========
/**
* @notice Handles an incoming message
* @param _origin The origin domain
* @param _sender The sender address
* @param _message The message
*/
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external override onlyReplica onlyRemoteRouter(_origin, _sender) {
// parse tokenId and action from message
bytes29 _msg = _message.ref(0).mustBeMessage();
bytes29 _tokenId = _msg.tokenId();
bytes29 _action = _msg.action();
// handle message based on the intended action
if (_action.isTransfer()) {
_handleTransfer(_tokenId, _action);
} else if (_action.isDetails()) {
_handleDetails(_tokenId, _action);
} else if (_action.isRequestDetails()) {
_handleRequestDetails(_origin, _sender, _tokenId);
} else {
require(false, "!valid action");
}
}
// ======== External: Request Token Details =========
/**
* @notice Request updated token metadata from another chain
* @dev This is only owner to prevent abuse and spam. Requesting details
* should be done automatically on token instantiation
* @param _domain The domain where that token is native
* @param _id The token id on that domain
*/
function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner {
bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id);
_requestDetails(_tokenId);
}
// ======== External: Send Token =========
/**
* @notice Send tokens to a recipient on a remote chain
* @param _token The token address
* @param _amount The token amount
* @param _destination The destination domain
* @param _recipient The recipient address
*/
function send(
address _token,
uint256 _amount,
uint32 _destination,
bytes32 _recipient
) external {
require(_amount > 0, "!amnt");
require(_recipient != bytes32(0), "!recip");
// get remote BridgeRouter address; revert if not found
bytes32 _remote = _mustHaveRemote(_destination);
// remove tokens from circulation on this chain
IERC20 _bridgeToken = IERC20(_token);
if (_isLocalOrigin(_bridgeToken)) {
// if the token originates on this chain, hold the tokens in escrow
// in the Router
_bridgeToken.safeTransferFrom(msg.sender, address(this), _amount);
} else {
// if the token originates on a remote chain, burn the
// representation tokens on this chain
_downcast(_bridgeToken).burn(msg.sender, _amount);
}
// format Transfer Tokens action
bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount);
// send message to remote chain via Optics
Home(xAppConnectionManager.home()).dispatch(
_destination,
_remote,
BridgeMessage.formatMessage(_formatTokenId(_token), _action)
);
// emit Send event to record token sender
emit Send(
address(_bridgeToken),
msg.sender,
_destination,
_recipient,
_amount
);
}
// ======== External: Fast Liquidity =========
/**
* @notice Allows a liquidity provider to give an
* end user fast liquidity by pre-filling an
* incoming transfer message.
* Transfers tokens from the liquidity provider to the end recipient, minus the LP fee;
* Records the liquidity provider, who receives
* the full token amount when the transfer message is handled.
* @dev fast liquidity can only be provided for ONE token transfer
* with the same (recipient, amount) at a time.
* in the case that multiple token transfers with the same (recipient, amount)
* @param _message The incoming transfer message to pre-fill
*/
function preFill(bytes calldata _message) external {
// parse tokenId and action from message
bytes29 _msg = _message.ref(0).mustBeMessage();
bytes29 _tokenId = _msg.tokenId().mustBeTokenId();
bytes29 _action = _msg.action().mustBeTransfer();
// calculate prefill ID
bytes32 _id = _preFillId(_tokenId, _action);
// require that transfer has not already been pre-filled
require(liquidityProvider[_id] == address(0), "!unfilled");
// record liquidity provider
liquidityProvider[_id] = msg.sender;
// transfer tokens from liquidity provider to token recipient
IERC20 _token = _mustHaveToken(_tokenId);
_token.safeTransferFrom(
msg.sender,
_action.evmRecipient(),
_applyPreFillFee(_action.amnt())
);
}
// ======== External: Custom Tokens =========
/**
* @notice Enroll a custom token. This allows projects to work with
* governance to specify a custom representation.
* @dev This is done by inserting the custom representation into the token
* lookup tables. It is permissioned to the owner (governance) and can
* potentially break token representations. It must be used with extreme
* caution.
* After the token is inserted, new mint instructions will be sent to the
* custom token. The default representation (and old custom representations)
* may still be burnt. Until all users have explicitly called migrate, both
* representations will continue to exist.
* The custom representation MUST be trusted, and MUST allow the router to
* both mint AND burn tokens at will.
* @param _id the canonical ID of the Token to enroll, as a byte vector
* @param _custom the address of the custom implementation to use.
*/
function enrollCustom(
uint32 _domain,
bytes32 _id,
address _custom
) external onlyOwner {
// Sanity check. Ensures that human error doesn't cause an
// unpermissioned contract to be enrolled.
IBridgeToken(_custom).mint(address(this), 1);
IBridgeToken(_custom).burn(address(this), 1);
// update mappings with custom token
bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id);
representationToCanonical[_custom].domain = _tokenId.domain();
representationToCanonical[_custom].id = _tokenId.id();
bytes32 _idHash = _tokenId.keccak();
canonicalToRepresentation[_idHash] = _custom;
}
/**
* @notice Migrate all tokens in a previous representation to the latest
* custom representation. This works by looking up local mappings and then
* burning old tokens and minting new tokens.
* @dev This is explicitly opt-in to allow dapps to decide when and how to
* upgrade to the new representation.
* @param _oldRepr The address of the old token to migrate
*/
function migrate(address _oldRepr) external {
// get the token ID for the old token contract
TokenId memory _id = representationToCanonical[_oldRepr];
require(_id.domain != 0, "!repr");
// ensure that new token & old token are different
IBridgeToken _old = IBridgeToken(_oldRepr);
IBridgeToken _new = _representationForCanonical(_id);
require(_new != _old, "!different");
// burn the old tokens & mint the new ones
uint256 _bal = _old.balanceOf(msg.sender);
_old.burn(msg.sender, _bal);
_new.mint(msg.sender, _bal);
}
// ============ Internal: Send / UpdateDetails ============
/**
* @notice Given a tokenAddress, format the tokenId
* identifier for the message.
* @param _token The token address
* @param _tokenId The bytes-encoded tokenId
*/
function _formatTokenId(address _token)
internal
view
returns (bytes29 _tokenId)
{
TokenId memory _tokId = _tokenIdFor(_token);
_tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id);
}
// ============ Internal: Handle ============
/**
* @notice Handles an incoming Transfer message.
*
* If the token is of local origin, the amount is sent from escrow.
* Otherwise, a representation token is minted.
*
* @param _tokenId The token ID
* @param _action The action
*/
function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal {
// get the token contract for the given tokenId on this chain;
// (if the token is of remote origin and there is
// no existing representation token contract, the TokenRegistry will
// deploy a new one)
IERC20 _token = _ensureToken(_tokenId);
address _recipient = _action.evmRecipient();
// If an LP has prefilled this token transfer,
// send the tokens to the LP instead of the recipient
bytes32 _id = _preFillId(_tokenId, _action);
address _lp = liquidityProvider[_id];
if (_lp != address(0)) {
_recipient = _lp;
delete liquidityProvider[_id];
}
// send the tokens into circulation on this chain
if (_isLocalOrigin(_token)) {
// if the token is of local origin, the tokens have been held in
// escrow in this contract
// while they have been circulating on remote chains;
// transfer the tokens to the recipient
_token.safeTransfer(_recipient, _action.amnt());
} else {
// if the token is of remote origin, mint the tokens to the
// recipient on this chain
_downcast(_token).mint(_recipient, _action.amnt());
}
}
/**
* @notice Handles an incoming Details message.
* @param _tokenId The token ID
* @param _action The action
*/
function _handleDetails(bytes29 _tokenId, bytes29 _action) internal {
// get the token contract deployed on this chain
// revert if no token contract exists
IERC20 _token = _mustHaveToken(_tokenId);
// require that the token is of remote origin
// (otherwise, the BridgeRouter did not deploy the token contract,
// and therefore cannot update its metadata)
require(!_isLocalOrigin(_token), "!remote origin");
// update the token metadata
_downcast(_token).setDetails(
TypeCasts.coerceString(_action.name()),
TypeCasts.coerceString(_action.symbol()),
_action.decimals()
);
}
/**
* @notice Handles an incoming RequestDetails message by sending an
* UpdateDetails message to the remote chain
* @dev The origin and remote are pre-checked by the handle function
* `onlyRemoteRouter` modifier and can be used without additional check
* @param _messageOrigin The domain from which the message arrived
* @param _messageRemoteRouter The remote router that sent the message
* @param _tokenId The token ID
*/
function _handleRequestDetails(
uint32 _messageOrigin,
bytes32 _messageRemoteRouter,
bytes29 _tokenId
) internal {
// get token & ensure is of local origin
address _token = _tokenId.evmId();
require(_isLocalOrigin(_token), "!local origin");
IBridgeToken _bridgeToken = IBridgeToken(_token);
// format Update Details message
bytes29 _updateDetailsAction = BridgeMessage.formatDetails(
TypeCasts.coerceBytes32(_bridgeToken.name()),
TypeCasts.coerceBytes32(_bridgeToken.symbol()),
_bridgeToken.decimals()
);
// send message to remote chain via Optics
Home(xAppConnectionManager.home()).dispatch(
_messageOrigin,
_messageRemoteRouter,
BridgeMessage.formatMessage(_tokenId, _updateDetailsAction)
);
}
// ============ Internal: Transfer ============
function _ensureToken(bytes29 _tokenId) internal returns (IERC20) {
address _local = _getTokenAddress(_tokenId);
if (_local == address(0)) {
// Representation does not exist yet;
// deploy representation contract
_local = _deployToken(_tokenId);
// message the origin domain
// to request the token details
_requestDetails(_tokenId);
}
return IERC20(_local);
}
// ============ Internal: Request Details ============
/**
* @notice Handles an incoming Details message.
* @param _tokenId The token ID
*/
function _requestDetails(bytes29 _tokenId) internal {
uint32 _destination = _tokenId.domain();
// get remote BridgeRouter address; revert if not found
bytes32 _remote = remotes[_destination];
if (_remote == bytes32(0)) {
return;
}
// format Request Details message
bytes29 _action = BridgeMessage.formatRequestDetails();
// send message to remote chain via Optics
Home(xAppConnectionManager.home()).dispatch(
_destination,
_remote,
BridgeMessage.formatMessage(_tokenId, _action)
);
}
// ============ Internal: Fast Liquidity ============
/**
* @notice Calculate the token amount after
* taking a 5 bps (0.05%) liquidity provider fee
* @param _amnt The token amount before the fee is taken
* @return _amtAfterFee The token amount after the fee is taken
*/
function _applyPreFillFee(uint256 _amnt)
internal
pure
returns (uint256 _amtAfterFee)
{
// overflow only possible if (2**256 / 9995) tokens sent once
// in which case, probably not a real token
_amtAfterFee =
(_amnt * PRE_FILL_FEE_NUMERATOR) /
PRE_FILL_FEE_DENOMINATOR;
}
/**
* @notice get the prefillId used to identify
* fast liquidity provision for incoming token send messages
* @dev used to identify a token/transfer pair in the prefill LP mapping.
* NOTE: This approach has a weakness: a user can receive >1 batch of tokens of
* the same size, but only 1 will be eligible for fast liquidity. The
* other may only be filled at regular speed. This is because the messages
* will have identical `tokenId` and `action` fields. This seems fine,
* tbqh. A delay of a few hours on a corner case is acceptable in v1.
* @param _tokenId The token ID
* @param _action The action
*/
function _preFillId(bytes29 _tokenId, bytes29 _action)
internal
view
returns (bytes32)
{
bytes29[] memory _views = new bytes29[](2);
_views[0] = _tokenId;
_views[1] = _action;
return TypedMemView.joinKeccak(_views);
}
/**
* @dev explicit override for compiler inheritance
* @dev explicit override for compiler inheritance
* @return domain of chain on which the contract is deployed
*/
function _localDomain()
internal
view
override(TokenRegistry, XAppConnectionClient)
returns (uint32)
{
return XAppConnectionClient._localDomain();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IWeth {
function deposit() external payable;
function approve(address _who, uint256 _wad) external;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Home} from "./Home.sol";
import {Replica} from "./Replica.sol";
import {TypeCasts} from "../libs/TypeCasts.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title XAppConnectionManager
* @author Celo Labs Inc.
* @notice Manages a registry of local Replica contracts
* for remote Home domains. Accepts Watcher signatures
* to un-enroll Replicas attached to fraudulent remote Homes
*/
contract XAppConnectionManager is Ownable {
// ============ Public Storage ============
// Home contract
Home public home;
// local Replica address => remote Home domain
mapping(address => uint32) public replicaToDomain;
// remote Home domain => local Replica address
mapping(uint32 => address) public domainToReplica;
// watcher address => replica remote domain => has/doesn't have permission
mapping(address => mapping(uint32 => bool)) private watcherPermissions;
// ============ Events ============
/**
* @notice Emitted when a new Replica is enrolled / added
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaEnrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when a new Replica is un-enrolled / removed
* @param domain the remote domain of the Home contract for the Replica
* @param replica the address of the Replica
*/
event ReplicaUnenrolled(uint32 indexed domain, address replica);
/**
* @notice Emitted when Watcher permissions are changed
* @param domain the remote domain of the Home contract for the Replica
* @param watcher the address of the Watcher
* @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed
*/
event WatcherPermissionSet(
uint32 indexed domain,
address watcher,
bool access
);
// ============ Modifiers ============
modifier onlyReplica() {
require(isReplica(msg.sender), "!replica");
_;
}
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor() Ownable() {}
// ============ External Functions ============
/**
* @notice Un-Enroll a replica contract
* in the case that fraud was detected on the Home
* @dev in the future, if fraud occurs on the Home contract,
* the Watcher will submit their signature directly to the Home
* and it can be relayed to all remote chains to un-enroll the Replicas
* @param _domain the remote domain of the Home contract for the Replica
* @param _updater the address of the Updater for the Home contract (also stored on Replica)
* @param _signature signature of watcher on (domain, replica address, updater address)
*/
function unenrollReplica(
uint32 _domain,
bytes32 _updater,
bytes memory _signature
) external {
// ensure that the replica is currently set
address _replica = domainToReplica[_domain];
require(_replica != address(0), "!replica exists");
// ensure that the signature is on the proper updater
require(
Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater),
"!current updater"
);
// get the watcher address from the signature
// and ensure that the watcher has permission to un-enroll this replica
address _watcher = _recoverWatcherFromSig(
_domain,
TypeCasts.addressToBytes32(_replica),
_updater,
_signature
);
require(watcherPermissions[_watcher][_domain], "!valid watcher");
// remove the replica from mappings
_unenrollReplica(_replica);
}
/**
* @notice Set the address of the local Home contract
* @param _home the address of the local Home contract
*/
function setHome(address _home) external onlyOwner {
home = Home(_home);
}
/**
* @notice Allow Owner to enroll Replica contract
* @param _replica the address of the Replica
* @param _domain the remote domain of the Home contract for the Replica
*/
function ownerEnrollReplica(address _replica, uint32 _domain)
external
onlyOwner
{
// un-enroll any existing replica
_unenrollReplica(_replica);
// add replica and domain to two-way mapping
replicaToDomain[_replica] = _domain;
domainToReplica[_domain] = _replica;
emit ReplicaEnrolled(_domain, _replica);
}
/**
* @notice Allow Owner to un-enroll Replica contract
* @param _replica the address of the Replica
*/
function ownerUnenrollReplica(address _replica) external onlyOwner {
_unenrollReplica(_replica);
}
/**
* @notice Allow Owner to set Watcher permissions for a Replica
* @param _watcher the address of the Watcher
* @param _domain the remote domain of the Home contract for the Replica
* @param _access TRUE to give the Watcher permissions, FALSE to remove permissions
*/
function setWatcherPermission(
address _watcher,
uint32 _domain,
bool _access
) external onlyOwner {
watcherPermissions[_watcher][_domain] = _access;
emit WatcherPermissionSet(_domain, _watcher, _access);
}
/**
* @notice Query local domain from Home
* @return local domain
*/
function localDomain() external view returns (uint32) {
return home.localDomain();
}
/**
* @notice Get access permissions for the watcher on the domain
* @param _watcher the address of the watcher
* @param _domain the domain to check for watcher permissions
* @return TRUE iff _watcher has permission to un-enroll replicas on _domain
*/
function watcherPermission(address _watcher, uint32 _domain)
external
view
returns (bool)
{
return watcherPermissions[_watcher][_domain];
}
// ============ Public Functions ============
/**
* @notice Check whether _replica is enrolled
* @param _replica the replica to check for enrollment
* @return TRUE iff _replica is enrolled
*/
function isReplica(address _replica) public view returns (bool) {
return replicaToDomain[_replica] != 0;
}
// ============ Internal Functions ============
/**
* @notice Remove the replica from the two-way mappings
* @param _replica replica to un-enroll
*/
function _unenrollReplica(address _replica) internal {
uint32 _currentDomain = replicaToDomain[_replica];
domainToReplica[_currentDomain] = address(0);
replicaToDomain[_replica] = 0;
emit ReplicaUnenrolled(_currentDomain, _replica);
}
/**
* @notice Get the Watcher address from the provided signature
* @return address of watcher that signed
*/
function _recoverWatcherFromSig(
uint32 _domain,
bytes32 _replica,
bytes32 _updater,
bytes memory _signature
) internal view returns (address) {
bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica))
.homeDomainHash();
bytes32 _digest = keccak256(
abi.encodePacked(_homeDomainHash, _domain, _updater)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return ECDSA.recover(_digest, _signature);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {BridgeMessage} from "./BridgeMessage.sol";
import {Encoding} from "./Encoding.sol";
import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol";
import {XAppConnectionClient} from "../XAppConnectionClient.sol";
// ============ External Imports ============
import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol";
import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title TokenRegistry
* @notice manages a registry of token contracts on this chain
* -
* We sort token types as "representation token" or "locally originating token".
* Locally originating - a token contract that was originally deployed on the local chain
* Representation (repr) - a token that was originally deployed on some other chain
* -
* When the router handles an incoming message, it determines whether the
* transfer is for an asset of local origin. If not, it checks for an existing
* representation contract. If no such representation exists, it deploys a new
* representation contract. It then stores the relationship in the
* "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always
* perform a lookup in either direction
* Note that locally originating tokens should NEVER be represented in these lookup tables.
*/
abstract contract TokenRegistry is Initializable {
// ============ Libraries ============
using TypedMemView for bytes;
using TypedMemView for bytes29;
using BridgeMessage for bytes29;
// ============ Structs ============
// Tokens are identified by a TokenId:
// domain - 4 byte chain ID of the chain from which the token originates
// id - 32 byte identifier of the token address on the origin chain, in that chain's address format
struct TokenId {
uint32 domain;
bytes32 id;
}
// ============ Public Storage ============
// UpgradeBeacon from which new token proxies will get their implementation
address public tokenBeacon;
// local representation token address => token ID
mapping(address => TokenId) public representationToCanonical;
// hash of the tightly-packed TokenId => local representation token address
// If the token is of local origin, this MUST map to address(0).
mapping(bytes32 => address) public canonicalToRepresentation;
// ============ Events ============
event TokenDeployed(
uint32 indexed domain,
bytes32 indexed id,
address indexed representation
);
// ======== Initializer =========
/**
* @notice Initialize the TokenRegistry with UpgradeBeaconController and
* XappConnectionManager.
* @dev This method deploys two new contracts, and may be expensive to call.
* @param _tokenBeacon The address of the upgrade beacon for bridge token
* proxies
*/
function __TokenRegistry_initialize(address _tokenBeacon)
internal
initializer
{
tokenBeacon = _tokenBeacon;
}
// ======== External: Token Lookup Convenience =========
/**
* @notice Looks up the canonical identifier for a local representation.
* @dev If no such canonical ID is known, this instead returns (0, bytes32(0))
* @param _local The local address of the representation
*/
function getCanonicalAddress(address _local)
external
view
returns (uint32 _domain, bytes32 _id)
{
TokenId memory _canonical = representationToCanonical[_local];
_domain = _canonical.domain;
_id = _canonical.id;
}
/**
* @notice Looks up the local address corresponding to a domain/id pair.
* @dev If the token is local, it will return the local address.
* If the token is non-local and no local representation exists, this
* will return `address(0)`.
* @param _domain the domain of the canonical version.
* @param _id the identifier of the canonical version in its domain.
* @return _token the local address of the token contract
*/
function getLocalAddress(uint32 _domain, address _id)
external
view
returns (address _token)
{
_token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id));
}
// ======== Public: Token Lookup Convenience =========
/**
* @notice Looks up the local address corresponding to a domain/id pair.
* @dev If the token is local, it will return the local address.
* If the token is non-local and no local representation exists, this
* will return `address(0)`.
* @param _domain the domain of the canonical version.
* @param _id the identifier of the canonical version in its domain.
* @return _token the local address of the token contract
*/
function getLocalAddress(uint32 _domain, bytes32 _id)
public
view
returns (address _token)
{
_token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id));
}
// ======== Internal Functions =========
function _localDomain() internal view virtual returns (uint32);
/**
* @notice Get default name and details for a token
* Sets name to "optics.[domain].[id]"
* and symbol to
* @param _tokenId the tokenId for the token
*/
function _defaultDetails(bytes29 _tokenId)
internal
pure
returns (string memory _name, string memory _symbol)
{
// get the first and second half of the token ID
(, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id()));
// encode the default token name: "[decimal domain].[hex 4 bytes of ID]"
_name = string(
abi.encodePacked(
Encoding.decimalUint32(_tokenId.domain()), // 10
".", // 1
uint32(_secondHalfId) // 4
)
);
// allocate the memory for a new 32-byte string
_symbol = new string(10 + 1 + 4);
assembly {
mstore(add(_symbol, 0x20), mload(add(_name, 0x20)))
}
}
/**
* @notice Deploy and initialize a new token contract
* @dev Each token contract is a proxy which
* points to the token upgrade beacon
* @return _token the address of the token contract
*/
function _deployToken(bytes29 _tokenId) internal returns (address _token) {
// deploy and initialize the token contract
_token = address(new UpgradeBeaconProxy(tokenBeacon, ""));
// initialize the token separately from the
IBridgeToken(_token).initialize();
// set the default token name & symbol
string memory _name;
string memory _symbol;
(_name, _symbol) = _defaultDetails(_tokenId);
IBridgeToken(_token).setDetails(_name, _symbol, 18);
// store token in mappings
representationToCanonical[_token].domain = _tokenId.domain();
representationToCanonical[_token].id = _tokenId.id();
canonicalToRepresentation[_tokenId.keccak()] = _token;
// emit event upon deploying new token
emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token);
}
/**
* @notice Get the local token address
* for the canonical token represented by tokenID
* Returns address(0) if canonical token is of remote origin
* and no representation token has been deployed locally
* @param _tokenId the token id of the canonical token
* @return _local the local token address
*/
function _getTokenAddress(bytes29 _tokenId)
internal
view
returns (address _local)
{
if (_tokenId.domain() == _localDomain()) {
// Token is of local origin
_local = _tokenId.evmId();
} else {
// Token is a representation of a token of remote origin
_local = canonicalToRepresentation[_tokenId.keccak()];
}
}
/**
* @notice Return the local token contract for the
* canonical tokenId; revert if there is no local token
* @param _tokenId the token id of the canonical token
* @return the IERC20 token contract
*/
function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) {
address _local = _getTokenAddress(_tokenId);
require(_local != address(0), "!token");
return IERC20(_local);
}
/**
* @notice Return tokenId for a local token address
* @param _token local token address (representation or canonical)
* @return _id local token address (representation or canonical)
*/
function _tokenIdFor(address _token)
internal
view
returns (TokenId memory _id)
{
_id = representationToCanonical[_token];
if (_id.domain == 0) {
_id.domain = _localDomain();
_id.id = TypeCasts.addressToBytes32(_token);
}
}
/**
* @notice Determine if token is of local origin
* @return TRUE if token is locally originating
*/
function _isLocalOrigin(IERC20 _token) internal view returns (bool) {
return _isLocalOrigin(address(_token));
}
/**
* @notice Determine if token is of local origin
* @return TRUE if token is locally originating
*/
function _isLocalOrigin(address _token) internal view returns (bool) {
// If the contract WAS deployed by the TokenRegistry,
// it will be stored in this mapping.
// If so, it IS NOT of local origin
if (representationToCanonical[_token].domain != 0) {
return false;
}
// If the contract WAS NOT deployed by the TokenRegistry,
// and the contract exists, then it IS of local origin
// Return true if code exists at _addr
uint256 _codeSize;
// solhint-disable-next-line no-inline-assembly
assembly {
_codeSize := extcodesize(_token)
}
return _codeSize != 0;
}
/**
* @notice Get the local representation contract for a canonical token
* @dev Returns contract with null address if tokenId has no representation
* @param _tokenId the tokenId of the canonical token
* @return representation token contract
*/
function _representationForCanonical(bytes29 _tokenId)
internal
view
returns (IBridgeToken)
{
return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]);
}
/**
* @notice Get the local representation contract for a canonical token
* @dev Returns contract with null address if tokenId has no representation
* @param _tokenId the tokenId of the canonical token
* @return representation token contract
*/
function _representationForCanonical(TokenId memory _tokenId)
internal
view
returns (IBridgeToken)
{
return _representationForCanonical(_serializeId(_tokenId));
}
/**
* @notice downcast an IERC20 to an IBridgeToken
* @dev Unsafe. Please know what you're doing
* @param _token the IERC20 contract
* @return the IBridgeToken contract
*/
function _downcast(IERC20 _token) internal pure returns (IBridgeToken) {
return IBridgeToken(address(_token));
}
/**
* @notice serialize a TokenId struct into a bytes view
* @param _id the tokenId
* @return serialized bytes of tokenId
*/
function _serializeId(TokenId memory _id) internal pure returns (bytes29) {
return BridgeMessage.formatTokenId(_id.domain, _id.id);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {XAppConnectionClient} from "./XAppConnectionClient.sol";
// ============ External Imports ============
import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol";
abstract contract Router is XAppConnectionClient, IMessageRecipient {
// ============ Mutable Storage ============
mapping(uint32 => bytes32) public remotes;
uint256[49] private __GAP; // gap for upgrade safety
// ============ Modifiers ============
/**
* @notice Only accept messages from a remote Router contract
* @param _origin The domain the message is coming from
* @param _router The address the message is coming from
*/
modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) {
require(_isRemoteRouter(_origin, _router), "!remote router");
_;
}
// ============ External functions ============
/**
* @notice Register the address of a Router contract for the same xApp on a remote chain
* @param _domain The domain of the remote xApp Router
* @param _router The address of the remote xApp Router
*/
function enrollRemoteRouter(uint32 _domain, bytes32 _router)
external
onlyOwner
{
remotes[_domain] = _router;
}
// ============ Virtual functions ============
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external virtual override;
// ============ Internal functions ============
/**
* @notice Return true if the given domain / router is the address of a remote xApp Router
* @param _domain The domain of the potential remote xApp Router
* @param _router The address of the potential remote xApp Router
*/
function _isRemoteRouter(uint32 _domain, bytes32 _router)
internal
view
returns (bool)
{
return remotes[_domain] == _router;
}
/**
* @notice Assert that the given domain has a xApp Router registered and return its address
* @param _domain The domain of the chain for which to get the xApp Router
* @return _remote The address of the remote xApp Router on _domain
*/
function _mustHaveRemote(uint32 _domain)
internal
view
returns (bytes32 _remote)
{
_remote = remotes[_domain];
require(_remote != bytes32(0), "!remote");
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ External Imports ============
import {Home} from "@celo-org/optics-sol/contracts/Home.sol";
import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
abstract contract XAppConnectionClient is OwnableUpgradeable {
// ============ Mutable Storage ============
XAppConnectionManager public xAppConnectionManager;
uint256[49] private __GAP; // gap for upgrade safety
// ============ Modifiers ============
/**
* @notice Only accept messages from an Optics Replica contract
*/
modifier onlyReplica() {
require(_isReplica(msg.sender), "!replica");
_;
}
// ======== Initializer =========
function __XAppConnectionClient_initialize(address _xAppConnectionManager)
internal
initializer
{
xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager);
__Ownable_init();
}
// ============ External functions ============
/**
* @notice Modify the contract the xApp uses to validate Replica contracts
* @param _xAppConnectionManager The address of the xAppConnectionManager contract
*/
function setXAppConnectionManager(address _xAppConnectionManager)
external
onlyOwner
{
xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager);
}
// ============ Internal functions ============
/**
* @notice Get the local Home contract from the xAppConnectionManager
* @return The local Home contract
*/
function _home() internal view returns (Home) {
return xAppConnectionManager.home();
}
/**
* @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager
* @return True if _potentialReplica is an enrolled Replica
*/
function _isReplica(address _potentialReplica)
internal
view
returns (bool)
{
return xAppConnectionManager.isReplica(_potentialReplica);
}
/**
* @notice Get the local domain from the xAppConnectionManager
* @return The local domain
*/
function _localDomain() internal view virtual returns (uint32) {
return xAppConnectionManager.localDomain();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IBridgeToken {
function initialize() external;
function name() external returns (string memory);
function balanceOf(address _account) external view returns (uint256);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function burn(address _from, uint256 _amnt) external;
function mint(address _to, uint256 _amnt) external;
function setDetails(
string calldata _name,
string calldata _symbol,
uint8 _decimals
) external;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library BridgeMessage {
// ============ Libraries ============
using TypedMemView for bytes;
using TypedMemView for bytes29;
// ============ Enums ============
// WARNING: do NOT re-write the numbers / order
// of message types in an upgrade;
// will cause in-flight messages to be mis-interpreted
enum Types {
Invalid, // 0
TokenId, // 1
Message, // 2
Transfer, // 3
Details, // 4
RequestDetails // 5
}
// ============ Constants ============
uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id
uint256 private constant IDENTIFIER_LEN = 1;
uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount
uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals
uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier
// ============ Modifiers ============
/**
* @notice Asserts a message is of type `_t`
* @param _view The message
* @param _t The expected type
*/
modifier typeAssert(bytes29 _view, Types _t) {
_view.assertType(uint40(_t));
_;
}
// ============ Internal Functions ============
/**
* @notice Checks that Action is valid type
* @param _action The action
* @return TRUE if action is valid
*/
function isValidAction(bytes29 _action) internal pure returns (bool) {
return
isDetails(_action) ||
isRequestDetails(_action) ||
isTransfer(_action);
}
/**
* @notice Checks that view is a valid message length
* @param _view The bytes string
* @return TRUE if message is valid
*/
function isValidMessageLength(bytes29 _view) internal pure returns (bool) {
uint256 _len = _view.len();
return
_len == TOKEN_ID_LEN + TRANSFER_LEN ||
_len == TOKEN_ID_LEN + DETAILS_LEN ||
_len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN;
}
/**
* @notice Formats an action message
* @param _tokenId The token ID
* @param _action The action
* @return The formatted message
*/
function formatMessage(bytes29 _tokenId, bytes29 _action)
internal
view
typeAssert(_tokenId, Types.TokenId)
returns (bytes memory)
{
require(isValidAction(_action), "!action");
bytes29[] memory _views = new bytes29[](2);
_views[0] = _tokenId;
_views[1] = _action;
return TypedMemView.join(_views);
}
/**
* @notice Returns the type of the message
* @param _view The message
* @return The type of the message
*/
function messageType(bytes29 _view) internal pure returns (Types) {
return Types(uint8(_view.typeOf()));
}
/**
* @notice Checks that the message is of type Transfer
* @param _action The message
* @return True if the message is of type Transfer
*/
function isTransfer(bytes29 _action) internal pure returns (bool) {
return
actionType(_action) == uint8(Types.Transfer) &&
messageType(_action) == Types.Transfer;
}
/**
* @notice Checks that the message is of type Details
* @param _action The message
* @return True if the message is of type Details
*/
function isDetails(bytes29 _action) internal pure returns (bool) {
return
actionType(_action) == uint8(Types.Details) &&
messageType(_action) == Types.Details;
}
/**
* @notice Checks that the message is of type Details
* @param _action The message
* @return True if the message is of type Details
*/
function isRequestDetails(bytes29 _action) internal pure returns (bool) {
return
actionType(_action) == uint8(Types.RequestDetails) &&
messageType(_action) == Types.RequestDetails;
}
/**
* @notice Formats Transfer
* @param _to The recipient address as bytes32
* @param _amnt The transfer amount
* @return
*/
function formatTransfer(bytes32 _to, uint256 _amnt)
internal
pure
returns (bytes29)
{
return
mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0));
}
/**
* @notice Formats Details
* @param _name The name
* @param _symbol The symbol
* @param _decimals The decimals
* @return The Details message
*/
function formatDetails(
bytes32 _name,
bytes32 _symbol,
uint8 _decimals
) internal pure returns (bytes29) {
return
mustBeDetails(
abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref(
0
)
);
}
/**
* @notice Formats Request Details
* @return The Request Details message
*/
function formatRequestDetails() internal pure returns (bytes29) {
return
mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0));
}
/**
* @notice Formats the Token ID
* @param _domain The domain
* @param _id The ID
* @return The formatted Token ID
*/
function formatTokenId(uint32 _domain, bytes32 _id)
internal
pure
returns (bytes29)
{
return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0));
}
/**
* @notice Retrieves the domain from a TokenID
* @param _tokenId The message
* @return The domain
*/
function domain(bytes29 _tokenId)
internal
pure
typeAssert(_tokenId, Types.TokenId)
returns (uint32)
{
return uint32(_tokenId.indexUint(0, 4));
}
/**
* @notice Retrieves the ID from a TokenID
* @param _tokenId The message
* @return The ID
*/
function id(bytes29 _tokenId)
internal
pure
typeAssert(_tokenId, Types.TokenId)
returns (bytes32)
{
// before = 4 bytes domain
return _tokenId.index(4, 32);
}
/**
* @notice Retrieves the EVM ID
* @param _tokenId The message
* @return The EVM ID
*/
function evmId(bytes29 _tokenId)
internal
pure
typeAssert(_tokenId, Types.TokenId)
returns (address)
{
// before = 4 bytes domain + 12 bytes empty to trim for address
return _tokenId.indexAddress(16);
}
/**
* @notice Retrieves the action identifier from message
* @param _message The action
* @return The message type
*/
function msgType(bytes29 _message) internal pure returns (uint8) {
return uint8(_message.indexUint(TOKEN_ID_LEN, 1));
}
/**
* @notice Retrieves the identifier from action
* @param _action The action
* @return The action type
*/
function actionType(bytes29 _action) internal pure returns (uint8) {
return uint8(_action.indexUint(0, 1));
}
/**
* @notice Retrieves the recipient from a Transfer
* @param _transferAction The message
* @return The recipient address as bytes32
*/
function recipient(bytes29 _transferAction)
internal
pure
typeAssert(_transferAction, Types.Transfer)
returns (bytes32)
{
// before = 1 byte identifier
return _transferAction.index(1, 32);
}
/**
* @notice Retrieves the EVM Recipient from a Transfer
* @param _transferAction The message
* @return The EVM Recipient
*/
function evmRecipient(bytes29 _transferAction)
internal
pure
typeAssert(_transferAction, Types.Transfer)
returns (address)
{
// before = 1 byte identifier + 12 bytes empty to trim for address
return _transferAction.indexAddress(13);
}
/**
* @notice Retrieves the amount from a Transfer
* @param _transferAction The message
* @return The amount
*/
function amnt(bytes29 _transferAction)
internal
pure
typeAssert(_transferAction, Types.Transfer)
returns (uint256)
{
// before = 1 byte identifier + 32 bytes ID
return _transferAction.indexUint(33, 32);
}
/**
* @notice Retrieves the name from Details
* @param _detailsAction The message
* @return The name
*/
function name(bytes29 _detailsAction)
internal
pure
typeAssert(_detailsAction, Types.Details)
returns (bytes32)
{
// before = 1 byte identifier
return _detailsAction.index(1, 32);
}
/**
* @notice Retrieves the symbol from Details
* @param _detailsAction The message
* @return The symbol
*/
function symbol(bytes29 _detailsAction)
internal
pure
typeAssert(_detailsAction, Types.Details)
returns (bytes32)
{
// before = 1 byte identifier + 32 bytes name
return _detailsAction.index(33, 32);
}
/**
* @notice Retrieves the decimals from Details
* @param _detailsAction The message
* @return The decimals
*/
function decimals(bytes29 _detailsAction)
internal
pure
typeAssert(_detailsAction, Types.Details)
returns (uint8)
{
// before = 1 byte identifier + 32 bytes name + 32 bytes symbol
return uint8(_detailsAction.indexUint(65, 1));
}
/**
* @notice Retrieves the token ID from a Message
* @param _message The message
* @return The ID
*/
function tokenId(bytes29 _message)
internal
pure
typeAssert(_message, Types.Message)
returns (bytes29)
{
return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId));
}
/**
* @notice Retrieves the action data from a Message
* @param _message The message
* @return The action
*/
function action(bytes29 _message)
internal
pure
typeAssert(_message, Types.Message)
returns (bytes29)
{
uint256 _actionLen = _message.len() - TOKEN_ID_LEN;
uint40 _type = uint40(msgType(_message));
return _message.slice(TOKEN_ID_LEN, _actionLen, _type);
}
/**
* @notice Converts to a Transfer
* @param _action The message
* @return The newly typed message
*/
function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) {
if (_action.len() == TRANSFER_LEN) {
return _action.castTo(uint40(Types.Transfer));
}
return TypedMemView.nullView();
}
/**
* @notice Converts to a Details
* @param _action The message
* @return The newly typed message
*/
function tryAsDetails(bytes29 _action) internal pure returns (bytes29) {
if (_action.len() == DETAILS_LEN) {
return _action.castTo(uint40(Types.Details));
}
return TypedMemView.nullView();
}
/**
* @notice Converts to a Details
* @param _action The message
* @return The newly typed message
*/
function tryAsRequestDetails(bytes29 _action)
internal
pure
returns (bytes29)
{
if (_action.len() == REQUEST_DETAILS_LEN) {
return _action.castTo(uint40(Types.RequestDetails));
}
return TypedMemView.nullView();
}
/**
* @notice Converts to a TokenID
* @param _tokenId The message
* @return The newly typed message
*/
function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) {
if (_tokenId.len() == TOKEN_ID_LEN) {
return _tokenId.castTo(uint40(Types.TokenId));
}
return TypedMemView.nullView();
}
/**
* @notice Converts to a Message
* @param _message The message
* @return The newly typed message
*/
function tryAsMessage(bytes29 _message) internal pure returns (bytes29) {
if (isValidMessageLength(_message)) {
return _message.castTo(uint40(Types.Message));
}
return TypedMemView.nullView();
}
/**
* @notice Asserts that the message is of type Transfer
* @param _view The message
* @return The message
*/
function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) {
return tryAsTransfer(_view).assertValid();
}
/**
* @notice Asserts that the message is of type Details
* @param _view The message
* @return The message
*/
function mustBeDetails(bytes29 _view) internal pure returns (bytes29) {
return tryAsDetails(_view).assertValid();
}
/**
* @notice Asserts that the message is of type Details
* @param _view The message
* @return The message
*/
function mustBeRequestDetails(bytes29 _view)
internal
pure
returns (bytes29)
{
return tryAsRequestDetails(_view).assertValid();
}
/**
* @notice Asserts that the message is of type TokenID
* @param _view The message
* @return The message
*/
function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) {
return tryAsTokenId(_view).assertValid();
}
/**
* @notice Asserts that the message is of type Message
* @param _view The message
* @return The message
*/
function mustBeMessage(bytes29 _view) internal pure returns (bytes29) {
return tryAsMessage(_view).assertValid();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {QueueLib} from "../libs/Queue.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {MerkleTreeManager} from "./Merkle.sol";
import {QueueManager} from "./Queue.sol";
import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol";
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Home
* @author Celo Labs Inc.
* @notice Accepts messages to be dispatched to remote chains,
* constructs a Merkle tree of the messages,
* and accepts signatures from a bonded Updater
* which notarize the Merkle tree roots.
* Accepts submissions of fraudulent signatures
* by the Updater and slashes the Updater in this case.
*/
contract Home is
Version0,
QueueManager,
MerkleTreeManager,
Common,
OwnableUpgradeable
{
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
using MerkleLib for MerkleLib.Tree;
// ============ Constants ============
// Maximum bytes per message = 2 KiB
// (somewhat arbitrarily set to begin)
uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10;
// ============ Public Storage Variables ============
// domain => next available nonce for the domain
mapping(uint32 => uint32) public nonces;
// contract responsible for Updater bonding, slashing and rotation
IUpdaterManager public updaterManager;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[48] private __GAP;
// ============ Events ============
/**
* @notice Emitted when a new message is dispatched via Optics
* @param leafIndex Index of message's leaf in merkle tree
* @param destinationAndNonce Destination and destination-specific
* nonce combined in single field ((destination << 32) & nonce)
* @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message
* @param committedRoot the latest notarized root submitted in the last signed Update
* @param message Raw bytes of message
*/
event Dispatch(
bytes32 indexed messageHash,
uint256 indexed leafIndex,
uint64 indexed destinationAndNonce,
bytes32 committedRoot,
bytes message
);
/**
* @notice Emitted when proof of an improper update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root of the improper update
* @param newRoot New root of the improper update
* @param signature Signature on `oldRoot` and `newRoot
*/
event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature);
/**
* @notice Emitted when the Updater is slashed
* (should be paired with ImproperUpdater or DoubleUpdate event)
* @param updater The address of the updater
* @param reporter The address of the entity that reported the updater misbehavior
*/
event UpdaterSlashed(address indexed updater, address indexed reporter);
/**
* @notice Emitted when Updater is rotated by the UpdaterManager
* @param updater The address of the new updater
*/
event NewUpdater(address updater);
/**
* @notice Emitted when the UpdaterManager contract is changed
* @param updaterManager The address of the new updaterManager
*/
event NewUpdaterManager(address updaterManager);
// ============ Constructor ============
constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks
// ============ Initializer ============
function initialize(IUpdaterManager _updaterManager) public initializer {
// initialize owner & queue
__Ownable_init();
__QueueManager_initialize();
// set Updater Manager contract and initialize Updater
_setUpdaterManager(_updaterManager);
address _updater = updaterManager.updater();
__Common_initialize(_updater);
emit NewUpdater(_updater);
}
// ============ Modifiers ============
/**
* @notice Ensures that function is called by the UpdaterManager contract
*/
modifier onlyUpdaterManager() {
require(msg.sender == address(updaterManager), "!updaterManager");
_;
}
// ============ External: Updater & UpdaterManager Configuration ============
/**
* @notice Set a new Updater
* @param _updater the new Updater
*/
function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
/**
* @notice Set a new UpdaterManager contract
* @dev Home(s) will initially be initialized using a trusted UpdaterManager contract;
* we will progressively decentralize by swapping the trusted contract with a new implementation
* that implements Updater bonding & slashing, and rules for Updater selection & rotation
* @param _updaterManager the new UpdaterManager contract
*/
function setUpdaterManager(address _updaterManager) external onlyOwner {
_setUpdaterManager(IUpdaterManager(_updaterManager));
}
// ============ External Functions ============
/**
* @notice Dispatch the message it to the destination domain & recipient
* @dev Format the message, insert its hash into Merkle tree,
* enqueue the new Merkle root, and emit `Dispatch` event with message information.
* @param _destinationDomain Domain of destination chain
* @param _recipientAddress Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes content of message
*/
function dispatch(
uint32 _destinationDomain,
bytes32 _recipientAddress,
bytes memory _messageBody
) external notFailed {
require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long");
// get the next nonce for the destination domain, then increment it
uint32 _nonce = nonces[_destinationDomain];
nonces[_destinationDomain] = _nonce + 1;
// format the message into packed bytes
bytes memory _message = Message.formatMessage(
localDomain,
bytes32(uint256(uint160(msg.sender))),
_nonce,
_destinationDomain,
_recipientAddress,
_messageBody
);
// insert the hashed message into the Merkle tree
bytes32 _messageHash = keccak256(_message);
tree.insert(_messageHash);
// enqueue the new Merkle root after inserting the message
queue.enqueue(root());
// Emit Dispatch event with message information
// note: leafIndex is count() - 1 since new leaf has already been inserted
emit Dispatch(
_messageHash,
count() - 1,
_destinationAndNonce(_destinationDomain, _nonce),
committedRoot,
_message
);
}
/**
* @notice Submit a signature from the Updater "notarizing" a root,
* which updates the Home contract's `committedRoot`,
* and publishes the signature which will be relayed to Replica contracts
* @dev emits Update event
* @dev If _newRoot is not contained in the queue,
* the Update is a fraudulent Improper Update, so
* the Updater is slashed & Home is set to FAILED state
* @param _committedRoot Current updated merkle root which the update is building off of
* @param _newRoot New merkle root to update the contract state to
* @param _signature Updater signature on `_committedRoot` and `_newRoot`
*/
function update(
bytes32 _committedRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// check that the update is not fraudulent;
// if fraud is detected, Updater is slashed & Home is set to FAILED state
if (improperUpdate(_committedRoot, _newRoot, _signature)) return;
// clear all of the intermediate roots contained in this update from the queue
while (true) {
bytes32 _next = queue.dequeue();
if (_next == _newRoot) break;
}
// update the Home state with the latest signed root & emit event
committedRoot = _newRoot;
emit Update(localDomain, _committedRoot, _newRoot, _signature);
}
/**
* @notice Suggest an update for the Updater to sign and submit.
* @dev If queue is empty, null bytes returned for both
* (No update is necessary because no messages have been dispatched since the last update)
* @return _committedRoot Latest root signed by the Updater
* @return _new Latest enqueued Merkle root
*/
function suggestUpdate()
external
view
returns (bytes32 _committedRoot, bytes32 _new)
{
if (queue.length() != 0) {
_committedRoot = committedRoot;
_new = queue.lastItem();
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(localDomain);
}
/**
* @notice Check if an Update is an Improper Update;
* if so, slash the Updater and set the contract to FAILED state.
*
* An Improper Update is an update building off of the Home's `committedRoot`
* for which the `_newRoot` does not currently exist in the Home's queue.
* This would mean that message(s) that were not truly
* dispatched on Home were falsely included in the signed root.
*
* An Improper Update will only be accepted as valid by the Replica
* If an Improper Update is attempted on Home,
* the Updater will be slashed immediately.
* If an Improper Update is submitted to the Replica,
* it should be relayed to the Home contract using this function
* in order to slash the Updater with an Improper Update.
*
* An Improper Update submitted to the Replica is only valid
* while the `_oldRoot` is still equal to the `committedRoot` on Home;
* if the `committedRoot` on Home has already been updated with a valid Update,
* then the Updater should be slashed with a Double Update.
* @dev Reverts (and doesn't slash updater) if signature is invalid or
* update not current
* @param _oldRoot Old merkle tree root (should equal home's committedRoot)
* @param _newRoot New merkle tree root
* @param _signature Updater signature on `_oldRoot` and `_newRoot`
* @return TRUE if update was an Improper Update (implying Updater was slashed)
*/
function improperUpdate(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) public notFailed returns (bool) {
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
require(_oldRoot == committedRoot, "not a current update");
// if the _newRoot is not currently contained in the queue,
// slash the Updater and set the contract to FAILED state
if (!queue.contains(_newRoot)) {
_fail();
emit ImproperUpdate(_oldRoot, _newRoot, _signature);
return true;
}
// if the _newRoot is contained in the queue,
// this is not an improper update
return false;
}
// ============ Internal Functions ============
/**
* @notice Set the UpdaterManager
* @param _updaterManager Address of the UpdaterManager
*/
function _setUpdaterManager(IUpdaterManager _updaterManager) internal {
require(
Address.isContract(address(_updaterManager)),
"!contract updaterManager"
);
updaterManager = IUpdaterManager(_updaterManager);
emit NewUpdaterManager(address(_updaterManager));
}
/**
* @notice Set the Updater
* @param _updater Address of the Updater
*/
function _setUpdater(address _updater) internal {
updater = _updater;
emit NewUpdater(_updater);
}
/**
* @notice Slash the Updater and set contract state to FAILED
* @dev Called when fraud is proven (Improper Update or Double Update)
*/
function _fail() internal override {
// set contract to FAILED
_setFailed();
// slash Updater
updaterManager.slashUpdater(msg.sender);
emit UpdaterSlashed(updater, msg.sender);
}
/**
* @notice Internal utility function that combines
* `_destination` and `_nonce`.
* @dev Both destination and nonce should be less than 2^32 - 1
* @param _destination Domain of destination chain
* @param _nonce Current nonce for given destination chain
* @return Returns (`_destination` << 32) & `_nonce`
*/
function _destinationAndNonce(uint32 _destination, uint32 _nonce)
internal
pure
returns (uint64)
{
return (uint64(_destination) << 32) | _nonce;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title Version0
* @notice Version getter for contracts
**/
contract Version0 {
uint8 public constant VERSION = 0;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.5.10;
import {SafeMath} from "./SafeMath.sol";
library TypedMemView {
using SafeMath for uint256;
// Why does this exist?
// the solidity `bytes memory` type has a few weaknesses.
// 1. You can't index ranges effectively
// 2. You can't slice without copying
// 3. The underlying data may represent any type
// 4. Solidity never deallocates memory, and memory costs grow
// superlinearly
// By using a memory view instead of a `bytes memory` we get the following
// advantages:
// 1. Slices are done on the stack, by manipulating the pointer
// 2. We can index arbitrary ranges and quickly convert them to stack types
// 3. We can insert type info into the pointer, and typecheck at runtime
// This makes `TypedMemView` a useful tool for efficient zero-copy
// algorithms.
// Why bytes29?
// We want to avoid confusion between views, digests, and other common
// types so we chose a large and uncommonly used odd number of bytes
//
// Note that while bytes are left-aligned in a word, integers and addresses
// are right-aligned. This means when working in assembly we have to
// account for the 3 unused bytes on the righthand side
//
// First 5 bytes are a type flag.
// - ff_ffff_fffe is reserved for unknown type.
// - ff_ffff_ffff is reserved for invalid types/errors.
// next 12 are memory address
// next 12 are len
// bottom 3 bytes are empty
// Assumptions:
// - non-modification of memory.
// - No Solidity updates
// - - wrt free mem point
// - - wrt bytes representation in memory
// - - wrt memory addressing in general
// Usage:
// - create type constants
// - use `assertType` for runtime type assertions
// - - unfortunately we can't do this at compile time yet :(
// - recommended: implement modifiers that perform type checking
// - - e.g.
// - - `uint40 constant MY_TYPE = 3;`
// - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }`
// - instantiate a typed view from a bytearray using `ref`
// - use `index` to inspect the contents of the view
// - use `slice` to create smaller views into the same memory
// - - `slice` can increase the offset
// - - `slice can decrease the length`
// - - must specify the output type of `slice`
// - - `slice` will return a null view if you try to overrun
// - - make sure to explicitly check for this with `notNull` or `assertType`
// - use `equal` for typed comparisons.
// The null view
bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff;
uint8 constant TWELVE_BYTES = 96;
/**
* @notice Returns the encoded hex character that represents the lower 4 bits of the argument.
* @param _b The byte
* @return char - The encoded hex character
*/
function nibbleHex(uint8 _b) internal pure returns (uint8 char) {
// This can probably be done more efficiently, but it's only in error
// paths, so we don't really care :)
uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4
if (_nibble == 0xf0) {return 0x30;} // 0
if (_nibble == 0xf1) {return 0x31;} // 1
if (_nibble == 0xf2) {return 0x32;} // 2
if (_nibble == 0xf3) {return 0x33;} // 3
if (_nibble == 0xf4) {return 0x34;} // 4
if (_nibble == 0xf5) {return 0x35;} // 5
if (_nibble == 0xf6) {return 0x36;} // 6
if (_nibble == 0xf7) {return 0x37;} // 7
if (_nibble == 0xf8) {return 0x38;} // 8
if (_nibble == 0xf9) {return 0x39;} // 9
if (_nibble == 0xfa) {return 0x61;} // a
if (_nibble == 0xfb) {return 0x62;} // b
if (_nibble == 0xfc) {return 0x63;} // c
if (_nibble == 0xfd) {return 0x64;} // d
if (_nibble == 0xfe) {return 0x65;} // e
if (_nibble == 0xff) {return 0x66;} // f
}
/**
* @notice Returns a uint16 containing the hex-encoded byte.
* @param _b The byte
* @return encoded - The hex-encoded byte
*/
function byteHex(uint8 _b) internal pure returns (uint16 encoded) {
encoded |= nibbleHex(_b >> 4); // top 4 bits
encoded <<= 8;
encoded |= nibbleHex(_b); // lower 4 bits
}
/**
* @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes.
* `second` contains the encoded lower 16 bytes.
*
* @param _b The 32 bytes as uint256
* @return first - The top 16 bytes
* @return second - The bottom 16 bytes
*/
function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) {
for (uint8 i = 31; i > 15; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
first |= byteHex(_byte);
if (i != 16) {
first <<= 16;
}
}
// abusing underflow here =_=
for (uint8 i = 15; i < 255 ; i -= 1) {
uint8 _byte = uint8(_b >> (i * 8));
second |= byteHex(_byte);
if (i != 0) {
second <<= 16;
}
}
}
/**
* @notice Changes the endianness of a uint256.
* @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
* @param _b The unsigned integer to reverse
* @return v - The reversed value
*/
function reverseUint256(uint256 _b) internal pure returns (uint256 v) {
v = _b;
// swap bytes
v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
// swap 2-byte long pairs
v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
// swap 4-byte long pairs
v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
// swap 8-byte long pairs
v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
// swap 16-byte long pairs
v = (v >> 128) | (v << 128);
}
/**
* @notice Create a mask with the highest `_len` bits set.
* @param _len The length
* @return mask - The mask
*/
function leftMask(uint8 _len) private pure returns (uint256 mask) {
// ugly. redo without assembly?
assembly {
// solium-disable-previous-line security/no-inline-assembly
mask := sar(
sub(_len, 1),
0x8000000000000000000000000000000000000000000000000000000000000000
)
}
}
/**
* @notice Return the null view.
* @return bytes29 - The null view
*/
function nullView() internal pure returns (bytes29) {
return NULL;
}
/**
* @notice Check if the view is null.
* @return bool - True if the view is null
*/
function isNull(bytes29 memView) internal pure returns (bool) {
return memView == NULL;
}
/**
* @notice Check if the view is not null.
* @return bool - True if the view is not null
*/
function notNull(bytes29 memView) internal pure returns (bool) {
return !isNull(memView);
}
/**
* @notice Check if the view is of a valid type and points to a valid location
* in memory.
* @dev We perform this check by examining solidity's unallocated memory
* pointer and ensuring that the view's upper bound is less than that.
* @param memView The view
* @return ret - True if the view is valid
*/
function isValid(bytes29 memView) internal pure returns (bool ret) {
if (typeOf(memView) == 0xffffffffff) {return false;}
uint256 _end = end(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ret := not(gt(_end, mload(0x40)))
}
}
/**
* @notice Require that a typed memory view be valid.
* @dev Returns the view for easy chaining.
* @param memView The view
* @return bytes29 - The validated view
*/
function assertValid(bytes29 memView) internal pure returns (bytes29) {
require(isValid(memView), "Validity assertion failed");
return memView;
}
/**
* @notice Return true if the memview is of the expected type. Otherwise false.
* @param memView The view
* @param _expected The expected type
* @return bool - True if the memview is of the expected type
*/
function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) {
return typeOf(memView) == _expected;
}
/**
* @notice Require that a typed memory view has a specific type.
* @dev Returns the view for easy chaining.
* @param memView The view
* @param _expected The expected type
* @return bytes29 - The view with validated type
*/
function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) {
if (!isType(memView, _expected)) {
(, uint256 g) = encodeHex(uint256(typeOf(memView)));
(, uint256 e) = encodeHex(uint256(_expected));
string memory err = string(
abi.encodePacked(
"Type assertion failed. Got 0x",
uint80(g),
". Expected 0x",
uint80(e)
)
);
revert(err);
}
return memView;
}
/**
* @notice Return an identical view with a different type.
* @param memView The view
* @param _newType The new type
* @return newView - The new view with the specified type
*/
function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) {
// then | in the new type
assembly {
// solium-disable-previous-line security/no-inline-assembly
// shift off the top 5 bytes
newView := or(newView, shr(40, shl(40, memView)))
newView := or(newView, shl(216, _newType))
}
}
/**
* @notice Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Unsafe raw pointer construction. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
newView := shl(96, or(newView, _type)) // insert type
newView := shl(96, or(newView, _loc)) // insert loc
newView := shl(24, or(newView, _len)) // empty bottom 3 bytes
}
}
/**
* @notice Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @dev Instantiate a new memory view. This should generally not be called
* directly. Prefer `ref` wherever possible.
* @param _type The type
* @param _loc The memory address
* @param _len The length
* @return newView - The new view with the specified type, location and length
*/
function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) {
uint256 _end = _loc.add(_len);
assembly {
// solium-disable-previous-line security/no-inline-assembly
if gt(_end, mload(0x40)) {
_end := 0
}
}
if (_end == 0) {
return NULL;
}
newView = unsafeBuildUnchecked(_type, _loc, _len);
}
/**
* @notice Instantiate a memory view from a byte array.
* @dev Note that due to Solidity memory representation, it is not possible to
* implement a deref, as the `bytes` type stores its len in memory.
* @param arr The byte array
* @param newType The type
* @return bytes29 - The memory view
*/
function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) {
uint256 _len = arr.length;
uint256 _loc;
assembly {
// solium-disable-previous-line security/no-inline-assembly
_loc := add(arr, 0x20) // our view is of the data, not the struct
}
return build(newType, _loc, _len);
}
/**
* @notice Return the associated type information.
* @param memView The memory view
* @return _type - The type associated with the view
*/
function typeOf(bytes29 memView) internal pure returns (uint40 _type) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 216 == 256 - 40
_type := shr(216, memView) // shift out lower 24 bytes
}
}
/**
* @notice Optimized type comparison. Checks that the 5-byte type flag is equal.
* @param left The first view
* @param right The second view
* @return bool - True if the 5-byte type flag is equal
*/
function sameType(bytes29 left, bytes29 right) internal pure returns (bool) {
return (left ^ right) >> (2 * TWELVE_BYTES) == 0;
}
/**
* @notice Return the memory address of the underlying bytes.
* @param memView The view
* @return _loc - The memory address
*/
function loc(bytes29 memView) internal pure returns (uint96 _loc) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
// 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space)
_loc := and(shr(120, memView), _mask)
}
}
/**
* @notice The number of memory words this memory view occupies, rounded up.
* @param memView The view
* @return uint256 - The number of memory words
*/
function words(bytes29 memView) internal pure returns (uint256) {
return uint256(len(memView)).add(32) / 32;
}
/**
* @notice The in-memory footprint of a fresh copy of the view.
* @param memView The view
* @return uint256 - The in-memory footprint of a fresh copy of the view.
*/
function footprint(bytes29 memView) internal pure returns (uint256) {
return words(memView) * 32;
}
/**
* @notice The number of bytes of the view.
* @param memView The view
* @return _len - The length of the view
*/
function len(bytes29 memView) internal pure returns (uint96 _len) {
uint256 _mask = LOW_12_MASK; // assembly can't use globals
assembly {
// solium-disable-previous-line security/no-inline-assembly
_len := and(shr(24, memView), _mask)
}
}
/**
* @notice Returns the endpoint of `memView`.
* @param memView The view
* @return uint256 - The endpoint of `memView`
*/
function end(bytes29 memView) internal pure returns (uint256) {
return loc(memView) + len(memView);
}
/**
* @notice Safe slicing without memory modification.
* @param memView The view
* @param _index The start index
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) {
uint256 _loc = loc(memView);
// Ensure it doesn't overrun the view
if (_loc.add(_index).add(_len) > end(memView)) {
return NULL;
}
_loc = _loc.add(_index);
return build(newType, _loc, _len);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, 0, _len, newType);
}
/**
* @notice Shortcut to `slice`. Gets a view representing the last `_len` byte.
* @param memView The view
* @param _len The length
* @param newType The new type
* @return bytes29 - The new view
*/
function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) {
return slice(memView, uint256(len(memView)).sub(_len), _len, newType);
}
/**
* @notice Construct an error message for an indexing overrun.
* @param _loc The memory address
* @param _len The length
* @param _index The index
* @param _slice The slice where the overrun occurred
* @return err - The err
*/
function indexErrOverrun(
uint256 _loc,
uint256 _len,
uint256 _index,
uint256 _slice
) internal pure returns (string memory err) {
(, uint256 a) = encodeHex(_loc);
(, uint256 b) = encodeHex(_len);
(, uint256 c) = encodeHex(_index);
(, uint256 d) = encodeHex(_slice);
err = string(
abi.encodePacked(
"TypedMemView/index - Overran the view. Slice is at 0x",
uint48(a),
" with length 0x",
uint48(b),
". Attempted to index at offset 0x",
uint48(c),
" with length 0x",
uint48(d),
"."
)
);
}
/**
* @notice Load up to 32 bytes from the view onto the stack.
* @dev Returns a bytes32 with only the `_bytes` highest bytes set.
* This can be immediately cast to a smaller fixed-length byte array.
* To automatically cast to an integer, use `indexUint`.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The 32 byte result
*/
function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) {
if (_bytes == 0) {return bytes32(0);}
if (_index.add(_bytes) > len(memView)) {
revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes)));
}
require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes");
uint8 bitLength = _bytes * 8;
uint256 _loc = loc(memView);
uint256 _mask = leftMask(bitLength);
assembly {
// solium-disable-previous-line security/no-inline-assembly
result := and(mload(add(_loc, _index)), _mask)
}
}
/**
* @notice Parse an unsigned integer from the view at `_index`.
* @dev Requires that the view have >= `_bytes` bytes following that index.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8);
}
/**
* @notice Parse an unsigned integer from LE bytes.
* @param memView The view
* @param _index The index
* @param _bytes The bytes
* @return result - The unsigned integer
*/
function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) {
return reverseUint256(uint256(index(memView, _index, _bytes)));
}
/**
* @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes
* following that index.
* @param memView The view
* @param _index The index
* @return address - The address
*/
function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) {
return address(uint160(indexUint(memView, _index, 20)));
}
/**
* @notice Return the keccak256 hash of the underlying memory
* @param memView The view
* @return digest - The keccak256 hash of the underlying memory
*/
function keccak(bytes29 memView) internal pure returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
digest := keccak256(_loc, _len)
}
}
/**
* @notice Return the sha2 digest of the underlying memory.
* @dev We explicitly deallocate memory afterwards.
* @param memView The view
* @return digest - The sha2 hash of the underlying memory
*/
function sha2(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
digest := mload(ptr)
}
}
/**
* @notice Implements bitcoin's hash160 (rmd160(sha2()))
* @param memView The pre-image
* @return digest - the Digest
*/
function hash160(bytes29 memView) internal view returns (bytes20 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2
pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160
digest := mload(add(ptr, 0xc)) // return value is 0-prefixed.
}
}
/**
* @notice Implements bitcoin's hash256 (double sha2)
* @param memView A view of the preimage
* @return digest - the Digest
*/
function hash256(bytes29 memView) internal view returns (bytes32 digest) {
uint256 _loc = loc(memView);
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1
pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2
digest := mload(ptr)
}
}
/**
* @notice Return true if the underlying memory is equal. Else false.
* @param left The first view
* @param right The second view
* @return bool - True if the underlying memory is equal
*/
function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right);
}
/**
* @notice Return false if the underlying memory is equal. Else true.
* @param left The first view
* @param right The second view
* @return bool - False if the underlying memory is equal
*/
function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !untypedEqual(left, right);
}
/**
* @notice Compares type equality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are the same
*/
function equal(bytes29 left, bytes29 right) internal pure returns (bool) {
return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right));
}
/**
* @notice Compares type inequality.
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param left The first view
* @param right The second view
* @return bool - True if the types are not the same
*/
function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) {
return !equal(left, right);
}
/**
* @notice Copy the view to a location, return an unsafe memory reference
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memView The view
* @param _newLoc The new location
* @return written - the unsafe memory reference
*/
function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) {
require(notNull(memView), "TypedMemView/copyTo - Null pointer deref");
require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref");
uint256 _len = len(memView);
uint256 _oldLoc = loc(memView);
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _newLoc) {
revert(0x60, 0x20) // empty revert message
}
// use the identity precompile to copy
// guaranteed not to fail, so pop the success
pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len))
}
written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len);
}
/**
* @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to
* the new memory
* @dev Shortcuts if the pointers are identical, otherwise compares type and digest.
* @param memView The view
* @return ret - The view pointing to the new memory
*/
function clone(bytes29 memView) internal view returns (bytes memory ret) {
uint256 ptr;
uint256 _len = len(memView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
ret := ptr
}
unsafeCopyTo(memView, ptr + 0x20);
assembly {
// solium-disable-previous-line security/no-inline-assembly
mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer
mstore(ptr, _len) // write len of new array (in bytes)
}
}
/**
* @notice Join the views in memory, return an unsafe reference to the memory.
* @dev Super Dangerous direct memory access.
*
* This reference can be overwritten if anything else modifies memory (!!!).
* As such it MUST be consumed IMMEDIATELY.
* This function is private to prevent unsafe usage by callers.
* @param memViews The views
* @return unsafeView - The conjoined view pointing to the new memory
*/
function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) {
assembly {
// solium-disable-previous-line security/no-inline-assembly
let ptr := mload(0x40)
// revert if we're writing in occupied memory
if gt(ptr, _location) {
revert(0x60, 0x20) // empty revert message
}
}
uint256 _offset = 0;
for (uint256 i = 0; i < memViews.length; i ++) {
bytes29 memView = memViews[i];
unsafeCopyTo(memView, _location + _offset);
_offset += len(memView);
}
unsafeView = unsafeBuildUnchecked(0, _location, _offset);
}
/**
* @notice Produce the keccak256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The keccak256 digest
*/
function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return keccak(unsafeJoin(memViews, ptr));
}
/**
* @notice Produce the sha256 digest of the concatenated contents of multiple views.
* @param memViews The views
* @return bytes32 - The sha256 digest
*/
function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
return sha2(unsafeJoin(memViews, ptr));
}
/**
* @notice copies all views, joins them into a new bytearray.
* @param memViews The views
* @return ret - The new byte array
*/
function join(bytes29[] memory memViews) internal view returns (bytes memory ret) {
uint256 ptr;
assembly {
// solium-disable-previous-line security/no-inline-assembly
ptr := mload(0x40) // load unused memory pointer
}
bytes29 _newView = unsafeJoin(memViews, ptr + 0x20);
uint256 _written = len(_newView);
uint256 _footprint = footprint(_newView);
assembly {
// solium-disable-previous-line security/no-inline-assembly
// store the legnth
mstore(ptr, _written)
// new pointer is old + 0x20 + the footprint of the body
mstore(0x40, add(add(ptr, _footprint), 0x20))
ret := ptr
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 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
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 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),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 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(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: 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(IERC20 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, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
library Encoding {
// ============ Constants ============
bytes private constant NIBBLE_LOOKUP = "0123456789abcdef";
// ============ Internal Functions ============
/**
* @notice Encode a uint32 in its DECIMAL representation, with leading
* zeroes.
* @param _num The number to encode
* @return _encoded The encoded number, suitable for use in abi.
* encodePacked
*/
function decimalUint32(uint32 _num)
internal
pure
returns (uint80 _encoded)
{
uint80 ASCII_0 = 0x30;
// all over/underflows are impossible
// this will ALWAYS produce 10 decimal characters
for (uint8 i = 0; i < 10; i += 1) {
_encoded |= ((_num % 10) + ASCII_0) << (i * 8);
_num = _num / 10;
}
}
/**
* @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes.
* `second` contains the encoded lower 16 bytes.
* @param _bytes The 32 bytes as uint256
* @return _firstHalf The top 16 bytes
* @return _secondHalf The bottom 16 bytes
*/
function encodeHex(uint256 _bytes)
internal
pure
returns (uint256 _firstHalf, uint256 _secondHalf)
{
for (uint8 i = 31; i > 15; i -= 1) {
uint8 _b = uint8(_bytes >> (i * 8));
_firstHalf |= _byteHex(_b);
if (i != 16) {
_firstHalf <<= 16;
}
}
// abusing underflow here =_=
for (uint8 i = 15; i < 255; i -= 1) {
uint8 _b = uint8(_bytes >> (i * 8));
_secondHalf |= _byteHex(_b);
if (i != 0) {
_secondHalf <<= 16;
}
}
}
/**
* @notice Returns the encoded hex character that represents the lower 4 bits of the argument.
* @param _byte The byte
* @return _char The encoded hex character
*/
function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) {
uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4
_char = uint8(NIBBLE_LOOKUP[_nibble]);
}
/**
* @notice Returns a uint16 containing the hex-encoded byte.
* @param _byte The byte
* @return _encoded The hex-encoded byte
*/
function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) {
_encoded |= _nibbleHex(_byte >> 4); // top 4 bits
_encoded <<= 8;
_encoded |= _nibbleHex(_byte); // lower 4 bits
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.11;
// ============ External Imports ============
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
/**
* @title UpgradeBeaconProxy
* @notice
* Proxy contract which delegates all logic, including initialization,
* to an implementation contract.
* The implementation contract is stored within an Upgrade Beacon contract;
* the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract.
* The Upgrade Beacon contract for this Proxy is immutably specified at deployment.
* @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage
* found in 0age's implementation:
* https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol
* With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment
* found in OpenZeppelin's implementation:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol
*/
contract UpgradeBeaconProxy {
// ============ Immutables ============
// Upgrade Beacon address is immutable (therefore not kept in contract storage)
address private immutable upgradeBeacon;
// ============ Constructor ============
/**
* @notice Validate that the Upgrade Beacon is a contract, then set its
* address immutably within this contract.
* Validate that the implementation is also a contract,
* Then call the initialization function defined at the implementation.
* The deployment will revert and pass along the
* revert reason if the initialization function reverts.
* @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract
* @param _initializationCalldata Calldata supplied when calling the initialization function
*/
constructor(address _upgradeBeacon, bytes memory _initializationCalldata)
payable
{
// Validate the Upgrade Beacon is a contract
require(Address.isContract(_upgradeBeacon), "beacon !contract");
// set the Upgrade Beacon
upgradeBeacon = _upgradeBeacon;
// Validate the implementation is a contract
address _implementation = _getImplementation(_upgradeBeacon);
require(
Address.isContract(_implementation),
"beacon implementation !contract"
);
// Call the initialization function on the implementation
if (_initializationCalldata.length > 0) {
_initialize(_implementation, _initializationCalldata);
}
}
// ============ External Functions ============
/**
* @notice Forwards all calls with data to _fallback()
* No public functions are declared on the contract, so all calls hit fallback
*/
fallback() external payable {
_fallback();
}
/**
* @notice Forwards all calls with no data to _fallback()
*/
receive() external payable {
_fallback();
}
// ============ Private Functions ============
/**
* @notice Call the initialization function on the implementation
* Used at deployment to initialize the proxy
* based on the logic for initialization defined at the implementation
* @param _implementation - Contract to which the initalization is delegated
* @param _initializationCalldata - Calldata supplied when calling the initialization function
*/
function _initialize(
address _implementation,
bytes memory _initializationCalldata
) private {
// Delegatecall into the implementation, supplying initialization calldata.
(bool _ok, ) = _implementation.delegatecall(_initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!_ok) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/**
* @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon
*/
function _fallback() private {
_delegate(_getImplementation());
}
/**
* @notice Delegate function execution to the implementation contract
* @dev This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param _implementation - Address to which the function execution is delegated
*/
function _delegate(address _implementation) private {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(
gas(),
_implementation,
0,
calldatasize(),
0,
0
)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize())
switch result
// Delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @return _implementation Address of the current implementation.
*/
function _getImplementation()
private
view
returns (address _implementation)
{
_implementation = _getImplementation(upgradeBeacon);
}
/**
* @notice Call the Upgrade Beacon to get the current implementation contract address
* @dev _upgradeBeacon is passed as a parameter so that
* we can also use this function in the constructor,
* where we can't access immutable variables.
* @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation
* @return _implementation Address of the current implementation.
*/
function _getImplementation(address _upgradeBeacon)
private
view
returns (address _implementation)
{
// Get the current implementation address from the upgrade beacon.
(bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(_ok, string(_returnData));
// Set the implementation to the address returned from the upgrade beacon.
_implementation = abi.decode(_returnData, (address));
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.10;
/*
The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
require(c / _a == _b, "Overflow during multiplication.");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, "Underflow during subtraction.");
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
require(c >= _a, "Overflow during addition.");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), 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 {
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 virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Message} from "../libs/Message.sol";
// ============ External Imports ============
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title Common
* @author Celo Labs Inc.
* @notice Shared utilities between Home and Replica.
*/
abstract contract Common is Initializable {
// ============ Enums ============
// States:
// 0 - UnInitialized - before initialize function is called
// note: the contract is initialized at deploy time, so it should never be in this state
// 1 - Active - as long as the contract has not become fraudulent
// 2 - Failed - after a valid fraud proof has been submitted;
// contract will no longer accept updates or new messages
enum States {
UnInitialized,
Active,
Failed
}
// ============ Immutable Variables ============
// Domain of chain on which the contract is deployed
uint32 public immutable localDomain;
// ============ Public Variables ============
// Address of bonded Updater
address public updater;
// Current state of contract
States public state;
// The latest root that has been signed by the Updater
bytes32 public committedRoot;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[47] private __GAP;
// ============ Events ============
/**
* @notice Emitted when update is made on Home
* or unconfirmed update root is submitted on Replica
* @param homeDomain Domain of home contract
* @param oldRoot Old merkle root
* @param newRoot New merkle root
* @param signature Updater's signature on `oldRoot` and `newRoot`
*/
event Update(
uint32 indexed homeDomain,
bytes32 indexed oldRoot,
bytes32 indexed newRoot,
bytes signature
);
/**
* @notice Emitted when proof of a double update is submitted,
* which sets the contract to FAILED state
* @param oldRoot Old root shared between two conflicting updates
* @param newRoot Array containing two conflicting new roots
* @param signature Signature on `oldRoot` and `newRoot`[0]
* @param signature2 Signature on `oldRoot` and `newRoot`[1]
*/
event DoubleUpdate(
bytes32 oldRoot,
bytes32[2] newRoot,
bytes signature,
bytes signature2
);
// ============ Modifiers ============
/**
* @notice Ensures that contract state != FAILED when the function is called
*/
modifier notFailed() {
require(state != States.Failed, "failed state");
_;
}
// ============ Constructor ============
constructor(uint32 _localDomain) {
localDomain = _localDomain;
}
// ============ Initializer ============
function __Common_initialize(address _updater) internal initializer {
updater = _updater;
state = States.Active;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Checks that signatures on two sets of
* roots are valid and that the new roots conflict with each other. If both
* cases hold true, the contract is failed and a `DoubleUpdate` event is
* emitted.
* @dev When `fail()` is called on Home, updater is slashed.
* @param _oldRoot Old root shared between two conflicting updates
* @param _newRoot Array containing two conflicting new roots
* @param _signature Signature on `_oldRoot` and `_newRoot`[0]
* @param _signature2 Signature on `_oldRoot` and `_newRoot`[1]
*/
function doubleUpdate(
bytes32 _oldRoot,
bytes32[2] calldata _newRoot,
bytes calldata _signature,
bytes calldata _signature2
) external notFailed {
if (
Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) &&
Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) &&
_newRoot[0] != _newRoot[1]
) {
_fail();
emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2);
}
}
// ============ Public Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view virtual returns (bytes32);
// ============ Internal Functions ============
/**
* @notice Hash of Home domain concatenated with "OPTICS"
* @param _homeDomain the Home domain to hash
*/
function _homeDomainHash(uint32 _homeDomain)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_homeDomain, "OPTICS"));
}
/**
* @notice Set contract state to FAILED
* @dev Called when a valid fraud proof is submitted
*/
function _setFailed() internal {
state = States.Failed;
}
/**
* @notice Moves the contract into failed state
* @dev Called when fraud is proven
* (Double Update is submitted on Home or Replica,
* or Improper Update is submitted on Home)
*/
function _fail() internal virtual;
/**
* @notice Checks that signature was signed by Updater
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Signature on `_oldRoot` and `_newRoot`
* @return TRUE iff signature is valid signed by updater
**/
function _isUpdaterSignature(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) internal view returns (bool) {
bytes32 _digest = keccak256(
abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot)
);
_digest = ECDSA.toEthSignedMessageHash(_digest);
return (ECDSA.recover(_digest, _signature) == updater);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
/**
* @title QueueLib
* @author Celo Labs Inc.
* @notice Library containing queue struct and operations for queue used by
* Home and Replica.
**/
library QueueLib {
/**
* @notice Queue struct
* @dev Internally keeps track of the `first` and `last` elements through
* indices and a mapping of indices to enqueued elements.
**/
struct Queue {
uint128 first;
uint128 last;
mapping(uint256 => bytes32) queue;
}
/**
* @notice Initializes the queue
* @dev Empty state denoted by _q.first > q._last. Queue initialized
* with _q.first = 1 and _q.last = 0.
**/
function initialize(Queue storage _q) internal {
if (_q.first == 0) {
_q.first = 1;
}
}
/**
* @notice Enqueues a single new element
* @param _item New element to be enqueued
* @return _last Index of newly enqueued element
**/
function enqueue(Queue storage _q, bytes32 _item)
internal
returns (uint128 _last)
{
_last = _q.last + 1;
_q.last = _last;
if (_item != bytes32(0)) {
// saves gas if we're queueing 0
_q.queue[_last] = _item;
}
}
/**
* @notice Dequeues element at front of queue
* @dev Removes dequeued element from storage
* @return _item Dequeued element
**/
function dequeue(Queue storage _q) internal returns (bytes32 _item) {
uint128 _last = _q.last;
uint128 _first = _q.first;
require(_length(_last, _first) != 0, "Empty");
_item = _q.queue[_first];
if (_item != bytes32(0)) {
// saves gas if we're dequeuing 0
delete _q.queue[_first];
}
_q.first = _first + 1;
}
/**
* @notice Batch enqueues several elements
* @param _items Array of elements to be enqueued
* @return _last Index of last enqueued element
**/
function enqueue(Queue storage _q, bytes32[] memory _items)
internal
returns (uint128 _last)
{
_last = _q.last;
for (uint256 i = 0; i < _items.length; i += 1) {
_last += 1;
bytes32 _item = _items[i];
if (_item != bytes32(0)) {
_q.queue[_last] = _item;
}
}
_q.last = _last;
}
/**
* @notice Batch dequeues `_number` elements
* @dev Reverts if `_number` > queue length
* @param _number Number of elements to dequeue
* @return Array of dequeued elements
**/
function dequeue(Queue storage _q, uint256 _number)
internal
returns (bytes32[] memory)
{
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
require(_length(_last, _first) >= _number, "Insufficient");
bytes32[] memory _items = new bytes32[](_number);
for (uint256 i = 0; i < _number; i++) {
_items[i] = _q.queue[_first];
delete _q.queue[_first];
_first++;
}
_q.first = _first;
return _items;
}
/**
* @notice Returns true if `_item` is in the queue and false if otherwise
* @dev Linearly scans from _q.first to _q.last looking for `_item`
* @param _item Item being searched for in queue
* @return True if `_item` currently exists in queue, false if otherwise
**/
function contains(Queue storage _q, bytes32 _item)
internal
view
returns (bool)
{
for (uint256 i = _q.first; i <= _q.last; i++) {
if (_q.queue[i] == _item) {
return true;
}
}
return false;
}
/// @notice Returns last item in queue
/// @dev Returns bytes32(0) if queue empty
function lastItem(Queue storage _q) internal view returns (bytes32) {
return _q.queue[_q.last];
}
/// @notice Returns element at front of queue without removing element
/// @dev Reverts if queue is empty
function peek(Queue storage _q) internal view returns (bytes32 _item) {
require(!isEmpty(_q), "Empty");
_item = _q.queue[_q.first];
}
/// @notice Returns true if queue is empty and false if otherwise
function isEmpty(Queue storage _q) internal view returns (bool) {
return _q.last < _q.first;
}
/// @notice Returns number of elements in queue
function length(Queue storage _q) internal view returns (uint256) {
uint128 _last = _q.last;
uint128 _first = _q.first;
// Cannot underflow unless state is corrupted
return _length(_last, _first);
}
/// @notice Returns number of elements between `_last` and `_first` (used internally)
function _length(uint128 _last, uint128 _first)
internal
pure
returns (uint256)
{
return uint256(_last + 1 - _first);
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// work based on eth2 deposit contract, which is used under CC0-1.0
/**
* @title MerkleLib
* @author Celo Labs Inc.
* @notice An incremental merkle tree modeled on the eth2 deposit contract.
**/
library MerkleLib {
uint256 internal constant TREE_DEPTH = 32;
uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1;
/**
* @notice Struct representing incremental merkle tree. Contains current
* branch and the number of inserted leaves in the tree.
**/
struct Tree {
bytes32[TREE_DEPTH] branch;
uint256 count;
}
/**
* @notice Inserts `_node` into merkle tree
* @dev Reverts if tree is full
* @param _node Element to insert into tree
**/
function insert(Tree storage _tree, bytes32 _node) internal {
require(_tree.count < MAX_LEAVES, "merkle tree full");
_tree.count += 1;
uint256 size = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
if ((size & 1) == 1) {
_tree.branch[i] = _node;
return;
}
_node = keccak256(abi.encodePacked(_tree.branch[i], _node));
size /= 2;
}
// As the loop should always end prematurely with the `return` statement,
// this code should be unreachable. We assert `false` just to be safe.
assert(false);
}
/**
* @notice Calculates and returns`_tree`'s current root given array of zero
* hashes
* @param _zeroes Array of zero hashes
* @return _current Calculated root of `_tree`
**/
function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes)
internal
view
returns (bytes32 _current)
{
uint256 _index = _tree.count;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _tree.branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _zeroes[i]));
}
}
}
/// @notice Calculates and returns`_tree`'s current root
function root(Tree storage _tree) internal view returns (bytes32) {
return rootWithCtx(_tree, zeroHashes());
}
/// @notice Returns array of TREE_DEPTH zero hashes
/// @return _zeroes Array of TREE_DEPTH zero hashes
function zeroHashes()
internal
pure
returns (bytes32[TREE_DEPTH] memory _zeroes)
{
_zeroes[0] = Z_0;
_zeroes[1] = Z_1;
_zeroes[2] = Z_2;
_zeroes[3] = Z_3;
_zeroes[4] = Z_4;
_zeroes[5] = Z_5;
_zeroes[6] = Z_6;
_zeroes[7] = Z_7;
_zeroes[8] = Z_8;
_zeroes[9] = Z_9;
_zeroes[10] = Z_10;
_zeroes[11] = Z_11;
_zeroes[12] = Z_12;
_zeroes[13] = Z_13;
_zeroes[14] = Z_14;
_zeroes[15] = Z_15;
_zeroes[16] = Z_16;
_zeroes[17] = Z_17;
_zeroes[18] = Z_18;
_zeroes[19] = Z_19;
_zeroes[20] = Z_20;
_zeroes[21] = Z_21;
_zeroes[22] = Z_22;
_zeroes[23] = Z_23;
_zeroes[24] = Z_24;
_zeroes[25] = Z_25;
_zeroes[26] = Z_26;
_zeroes[27] = Z_27;
_zeroes[28] = Z_28;
_zeroes[29] = Z_29;
_zeroes[30] = Z_30;
_zeroes[31] = Z_31;
}
/**
* @notice Calculates and returns the merkle root for the given leaf
* `_item`, a merkle branch, and the index of `_item` in the tree.
* @param _item Merkle leaf
* @param _branch Merkle proof
* @param _index Index of `_item` in tree
* @return _current Calculated merkle root
**/
function branchRoot(
bytes32 _item,
bytes32[TREE_DEPTH] memory _branch,
uint256 _index
) internal pure returns (bytes32 _current) {
_current = _item;
for (uint256 i = 0; i < TREE_DEPTH; i++) {
uint256 _ithBit = (_index >> i) & 0x01;
bytes32 _next = _branch[i];
if (_ithBit == 1) {
_current = keccak256(abi.encodePacked(_next, _current));
} else {
_current = keccak256(abi.encodePacked(_current, _next));
}
}
}
// keccak256 zero hashes
bytes32 internal constant Z_0 =
hex"0000000000000000000000000000000000000000000000000000000000000000";
bytes32 internal constant Z_1 =
hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5";
bytes32 internal constant Z_2 =
hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30";
bytes32 internal constant Z_3 =
hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85";
bytes32 internal constant Z_4 =
hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344";
bytes32 internal constant Z_5 =
hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d";
bytes32 internal constant Z_6 =
hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968";
bytes32 internal constant Z_7 =
hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83";
bytes32 internal constant Z_8 =
hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af";
bytes32 internal constant Z_9 =
hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0";
bytes32 internal constant Z_10 =
hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5";
bytes32 internal constant Z_11 =
hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892";
bytes32 internal constant Z_12 =
hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c";
bytes32 internal constant Z_13 =
hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb";
bytes32 internal constant Z_14 =
hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc";
bytes32 internal constant Z_15 =
hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2";
bytes32 internal constant Z_16 =
hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f";
bytes32 internal constant Z_17 =
hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a";
bytes32 internal constant Z_18 =
hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0";
bytes32 internal constant Z_19 =
hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0";
bytes32 internal constant Z_20 =
hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2";
bytes32 internal constant Z_21 =
hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9";
bytes32 internal constant Z_22 =
hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377";
bytes32 internal constant Z_23 =
hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652";
bytes32 internal constant Z_24 =
hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef";
bytes32 internal constant Z_25 =
hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d";
bytes32 internal constant Z_26 =
hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0";
bytes32 internal constant Z_27 =
hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e";
bytes32 internal constant Z_28 =
hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e";
bytes32 internal constant Z_29 =
hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322";
bytes32 internal constant Z_30 =
hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735";
bytes32 internal constant Z_31 =
hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9";
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
import {
TypeCasts
} from "./TypeCasts.sol";
/**
* @title Message Library
* @author Celo Labs Inc.
* @notice Library for formatted messages used by Home and Replica.
**/
library Message {
using TypedMemView for bytes;
using TypedMemView for bytes29;
// Number of bytes in formatted message before `body` field
uint256 internal constant PREFIX_LENGTH = 76;
/**
* @notice Returns formatted (packed) message with provided fields
* @param _originDomain Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce
* @param _destinationDomain Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _messageBody Raw bytes of message body
* @return Formatted message
**/
function formatMessage(
uint32 _originDomain,
bytes32 _sender,
uint32 _nonce,
uint32 _destinationDomain,
bytes32 _recipient,
bytes memory _messageBody
) internal pure returns (bytes memory) {
return
abi.encodePacked(
_originDomain,
_sender,
_nonce,
_destinationDomain,
_recipient,
_messageBody
);
}
/**
* @notice Returns leaf of formatted message with provided fields.
* @param _origin Domain of home chain
* @param _sender Address of sender as bytes32
* @param _nonce Destination-specific nonce number
* @param _destination Domain of destination chain
* @param _recipient Address of recipient on destination chain as bytes32
* @param _body Raw bytes of message body
* @return Leaf (hash) of formatted message
**/
function messageHash(
uint32 _origin,
bytes32 _sender,
uint32 _nonce,
uint32 _destination,
bytes32 _recipient,
bytes memory _body
) internal pure returns (bytes32) {
return
keccak256(
formatMessage(
_origin,
_sender,
_nonce,
_destination,
_recipient,
_body
)
);
}
/// @notice Returns message's origin field
function origin(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(0, 4));
}
/// @notice Returns message's sender field
function sender(bytes29 _message) internal pure returns (bytes32) {
return _message.index(4, 32);
}
/// @notice Returns message's nonce field
function nonce(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(36, 4));
}
/// @notice Returns message's destination field
function destination(bytes29 _message) internal pure returns (uint32) {
return uint32(_message.indexUint(40, 4));
}
/// @notice Returns message's recipient field as bytes32
function recipient(bytes29 _message) internal pure returns (bytes32) {
return _message.index(44, 32);
}
/// @notice Returns message's recipient field as an address
function recipientAddress(bytes29 _message)
internal
pure
returns (address)
{
return TypeCasts.bytes32ToAddress(recipient(_message));
}
/// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type)
function body(bytes29 _message) internal pure returns (bytes29) {
return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0);
}
function leaf(bytes29 _message) internal view returns (bytes32) {
return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message)));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {MerkleLib} from "../libs/Merkle.sol";
/**
* @title MerkleTreeManager
* @author Celo Labs Inc.
* @notice Contains a Merkle tree instance and
* exposes view functions for the tree.
*/
contract MerkleTreeManager {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
MerkleLib.Tree public tree;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Public Functions ============
/**
* @notice Calculates and returns tree's current root
*/
function root() public view returns (bytes32) {
return tree.root();
}
/**
* @notice Returns the number of inserted leaves in the tree (current index)
*/
function count() public view returns (uint256) {
return tree.count;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {QueueLib} from "../libs/Queue.sol";
// ============ External Imports ============
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* @title QueueManager
* @author Celo Labs Inc.
* @notice Contains a queue instance and
* exposes view functions for the queue.
**/
contract QueueManager is Initializable {
// ============ Libraries ============
using QueueLib for QueueLib.Queue;
QueueLib.Queue internal queue;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[49] private __GAP;
// ============ Initializer ============
function __QueueManager_initialize() internal initializer {
queue.initialize();
}
// ============ Public Functions ============
/**
* @notice Returns number of elements in queue
*/
function queueLength() external view returns (uint256) {
return queue.length();
}
/**
* @notice Returns TRUE iff `_item` is in the queue
*/
function queueContains(bytes32 _item) external view returns (bool) {
return queue.contains(_item);
}
/**
* @notice Returns last item enqueued to the queue
*/
function queueEnd() external view returns (bytes32) {
return queue.lastItem();
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IUpdaterManager {
function slashUpdater(address payable _reporter) external;
function updater() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <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;
// solhint-disable-next-line no-inline-assembly
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");
// 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
import "@summa-tx/memview-sol/contracts/TypedMemView.sol";
library TypeCasts {
using TypedMemView for bytes;
using TypedMemView for bytes29;
function coerceBytes32(string memory _s)
internal
pure
returns (bytes32 _b)
{
_b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length));
}
// treat it as a null-terminated string of max 32 bytes
function coerceString(bytes32 _buf)
internal
pure
returns (string memory _newStr)
{
uint8 _slen = 0;
while (_slen < 32 && _buf[_slen] != 0) {
_slen++;
}
// solhint-disable-next-line no-inline-assembly
assembly {
_newStr := mload(0x40)
mstore(0x40, add(_newStr, 0x40)) // may end up with extra
mstore(_newStr, _slen)
mstore(add(_newStr, 0x20), _buf)
}
}
// alignment preserving cast
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
// alignment preserving cast
function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {
return address(uint160(uint256(_buf)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
// solhint-disable-next-line no-inline-assembly
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");
// 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @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.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
// ============ Internal Imports ============
import {Version0} from "./Version0.sol";
import {Common} from "./Common.sol";
import {MerkleLib} from "../libs/Merkle.sol";
import {Message} from "../libs/Message.sol";
import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol";
// ============ External Imports ============
import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol";
/**
* @title Replica
* @author Celo Labs Inc.
* @notice Track root updates on Home,
* prove and dispatch messages to end recipients.
*/
contract Replica is Version0, Common {
// ============ Libraries ============
using MerkleLib for MerkleLib.Tree;
using TypedMemView for bytes;
using TypedMemView for bytes29;
using Message for bytes29;
// ============ Enums ============
// Status of Message:
// 0 - None - message has not been proven or processed
// 1 - Proven - message inclusion proof has been validated
// 2 - Processed - message has been dispatched to recipient
enum MessageStatus {
None,
Proven,
Processed
}
// ============ Immutables ============
// Minimum gas for message processing
uint256 public immutable PROCESS_GAS;
// Reserved gas (to ensure tx completes in case message processing runs out)
uint256 public immutable RESERVE_GAS;
// ============ Public Storage ============
// Domain of home chain
uint32 public remoteDomain;
// Number of seconds to wait before root becomes confirmable
uint256 public optimisticSeconds;
// re-entrancy guard
uint8 private entered;
// Mapping of roots to allowable confirmation times
mapping(bytes32 => uint256) public confirmAt;
// Mapping of message leaves to MessageStatus
mapping(bytes32 => MessageStatus) public messages;
// ============ Upgrade Gap ============
// gap for upgrade safety
uint256[44] private __GAP;
// ============ Events ============
/**
* @notice Emitted when message is processed
* @param messageHash Hash of message that failed to process
* @param success TRUE if the call was executed successfully, FALSE if the call reverted
* @param returnData the return data from the external call
*/
event Process(
bytes32 indexed messageHash,
bool indexed success,
bytes indexed returnData
);
// ============ Constructor ============
// solhint-disable-next-line no-empty-blocks
constructor(
uint32 _localDomain,
uint256 _processGas,
uint256 _reserveGas
) Common(_localDomain) {
require(_processGas >= 850_000, "!process gas");
require(_reserveGas >= 15_000, "!reserve gas");
PROCESS_GAS = _processGas;
RESERVE_GAS = _reserveGas;
}
// ============ Initializer ============
function initialize(
uint32 _remoteDomain,
address _updater,
bytes32 _committedRoot,
uint256 _optimisticSeconds
) public initializer {
__Common_initialize(_updater);
entered = 1;
remoteDomain = _remoteDomain;
committedRoot = _committedRoot;
confirmAt[_committedRoot] = 1;
optimisticSeconds = _optimisticSeconds;
}
// ============ External Functions ============
/**
* @notice Called by external agent. Submits the signed update's new root,
* marks root's allowable confirmation time, and emits an `Update` event.
* @dev Reverts if update doesn't build off latest committedRoot
* or if signature is invalid.
* @param _oldRoot Old merkle root
* @param _newRoot New merkle root
* @param _signature Updater's signature on `_oldRoot` and `_newRoot`
*/
function update(
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _signature
) external notFailed {
// ensure that update is building off the last submitted root
require(_oldRoot == committedRoot, "not current update");
// validate updater signature
require(
_isUpdaterSignature(_oldRoot, _newRoot, _signature),
"!updater sig"
);
// Hook for future use
_beforeUpdate();
// set the new root's confirmation timer
confirmAt[_newRoot] = block.timestamp + optimisticSeconds;
// update committedRoot
committedRoot = _newRoot;
emit Update(remoteDomain, _oldRoot, _newRoot, _signature);
}
/**
* @notice First attempts to prove the validity of provided formatted
* `message`. If the message is successfully proven, then tries to process
* message.
* @dev Reverts if `prove` call returns false
* @param _message Formatted message (refer to Common.sol Message library)
* @param _proof Merkle proof of inclusion for message's leaf
* @param _index Index of leaf in home's merkle tree
*/
function proveAndProcess(
bytes memory _message,
bytes32[32] calldata _proof,
uint256 _index
) external {
require(prove(keccak256(_message), _proof, _index), "!prove");
process(_message);
}
/**
* @notice Given formatted message, attempts to dispatch
* message payload to end recipient.
* @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol)
* Reverts if formatted message's destination domain is not the Replica's domain,
* if message has not been proven,
* or if not enough gas is provided for the dispatch transaction.
* @param _message Formatted message
* @return _success TRUE iff dispatch transaction succeeded
*/
function process(bytes memory _message) public returns (bool _success) {
bytes29 _m = _message.ref(0);
// ensure message was meant for this domain
require(_m.destination() == localDomain, "!destination");
// ensure message has been proven
bytes32 _messageHash = _m.keccak();
require(messages[_messageHash] == MessageStatus.Proven, "!proven");
// check re-entrancy guard
require(entered == 1, "!reentrant");
entered = 0;
// update message status as processed
messages[_messageHash] = MessageStatus.Processed;
// A call running out of gas TYPICALLY errors the whole tx. We want to
// a) ensure the call has a sufficient amount of gas to make a
// meaningful state change.
// b) ensure that if the subcall runs out of gas, that the tx as a whole
// does not revert (i.e. we still mark the message processed)
// To do this, we require that we have enough gas to process
// and still return. We then delegate only the minimum processing gas.
require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas");
// get the message recipient
address _recipient = _m.recipientAddress();
// set up for assembly call
uint256 _toCopy;
uint256 _maxCopy = 256;
uint256 _gas = PROCESS_GAS;
// allocate memory for returndata
bytes memory _returnData = new bytes(_maxCopy);
bytes memory _calldata = abi.encodeWithSignature(
"handle(uint32,bytes32,bytes)",
_m.origin(),
_m.sender(),
_m.body().clone()
);
// dispatch message to recipient
// by assembly calling "handle" function
// we call via assembly to avoid memcopying a very large returndata
// returned by a malicious contract
assembly {
_success := call(
_gas, // gas
_recipient, // recipient
0, // ether value
add(_calldata, 0x20), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
// limit our copy to 256 bytes
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytes
mstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
// emit process results
emit Process(_messageHash, _success, _returnData);
// reset re-entrancy guard
entered = 1;
}
// ============ Public Functions ============
/**
* @notice Check that the root has been submitted
* and that the optimistic timeout period has expired,
* meaning the root can be processed
* @param _root the Merkle root, submitted in an update, to check
* @return TRUE iff root has been submitted & timeout has expired
*/
function acceptableRoot(bytes32 _root) public view returns (bool) {
uint256 _time = confirmAt[_root];
if (_time == 0) {
return false;
}
return block.timestamp >= _time;
}
/**
* @notice Attempts to prove the validity of message given its leaf, the
* merkle proof of inclusion for the leaf, and the index of the leaf.
* @dev Reverts if message's MessageStatus != None (i.e. if message was
* already proven or processed)
* @dev For convenience, we allow proving against any previous root.
* This means that witnesses never need to be updated for the new root
* @param _leaf Leaf of message to prove
* @param _proof Merkle proof of inclusion for leaf
* @param _index Index of leaf in home's merkle tree
* @return Returns true if proof was valid and `prove` call succeeded
**/
function prove(
bytes32 _leaf,
bytes32[32] calldata _proof,
uint256 _index
) public returns (bool) {
// ensure that message has not been proven or processed
require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None");
// calculate the expected root based on the proof
bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index);
// if the root is valid, change status to Proven
if (acceptableRoot(_calculatedRoot)) {
messages[_leaf] = MessageStatus.Proven;
return true;
}
return false;
}
/**
* @notice Hash of Home domain concatenated with "OPTICS"
*/
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(remoteDomain);
}
// ============ Internal Functions ============
/**
* @notice Moves the contract into failed state
* @dev Called when a Double Update is submitted
*/
function _fail() internal override {
_setFailed();
}
/// @notice Hook for potential future use
// solhint-disable-next-line no-empty-blocks
function _beforeUpdate() internal {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), 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 {
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 virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.11;
interface IMessageRecipient {
function handle(
uint32 _origin,
bytes32 _sender,
bytes memory _message
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 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.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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;
}
}
|
Hash of Home domain concatenated with "OPTICS"/
|
function homeDomainHash() public view override returns (bytes32) {
return _homeDomainHash(localDomain);
}
| 1,209,274
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "./DVinMembership.sol";
import "./EIP712Whitelisting.sol";
error RoundDisabled(uint256 round);
error InvalidTier(uint256 tier);
error FailedToMint();
error LengthMismatch();
error PurchaseLimitExceeded();
error InsufficientValue();
error RoundLimitExceeded();
error FailedToSendETH();
/// @title DVin Membership Sale
/// @notice Sale contract with authorization to mint tokens on the DVin NFT contract
contract DVinMint is EIP712Whitelisting {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /*Role used to permission admin minting*/
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE"); /*Role used to permission contract configuration changes*/
address payable public ethSink; /*recipient for ETH*/
mapping(uint256 => address) public tierContracts; /*Contracts for different tier options*/
uint256 public limitPerPurchase; /*Max amount of tokens someone can buy in one transaction*/
/* Track when presales and public sales are allowed */
enum ContractState {
Presale,
Public
}
mapping(ContractState => bool) public contractState; /*Track which state is enabled*/
/* Track prices and limits for sales*/
struct SaleConfig {
uint256 price;
uint256 limit;
}
mapping(uint256 => SaleConfig) public presaleConfig; /*Configuration for presale*/
mapping(uint256 => SaleConfig) public publicConfig; /*Configuration for public sale*/
/// @notice Constructor configures sale parameters
/// @dev Sets external contract addresses, sets up roles
/// @param _tiers Token types
/// @param _addresses Token addresses
/// @param _sink Address to send sale ETH to
constructor(
uint256[] memory _tiers,
address[] memory _addresses,
address payable _sink
) EIP712Whitelisting("DVin") {
_setupRole(MINTER_ROLE, msg.sender); /*Grant role to deployer for admin minting*/
_setupRole(OWNER_ROLE, msg.sender); /*Grant role to deployer for config changes*/
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); /*Grant role to deployer for access control changes*/
ethSink = _sink; /*Set address to send ETH to*/
setTierContracts(_tiers, _addresses); /*Set contracts to use for types*/
}
/*****************
EXTERNAL MINTING FUNCTIONS
*****************/
/// @notice Mint tokens by authorized address - useful for people buying with CC
/// @param _tier Which token type to purchase
/// @param _dst Where to send tokens
/// @param _qty Quantity to send
function mintTierAdmin(
uint256 _tier,
address _dst,
uint256 _qty
) public onlyRole(MINTER_ROLE) {
if (tierContracts[_tier] == address(0)) revert InvalidTier(_tier); /*Ensure tier contract is populated*/
if (!DVin(tierContracts[_tier]).mint(_dst, _qty)) revert FailedToMint(); /*Mint token by admin to specified address*/
}
function mintTierAdminBatch(
uint256[] calldata _tiers,
address[] calldata _dsts,
uint256[] calldata _qtys
) public onlyRole(MINTER_ROLE) {
if (_tiers.length != _dsts.length || _dsts.length != _qtys.length)
revert LengthMismatch();
for (uint256 index = 0; index < _tiers.length; index++) {
mintTierAdmin(_tiers[index], _dsts[index], _qtys[index]);
}
}
/// @notice Mint presale by qualified address.
/// @dev Presale state must be enabled
/// @param _tier Which token type to purchase
/// @param _qty How many tokens to buy
/// @param _nonce Whitelist signature nonce
/// @param _signature Whitelist signature
function purchaseTokenPresale(
uint256 _tier,
uint256 _qty,
uint256 _nonce,
bytes calldata _signature
) external payable requiresWhitelist(_signature, _nonce) {
if (!contractState[ContractState.Presale])
revert RoundDisabled(uint256(ContractState.Presale)); /*Presale must be enabled*/
if (presaleConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/
SaleConfig memory _config = presaleConfig[_tier]; /*Fetch sale config*/
_purchase(_tier, _qty, _config.price, _config.limit); /*Purchase token if all values & limits are valid*/
}
/// @notice Mint presale by anyone
/// @dev Public sale must be enabled
/// @param _tier Which token type to purchase
/// @param _qty How many tokens to buy
function purchaseTokenOpensale(uint256 _tier, uint256 _qty)
external
payable
{
if (!contractState[ContractState.Public])
revert RoundDisabled(uint256(ContractState.Public)); /*Public must be enabled*/
if (publicConfig[_tier].price == 0) revert InvalidTier(_tier); /*Do not allow 0 value purchase. If desired use separate function for free claim*/
_purchase(
_tier,
_qty,
publicConfig[_tier].price,
publicConfig[_tier].limit
); /*Purchase token if all values & limits are valid*/
}
/*****************
INTERNAL MINTING FUNCTIONS AND HELPERS
*****************/
/// @notice Mint tokens and transfer eth to sink
/// @dev Validations:
/// - Msg value is checked in comparison to price and quantity
/// @param _tier Token type to mint
/// @param _qty How many tokens to mint
/// @param _price Price per token
/// @param _limit Max token ID
function _purchase(
uint256 _tier,
uint256 _qty,
uint256 _price,
uint256 _limit
) internal {
if (_qty > limitPerPurchase) revert PurchaseLimitExceeded();
if (msg.value < (_price * _qty)) revert InsufficientValue();
if ((DVin(tierContracts[_tier]).totalSupply() + _qty) > _limit)
revert RoundLimitExceeded();
(bool _success, ) = ethSink.call{value: msg.value}(""); /*Send ETH to sink first*/
if (!_success) revert FailedToSendETH();
if (!DVin(tierContracts[_tier]).mint(msg.sender, _qty))
revert FailedToMint(); /*Mint token by admin to specified address*/
}
/*****************
CONFIG FUNCTIONS
*****************/
/// @notice Set states enabled or disabled as owner
/// @param _state 0: presale, 1: public sale
/// @param _enabled specified state on or off
function setContractState(ContractState _state, bool _enabled)
external
onlyRole(OWNER_ROLE)
{
contractState[_state] = _enabled;
}
/// @notice Set sale proceeds address
/// @param _sink new sink
function setSink(address payable _sink) external onlyRole(OWNER_ROLE) {
ethSink = _sink;
}
/// @notice Set new contracts for types
/// @param _tiers Token types like 1,2
/// @param _addresses Addresses of token contracts
function setTierContracts(
uint256[] memory _tiers,
address[] memory _addresses
) public onlyRole(OWNER_ROLE) {
if (_tiers.length != _addresses.length) revert LengthMismatch();
for (uint256 index = 0; index < _tiers.length; index++) {
tierContracts[_tiers[index]] = _addresses[index];
}
}
/// @notice Set token limits for this sale
/// @param _tier Token type to set
/// @param _presaleLimit Max tokens of this type to sell during presale
/// @param _publicLimit Max tokens of this type to sell during public
function setLimit(
uint256 _tier,
uint256 _presaleLimit,
uint256 _publicLimit
) external onlyRole(OWNER_ROLE) {
presaleConfig[_tier].limit = _presaleLimit;
publicConfig[_tier].limit = _publicLimit;
}
/// @notice Set token limits for this sale
/// @param _tier Token type to set
/// @param _presalePrice Price at which to sell this type during presale
/// @param _opensalePrice Price at which to sell this type during public sale
function setPrice(
uint256 _tier,
uint256 _presalePrice,
uint256 _opensalePrice
) external onlyRole(OWNER_ROLE) {
presaleConfig[_tier].price = _presalePrice;
publicConfig[_tier].price = _opensalePrice;
}
/// @notice Set token limits per purchase
/// @param _limit Max tokens someone can buy at once
function setLimitPerPurchase(uint256 _limit) external onlyRole(OWNER_ROLE) {
limitPerPurchase = _limit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./EIP712Base.sol";
import "./erc721a/extensions/ERC721ABurnable.sol";
contract CloneFactory {
// implementation of eip-1167 - see https://eips.ethereum.org/EIPS/eip-1167
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
result := create(0, clone, 0x37)
}
}
}
error CallerIsNotMinter();
error MaxSupplyExceeded();
error NonceTooLow();
error RecoveredUnauthorizedAddress();
error DeadlineExpired();
error TransfersDisabled();
/// @title DVin Membership NFT
/// @notice NFT contract with upgradeable sale contract and signature based transfers
contract DVin is ERC721ABurnable, Ownable, EIP712Base, Initializable {
using Strings for uint256; /*String library allows for token URI concatenation*/
using ECDSA for bytes32; /*ECDSA library allows for signature recovery*/
bool public tradingEnabled; /*Trading can be disabled by owner*/
string public contractURI; /*contractURI contract metadata json*/
string public baseURI; /*baseURI_ String to prepend to token IDs*/
string private _name; /*Token name override*/
string private _symbol; /*Token symbol override*/
uint256 public maxSupply;
address public minter; /*Contract that can mint tokens, changeable by owner*/
mapping(address => uint256) public nonces; /*maps record of states for signing & validating signatures
Nonces increment each time a permit is used.
Users can invalidate a previously signed permit by changing their account nonce
*/
/*EIP712 typehash for permit to allow spender to send a specific token ID*/
bytes32 constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"
);
/*EIP712 typehash for permit to allow spender to send a specific token ID*/
bytes32 constant UNIVERSAL_PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 nonce,uint256 deadline)"
);
/// @notice constructor configures template contract metadata
constructor() ERC721A("TEMPLATE", "DEAD") initializer {
_transferOwnership(address(0xdead)); /*Disable template*/
}
/// @notice setup configures interfaces and production metadata
/// @param name_ Token name
/// @param symbol_ Token symbol
/// @param _contractURI Metadata location for contract
/// @param baseURI_ Metadata location for tokens
/// @param _minter Authorized address to mint
/// @param _maxSupply Max supply for this token
function setUp(
string memory name_,
string memory symbol_,
string memory _contractURI,
string memory baseURI_,
address _minter,
address _owner,
uint256 _maxSupply
) public initializer {
_name = name_;
_symbol = symbol_;
_setBaseURI(baseURI_); /*Base URI for token ID resolution*/
contractURI = _contractURI; /*Contract URI for marketplace metadata*/
minter = _minter; /*Address authorized to mint */
_currentIndex = _startTokenId();
maxSupply = _maxSupply;
_transferOwnership(_owner);
setUpDomain(name_);
}
function _startTokenId() internal view override(ERC721A) returns (uint256) {
return 1;
}
/*****************
Permissioned Minting
*****************/
/// @dev Mint the token for specified tier by authorized minter contract or EOA
/// @param _dst Recipient
/// @param _qty Number of tokens to send
function mint(address _dst, uint256 _qty) external returns (bool) {
if (msg.sender != minter) revert CallerIsNotMinter(); /*Minting can only be done by minter address*/
if ((totalSupply() + _qty) > maxSupply) revert MaxSupplyExceeded(); /*Cannot exceed max supply*/
_safeMint(_dst, _qty); /*Send token to new recipient*/
return true; /*Return success to external caller*/
}
/*****************
Permit & Guardian tools
*****************/
/// @notice Manually update nonce to invalidate previously signed permits
/// @dev New nonce must be higher than current to prevent replay
/// @param _nonce New nonce
function setNonce(uint256 _nonce) external {
if (_nonce <= nonces[msg.sender]) revert NonceTooLow(); /*New nonce must be higher to prevent replay*/
nonces[msg.sender] = _nonce; /*Set new nonce for sender*/
}
/// @notice Transfer token on behalf of owner using signed authorization
/// Useful to help people authorize a guardian to rescue tokens if access is lost
/// @dev Signature can be either per token ID or universal
/// @param _owner Current owner of token
/// @param _tokenId Token ID to transfer
/// @param _dst New recipient
/// @param _deadline Date the permit must be used by
/// @param _signature Concatenated RSV of sig
function transferWithUniversalPermit(
address _owner,
uint256 _tokenId,
address _dst,
uint256 _deadline,
bytes calldata _signature
) external {
bytes32 structHash = keccak256(
abi.encode(
UNIVERSAL_PERMIT_TYPEHASH,
_owner,
msg.sender,
nonces[_owner]++, /*Increment nonce to prevent replay*/
_deadline
)
); /*calculate EIP-712 struct hash*/
bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/
address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/
if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/
if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/
_approve(msg.sender, _tokenId, _owner);
safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/
}
/// @notice Transfer token on behalf of owner using signed authorization
/// Useful to help people authorize a guardian to rescue tokens if access is lost
/// @dev Signature can be either per token ID or universal
/// @param _owner Current owner of token
/// @param _tokenId Token ID to transfer
/// @param _dst New recipient
/// @param _deadline Date the permit must be used by
/// @param _signature Concatenated RSV of sig
function transferWithPermit(
address _owner,
uint256 _tokenId,
address _dst,
uint256 _deadline,
bytes calldata _signature
) external {
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
msg.sender,
_tokenId,
nonces[_owner]++, /*Increment nonce to prevent replay*/
_deadline
)
); /*calculate EIP-712 struct hash*/
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash)
); /*calculate EIP-712 digest for signature*/
address recoveredAddress = digest.recover(_signature); /*Attempt to recover signer*/
if (recoveredAddress != _owner) revert RecoveredUnauthorizedAddress(); /*check signer is `owner`*/
if (block.timestamp > _deadline) revert DeadlineExpired(); /*check signature is not expired*/
_approve(msg.sender, _tokenId, _owner);
safeTransferFrom(_owner, _dst, _tokenId); /*Move token to new wallet*/
}
/*****************
CONFIG FUNCTIONS
*****************/
/// @notice Set new base URI for token IDs
/// @param baseURI_ String to prepend to token IDs
function setBaseURI(string memory baseURI_) external onlyOwner {
_setBaseURI(baseURI_);
}
/// @notice Enable or disable trading
/// @param _enabled bool to set state on or off
function setTradingState(bool _enabled) external onlyOwner {
tradingEnabled = _enabled;
}
/// @notice Set minting contract
/// @param _minter new minting contract
function setMinter(address _minter) external onlyOwner {
minter = _minter;
}
/// @notice internal helper to update token URI
/// @param baseURI_ String to prepend to token IDs
function _setBaseURI(string memory baseURI_) internal {
baseURI = baseURI_;
}
/// @notice Set new contract URI
/// @param _contractURI Contract metadata json
function setContractURI(string memory _contractURI) external onlyOwner {
contractURI = _contractURI;
}
/*****************
Public interfaces
*****************/
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString(), ".json"))
: "";
}
///@dev Support interfaces for Access Control and ERC721
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721A)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @dev Hook for disabling trading
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal override(ERC721A) {
super._beforeTokenTransfers(from, to, startTokenId, quantity);
if (from != address(0) && to != address(0) && !tradingEnabled)
revert TransfersDisabled();
}
}
/// @title DVin Membership NFT Summoner
/// @notice Clone factory for new membership tiers
contract DVinSummoner is CloneFactory, Ownable {
address public template; /*Template contract to clone*/
constructor(address _template) public {
template = _template;
}
event SummonComplete(
address indexed newContract,
string name,
string symbol,
address summoner
);
/// @notice Public interface for owner to create new membership tiers
/// @param name_ Token name
/// @param symbol_ Token symbol
/// @param _contractURI Metadata for contract
/// @param baseURI_ Metadata for tokens
/// @param _minter Authorized minting address
/// @param _maxSupply Max amount of this token that can be minted
/// @param _owner Owner address of new contract
function summonDvin(
string memory name_,
string memory symbol_,
string memory _contractURI,
string memory baseURI_,
address _minter,
uint256 _maxSupply,
address _owner
) external onlyOwner returns (address) {
DVin dvin = DVin(createClone(template)); /*Create a new clone of the template*/
/*Set up the external interfaces*/
dvin.setUp(
name_,
symbol_,
_contractURI,
baseURI_,
_minter,
_owner,
_maxSupply
);
emit SummonComplete(address(dvin), name_, symbol_, msg.sender);
return address(dvin);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./EIP712Base.sol";
contract EIP712Whitelisting is AccessControl, EIP712Base {
using ECDSA for bytes32;
bytes32 public constant WHITELISTING_ROLE = keccak256("WHITELISTING_ROLE");
mapping(bytes32 => bool) public signatureUsed;
// The typehash for the data type specified in the structured data
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-typehash
// This should match whats in the client side whitelist signing code
// https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L22
bytes32 public constant MINTER_TYPEHASH =
keccak256("Minter(address wallet,uint256 nonce)");
constructor(string memory name) {
setUpDomain(name);
_setupRole(WHITELISTING_ROLE, msg.sender);
}
modifier requiresWhitelist(
bytes calldata signature,
uint256 nonce
) {
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 structHash = keccak256(
abi.encode(MINTER_TYPEHASH, msg.sender, nonce)
);
bytes32 digest = toTypedMessageHash(structHash); /*Calculate EIP712 digest*/
require(!signatureUsed[digest], "signature used");
signatureUsed[digest] = true;
// Use the recover method to see what address was used to create
// the signature on this data.
// Note that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
address recoveredAddress = digest.recover(signature);
require(
hasRole(WHITELISTING_ROLE, recoveredAddress),
"Invalid Signature"
);
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @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() {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
pragma solidity 0.8.10;
contract EIP712Base {
bytes32 internal DOMAIN_SEPARATOR;
function setUpDomain(string memory name) internal {
// This should match whats in the client side whitelist signing code
// https://github.com/msfeldstein/EIP712-whitelisting/blob/main/test/signWhitelist.ts#L12
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
// This should match the domain you set in your client side signing.
keccak256(bytes(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, messageHash)
);
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import "../ERC721A.sol";
/**
* @title ERC721A Burnable Token
* @dev ERC721A Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721ABurnable is ERC721A {
/**
* @dev Burns `tokenId`. See {ERC721A-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
_burn(tokenId, true);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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);
}
}
}
}
// SPDX-License-Identifier: MIT
// Creator: Chiru Labs
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @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 override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @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)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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 override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (
to.isContract() &&
!_checkContractOnERC721Received(from, to, tokenId, _data)
) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return
_startTokenId() <= tokenId &&
tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (
!_checkContractOnERC721Received(
address(0),
to,
updatedIndex++,
_data
)
) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) internal {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* 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, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
|
Set new contracts for types _tiers Token types like 1,2 _addresses Addresses of token contracts
|
function setTierContracts(
uint256[] memory _tiers,
address[] memory _addresses
) public onlyRole(OWNER_ROLE) {
if (_tiers.length != _addresses.length) revert LengthMismatch();
for (uint256 index = 0; index < _tiers.length; index++) {
tierContracts[_tiers[index]] = _addresses[index];
}
}
| 10,009,009
|
pragma solidity ^0.4.24;
contract DAO {
function balanceOf(address addr) public returns (uint);
}
interface RegisterInterface {
function register(string);
}
// auth
contract Auth {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier auth {
require(isAuthorized(msg.sender) == true);
_;
}
function isAuthorized(address src) internal view returns (bool) {
if(src == owner){
return true;
} else {
return false;
}
}
}
contract TokenTimelock is Auth{
constructor() public {
benificiary = msg.sender;
}
uint constant public days_of_month = 30;
uint[] public dateArray;
uint public release_percent = 0;
mapping (uint => bool) public release_map;
uint256 public totalFutureRelease = 0;
// cosToken address,
address constant public contract_addr = 0x589891a198195061cb8ad1a75357a3b7dbadd7bc;
address public benificiary;
uint public startTime;
bool public lockStart = false;
// set total cos to lock
function set_total(uint256 total) auth public {
require(lockStart == false);
totalFutureRelease = total;
}
// set month to release
function set_lock_info(int startMonth,int periods,int percent,int gap) auth public {
require(lockStart == false);
require(startMonth > 0);
require(periods > 0);
require(percent > 0);
require(gap > 0);
require(periods * percent == 100);
release_percent = uint(percent);
uint tmp = uint(startMonth);
delete dateArray;
for (int i = 0; i < periods; i++) {
dateArray.push(tmp * days_of_month);
tmp += uint(gap);
}
}
// when transfer certain balance to this contract address, we can call lock
function lock(int offsetMinutes) auth public returns(bool) {
require(lockStart == false);
require(offsetMinutes >= 0);
for(uint i = 0; i < dateArray.length; i++) {
require(dateArray[i] != 0);
}
require(release_percent != 0);
require(totalFutureRelease != 0);
DAO cosTokenApi = DAO(contract_addr);
uint256 balance = cosTokenApi.balanceOf(address(this));
require(balance == totalFutureRelease);
startTime = block.timestamp + uint(offsetMinutes) * 1 minutes;
lockStart = true;
}
function set_benificiary(address b) auth public {
benificiary = b;
}
function release_specific(uint i) private {
if (release_map[i] == true) {
emit mapCheck(true,i);
return;
}
emit mapCheck(false,i);
DAO cosTokenApi = DAO(contract_addr);
uint256 balance = cosTokenApi.balanceOf(address(this));
uint256 eachRelease = 0;
eachRelease = (totalFutureRelease / 100) * release_percent;
bool ok = balance >= eachRelease;
emit balanceCheck(ok,balance);
require(balance >= eachRelease);
bool success = contract_addr.call(bytes4(keccak256("transfer(address,uint256)")),benificiary,eachRelease);
emit tokenTransfer(success);
require(success);
release_map[i] = true;
}
event mapCheck(bool ok,uint window);
event balanceCheck(bool ok,uint256 balance);
event tokenTransfer(bool success);
function release() auth public {
require(lockStart == true);
require(release_map[dateArray[dateArray.length-1]] == false);
uint theDay = dayFor();
for (uint i=0; i<dateArray.length;i++) {
if(theDay > dateArray[i]) {
release_specific(dateArray[i]);
}
}
}
// days after lock
function dayFor() view public returns (uint) {
uint timestamp = block.timestamp;
return timestamp < startTime ? 0 : (timestamp - startTime) / 1 days + 1;
}
function regist(string key) auth public {
RegisterInterface(contract_addr).register(key);
}
}
|
set month to release
|
function set_lock_info(int startMonth,int periods,int percent,int gap) auth public {
require(lockStart == false);
require(startMonth > 0);
require(periods > 0);
require(percent > 0);
require(gap > 0);
require(periods * percent == 100);
release_percent = uint(percent);
uint tmp = uint(startMonth);
delete dateArray;
for (int i = 0; i < periods; i++) {
dateArray.push(tmp * days_of_month);
tmp += uint(gap);
}
}
| 12,965,412
|
./full_match/80001/0x384acAD9ABE419A30CB3Fd232370fCe79920c1aC/sources/contracts-link/StakeManager.sol
|
maps relay managers to their stakes @inheritdoc IStakeManager
|
function getStakeInfo(address relayManager) external override view returns (StakeInfo memory stakeInfo, bool isSenderAuthorizedHub) {
bool isHubAuthorized = authorizedHubs[relayManager][msg.sender].removalTime == type(uint256).max;
return (stakes[relayManager], isHubAuthorized);
}
| 5,678,564
|
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
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;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
}
|
inject NONSTANDARD NAMING
|
function LOGBYTES1678(bytes16 p0) internal view {
| 1,018,859
|
./partial_match/1/0x0b1D5984085fD2FD4819ccDCB026dD7A508526B0/sources/CEFIStaker.sol
|
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, IERC20 _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,
accCefiPerShare: 0
}));
}
| 2,690,976
|
./full_match/80001/0x127de82890D5298dE64bf7dbdde059e2a665e615/sources/base/ERC721Drop.sol
|
Checks whether platform fee info can be set in the given execution context.
|
function _canSetClaimConditions() internal view virtual override returns (bool) {
return msg.sender == owner() || hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 839,616
|
./partial_match/56/0xBEe043b549B201269b3DD127d415f2aBE5C0cb8c/sources/MasterChef.sol
|
Deposit LP tokens to MasterChef for BITD allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accBITDPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeBITDTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accBITDPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 11,246,673
|
./partial_match/1/0x63D1cD65FBba57A30467198eBc2aAb78A06aB245/sources/KFIStaker.sol
|
calculates stakeholders latest unclaimed earningsrecords the number of days between the last payout time and nowreturns earnings based on daily ROI and active days
|
function calculateEarnings(address _stakeholder) public view returns(uint) {
uint activeDays = (now.sub(lastClock[_stakeholder])).div(86400);
return ((stakes[_stakeholder]).mul(dailyROI).mul(activeDays)).div(10000);
}
| 2,623,715
|
/**
*Submitted for verification at Etherscan.io on 2021-09-08
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
contract PasvTimelock {
address admin;
uint256 public totalAllocated = 0;
struct Founder {
uint256 amountWithdrawn;
uint256 totalAmountLocked;
}
mapping(address => Founder) public founders;
uint256 public immutable start;
uint256 public immutable totalAmountTimelocked = 50000000000000;
uint256 public totalAmountWithdrawn = 0;
mapping(uint256 => uint256) private percentageAvailableByDays;
constructor() {
start = block.timestamp;
admin = msg.sender;
_setWithdrawalSchedule();
}
function _setWithdrawalSchedule() internal {
uint256 currentPercentage = 0;
uint256 startDay = 7;
while (currentPercentage <= 100) {
percentageAvailableByDays[startDay] = currentPercentage += 10;
startDay += 7;
}
}
function addFounder(
address _founderAddress,
uint256 _amountLocked
) external {
require(msg.sender == admin, "Caller must be admin");
require(
founders[_founderAddress].totalAmountLocked == 0,
"Address has already been added"
);
require(_founderAddress != address(0), "Cannot add address(0)");
require(
(totalAllocated + _amountLocked) <= totalAmountTimelocked,
"Suggested allocation exceeds amount in timelock"
);
founders[_founderAddress].totalAmountLocked = _amountLocked;
founders[_founderAddress].amountWithdrawn = 0;
totalAllocated += _amountLocked;
}
receive() external payable {}
function withdraw(address token) external {
require(
founders[msg.sender].totalAmountLocked > 0,
"only founder accessible"
);
require(token != address(0));
require((block.timestamp >= start + 7 days),
"should not be able to withdraw yet"
);
address owner = msg.sender;
uint256 currentElapsedTime = block.timestamp - start;
uint256 currentElapsedDays = (currentElapsedTime / 86400);
uint256 standardWithdrawalDay =
(currentElapsedDays - (7)) -
((currentElapsedDays - (7)) % 7) +
(7);
uint256 percentageAvailableToOwner = percentageAvailableByDays[standardWithdrawalDay];
uint256 amountAvailableToOwner = ((percentageAvailableToOwner) *
founders[msg.sender].totalAmountLocked) / 100;
uint256 amountAvailableForWithdrawal = amountAvailableToOwner -
founders[msg.sender].amountWithdrawn;
require(
amountAvailableForWithdrawal > 0,
"Nothing available for withdrawal"
);
require(
(amountAvailableForWithdrawal + totalAmountWithdrawn) <
totalAmountTimelocked,
"Claim more than amount designated for withdrawal"
);
IERC20(token).transfer(owner, amountAvailableForWithdrawal);
totalAmountWithdrawn += amountAvailableForWithdrawal;
founders[owner].amountWithdrawn += amountAvailableForWithdrawal;
}
// Functions for testing
function checkFounderAllocation(address _founder)
external
view
returns (uint256)
{
return founders[_founder].totalAmountLocked;
}
function checkAvailability(uint256 _daysElapsed)
external
view
returns (uint256)
{
uint256 standardWithdrawalDay = (_daysElapsed - (7)) -
((_daysElapsed - (7)) % 7) +
(7);
return percentageAvailableByDays[standardWithdrawalDay];
}
function checkAmountAvailable(uint256 _percentAvailable)
external
view
returns (uint256)
{
return
(_percentAvailable * founders[msg.sender].totalAmountLocked) / 100;
}
function checkAmountWithdrawn() external view returns (uint256) {
return founders[msg.sender].amountWithdrawn;
}
}
|
Functions for testing
|
function checkFounderAllocation(address _founder)
external
view
returns (uint256)
{
return founders[_founder].totalAmountLocked;
}
| 6,708,237
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.0;
// --- INTERFACES ---
// Interfaces for Uniswap and MakerDao
//
// CDP Interface
contract DssCdpManagerLike {
mapping (address => uint) public first; // Owner => First CDPId
mapping (uint => address) public urns; // CDPId => UrnHandler
}
// Vat Interface
contract VatLike {
struct Ilk {
uint256 Art; // Total Normalised Debt [wad]
uint256 rate; // Accumulated Rates [ray]
uint256 spot; // Price with Safety Margin [ray]
uint256 line; // Debt Ceiling [rad]
uint256 dust; // Urn Debt Floor [rad]
}
struct Urn {
uint256 ink; // Locked Collateral [wad]
uint256 art; // Normalised Debt [wad]
}
mapping (bytes32 => Ilk) public ilks;
mapping (bytes32 => mapping (address => Urn)) public urns;
}
// Proxy Registry Interface
interface ProxyRegistryLike {
function proxies(address)
external
view
returns (address);
// build proxy contract
function build()
external;
}
// Very basic Erc-20 like token interface
interface TokenLike {
function approve(address usr, uint wad)
external
returns (bool);
function balanceOf(address account)
external
view
returns (uint256);
function withdraw(uint wad) external;
function allowance(address owner,address spender)
external
view
returns (uint256);
}
// Uniswap Router Interface
interface UniswapV2Router02Like {
function WETH() external returns (address);
function swapExactTokensForETH(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
returns (uint[] memory amounts);
}
// Uniswap Factory Interface
interface UniswapV2FactoryLike{
function getPair(address tokenA,
address tokenB
)
external
view
returns (address pair);
}
// Uniswap Pair Interface
interface UniswapV2PairLike {
function getReserves()
external
view
returns (uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
// --- HELPER CONTRACT ---
// Contract stores the state variables and very basic helper functions
//
contract HelperContract {
address payable owner;
address DssProxyActions = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038;
address CPD_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
address MCD_VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B;
address MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
address ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A;
address DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
bytes32 ilk = 0x4554482d41000000000000000000000000000000000000000000000000000000;
address DAI_TOKEN = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address UNI_Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address UNI_Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address Wrapped_ETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address MCD_PROXY_REGISTRY = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4;
address MCD_UrnHandler;
address public proxy;
uint256 public cdpi;
uint8 public loopCount;
DssCdpManagerLike dcml = DssCdpManagerLike(CPD_MANAGER);
ProxyRegistryLike prl = ProxyRegistryLike(MCD_PROXY_REGISTRY);
UniswapV2Router02Like url = UniswapV2Router02Like(UNI_Router);
UniswapV2FactoryLike uv2 = UniswapV2FactoryLike(UNI_Factory);
TokenLike dai = TokenLike(DAI_TOKEN);
TokenLike weth = TokenLike(url.WETH());
VatLike vat = VatLike(MCD_VAT);
//
// Modifiers
//
// Ensure only the deployer of the contract can interact with ´onlyMyself´ flagged functions
modifier onlyMyself {
require(tx.origin == owner, "Your not the owner");
_;
}
// Ensure only the DS Proxy doesn't already have opened a Vault
modifier NoExistingCDP {
require(cdpi == 0, "There exists already a CDP");
_;
}
// Ensure only the Contract doesn't already have a DS Proxy
modifier NoExistingProxy {
require(proxy == address(0), "There exists already a Proxy");
_;
}
//
// Helper Function
//
// Return minimum and maximum draw amount of DAI
function getMinAndMaxDraw(uint input)
public
view
onlyMyself
returns (uint[2] memory) {
(,uint rate,uint spot,,uint dust) = vat.ilks(ilk);
(uint balance, uint dept) = vat.urns(ilk, MCD_UrnHandler);
uint ethbalance = balance + input;
return [dust/rate, ethbalance*spot/rate-dept];
}
// get Uniswap's exchange rate of DAI/WETH
function getExchangeRate()
public
view
onlyMyself
returns(uint) {
(uint a, uint b) = getTokenReserves_uni() ;
return a/b;
}
// get token reserves from the pool to determine the current exchange rate
function getTokenReserves_uni()
public
view
onlyMyself
returns (uint, uint) {
address pair = uv2.getPair(DAI_TOKEN,address(weth));
(uint reserved0, uint reserved1,) = UniswapV2PairLike(pair).getReserves();
return (reserved0, reserved1);
}
// This contracts ether balance
function daiBalance()
public
view
onlyMyself
returns (uint){
return dai.balanceOf(address(this));
}
// This contracts weth balance
function wethBalance()
public
view
onlyMyself
returns (uint){
return weth.balanceOf(address(this));
}
// Check if Uniswap's Router is approved to transfer Dai
function daiAllowanceApproved()
public
view
onlyMyself
returns (uint) {
return dai.allowance(address(this),UNI_Router);
}
// This contracts' vault balance
function vaultBalance()
public
view
onlyMyself
returns (uint[2] memory){
(uint coll, uint dept) = vat.urns(ilk, MCD_UrnHandler);
return [coll, dept];
}
// This contracts' vault balance incl. collaterals locked
function vaultEndBalance()
public
view
onlyMyself
returns (uint){
(uint coll, ) = vat.urns(ilk, MCD_UrnHandler);
return address(this).balance + coll;
}
}
// --- CALLER CONTRACT ---
// Contract stores the functions that interact with the protocols of MakerDao and Uniswap
//
contract CallerContract is HelperContract{
// Build DS Proxy for the CallerContract
function buildProxy() NoExistingProxy public {
prl.build();
proxy = prl.proxies(address(this)); // Safe proxy address to state variable
}
// Open CDP, lock some Eth and draw Dai
function openLockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself NoExistingCDP {
bytes memory payload = abi.encodeWithSignature("openLockETHAndDraw(address,address,address,address,bytes32,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
ilk,
drawAmount
);
(bool success, ) = proxy.call{
value:input
}(abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions, payload)
);
cdpi = dcml.first(proxy);
MCD_UrnHandler = dcml.urns(cdpi);
}
// Lock some Eth and draw Dai
function lockETHAndDraw(uint input, uint drawAmount) public payable onlyMyself {
bytes memory payload = abi.encodeWithSignature("lockETHAndDraw(address,address,address,address,uint256,uint256)",
address(dcml),
MCD_JUG,
ETH_JOIN,
DAI_JOIN,
cdpi,
drawAmount
);
(bool success, ) = proxy.call{
value:input
}(abi.encodeWithSignature(
"execute(address,bytes)",
DssProxyActions, payload)
);
}
// Approve Uniswap to take Dai tokens
function approveUNIRouter(uint value)
public
onlyMyself {
(bool success) = dai.approve(UNI_Router, value);
require(success);
}
// Execute Swap from Dai to Weth on Uniswap
function swapDAItoETH(uint value_in, uint value_out)
public
onlyMyself
returns (uint[] memory amounts) {
address[] memory path = new address[](2);
path[0] = address(DAI_TOKEN);
path[1] = url.WETH();
// IN and OUT amounts
uint amount_in = value_in;
uint amount_out = value_out;
amounts = url.swapExactTokensForETH(amount_in,
amount_out,
path,
address(this),
block.timestamp + 60
);
return amounts;
}
// Swap WETH to ETH
function wethToEthSwap()
public
onlyMyself {
weth.withdraw(wethBalance());
}
// Pay back contract's ether to owner
function payBack()
public
onlyMyself {
owner.transfer(address(this).balance);
}
fallback() external payable{}
receive() external payable{}
}
// --- ETH LEVERAGE CONTRACT ---
// Main Interface to interact with the CallerContract
//
contract EthLeverager is CallerContract {
constructor() payable {
owner = payable(msg.sender);
}
//
// Single Round - Action function to execute the magic within one transaction
//
// Input: ExchangeRate DAI/ETH (1855), price tolerance in wei (1000000000)
function action(uint rate, uint offset)
payable
onlyMyself
public {
// Ensure that the exchange rate didn't change dramatically
uint exchangeRate = getExchangeRate();
require(exchangeRate >= rate - offset
&&
exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small"
);
uint input = msg.value;
uint drawAmount = getMinAndMaxDraw(input)[1];
uint eth_out = drawAmount/(exchangeRate+offset);
if (proxy == address(0)) {
buildProxy();
}
if (cdpi == 0){
openLockETHAndDraw(input, drawAmount);
} else {
lockETHAndDraw(input, drawAmount);
}
require(daiBalance()>0, "SR - Problem with lock and draw");
approveUNIRouter(drawAmount);
require(daiAllowanceApproved() > 0, "SR - Problem with Approval");
swapDAItoETH(drawAmount, eth_out);
}
//
// Mulitple Rounds - Action function to execute the magic within one transaction
//
// Input: Leverage factor (ex. 150), exchangeRate DAI/ETH (ex. 1855), price tolerance in wei (ex. 1000000000)
function action(uint leverage, uint rate, uint offset)
payable
onlyMyself
public {
// Leverage factor cannot be risen above 2.7x
require(leverage >= 100 && leverage < 270, "Leverage factor must be somewhere between 100 and 270");
// Ensure that the exchange rate didn't change dramatically
uint exchangeRate = getExchangeRate();
require(exchangeRate >= rate - offset
&&
exchangeRate <= rate + offset, "Exchange Rate might have changed or offset too small"
);
// Desired ether amount at the end
uint goal = msg.value*leverage/100;
if (proxy == address(0)) {
buildProxy();
}
uint input = msg.value;
uint[2] memory draw = getMinAndMaxDraw(input);
uint minDraw = draw[0];
uint drawAmount = draw[1];
uint eth_out = drawAmount/(exchangeRate+offset);
uint vault = vaultBalance()[0];
loopCount = 0;
while ((vault < goal) && (drawAmount > minDraw)) {
require(drawAmount > 0, "MR - Draw is zero");
require(eth_out > 0, "MR - ETH out is zero");
if (cdpi == 0){
openLockETHAndDraw(input, drawAmount);
} else {
lockETHAndDraw(input, drawAmount);
}
require(daiBalance() > 0, "MR - Problem with lock and draw");
approveUNIRouter(drawAmount);
require(daiAllowanceApproved() > 0, "MR - Problem with approval");
swapDAItoETH(drawAmount, eth_out);
require(address(this).balance > 0, "MR - Problem with the swap");
input = address(this).balance;
draw = getMinAndMaxDraw(input);
minDraw = draw[0];
drawAmount = draw[1];
eth_out = drawAmount/(exchangeRate+offset);
vault = vaultBalance()[0];
require(vault > 0, "MR - Problem with the vault");
loopCount += 1;
}
}
}
|
Uniswap Router Interface
|
interface UniswapV2Router02Like {
function WETH() external returns (address);
function swapExactTokensForETH(uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
returns (uint[] memory amounts);
}
| 12,664,144
|
./full_match/4/0x97E5a18A28519c07D6987AC06b989eDA6B0F2038/sources/contracts/SpaceCraft.sol
|
claim TESTAs reward
|
function claim(uint256 _pid) public nonReentrant afterStartBlock(_pid) {
PoolInfo storage pool = poolInfo[_pid];
require(maxState == currState, "claim fail: unmatched condition.");
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending =
user
.amount
.mul(pool.accTestaPerShare)
.div(1e12)
.sub(user.rewardDebt)
.add(user.accReward);
uint256 farmBal = getTestaFarmBalance();
uint256 rest = pending - Math.min(pending, farmBal);
user.accReward = rest;
if (pending > 0) {
safeTestaTransfer(address(msg.sender), pending);
}
user.rewardDebt = user.amount.mul(pool.accTestaPerShare).div(1e12);
emit Claim(msg.sender, _pid, pending);
}
| 12,380,589
|
./partial_match/42/0x66Eec3A5AA2E63Cc817E7417eECC3D52d0E1a857/sources/ExchangeV1.sol
|
Sig calldata buyerFeeSig,validateOrderSig(order, sig);validateBuyerFeeSig(order, buyerFee, buyerFeeSig);
|
function exchange5(
Order calldata order,
Sig calldata sig,
uint buyerFee,
uint amount,
address buyer
) payable external {
uint paying = order.buying.mul(amount).div(order.selling);
verifyOpenAndModifyOrderState(order.key, order.selling, amount);
require(order.key.sellAsset.assetType != AssetType.ETH, "ETH is not supported on sell side");
if (order.key.buyAsset.assetType == AssetType.ETH) {
validateEthTransfer(paying, buyerFee);
}
FeeSide feeSide = getFeeSide(order.key.sellAsset.assetType, order.key.buyAsset.assetType);
if (buyer == address(0x0)) {
buyer = msg.sender;
}
transferWithFeesPossibility3(order.key.sellAsset, amount, order.key.owner, buyer, feeSide == FeeSide.SELL, buyerFee, order.sellerFee, order.key.buyAsset);
transferWithFeesPossibility3(order.key.buyAsset, paying, msg.sender, order.key.owner, feeSide == FeeSide.BUY, order.sellerFee, buyerFee, order.key.sellAsset);
emitBuy(order, amount, buyer);
}
| 3,297,214
|
pragma solidity 0.6.0;
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) {
// Solidity only automatically asserts when dividing by 0
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;
}
}
pragma solidity 0.6.0;
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) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` pnch to
* `recipient`, forwarding all available gas and reverting on errors.
*
*/
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");
}
}
pragma solidity 0.6.0;
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
pragma solidity 0.6.0;
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity 0.6.0;
contract Ownable {
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 = msg.sender;
_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 == msg.sender, "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 {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity 0.6.0;
contract MyFT is Ownable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
/**
* @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);
// Mapping from eth address to nch address
mapping (string => address) public addrs;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private tokenOwners;
// 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;
// Optional mapping for token URIs
mapping(uint256 => string) private tokenURIs;
// Base URI
string public baseURI;
// Token name
string private _name;
// Token symbol
string private _symbol;
constructor () public {
_name = "BEE-EGG";
_symbol = "BEE-EGG";
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0), "NRC721: balance query for the zero address");
return holderTokens[_owner].length();
}
function balanceOfWithETHAddr(string memory _ethAddress) public view returns (uint256) {
address owner = addrs[_ethAddress];
return balanceOf(owner);
}
/**
* @dev Gets the owner of the specified token ID.
* @param _tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
return tokenOwners.get(_tokenId, "NRC721: owner query for nonexistent token");
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If the token's URI is non-empty and a base URI was set (via
* {_setBaseURI}), it will be added to the token ID's URI as a prefix.
*
* Reverts if the token ID does not exist.
*/
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "NRC721Metadata: URI query for nonexistent token");
string memory _tokenURI = tokenURIs[_tokenId];
// Even if there is a base URI, it is only appended to non-empty token-specific URIs
if (bytes(_tokenURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(baseURI, _tokenURI));
}
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
return holderTokens[_owner].at(_index);
}
function tokenOfOwnerByIndexWithEthAddr(string memory _ethAddress, uint256 _index) public view returns (uint256) {
address owner = addrs[_ethAddress];
return holderTokens[owner].at(_index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
// tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
(uint256 tokenId, ) = tokenOwners.at(_index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner, "NRC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"NRC721: approve caller is not owner nor approved for all"
);
_approve(_to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
require(_exists(_tokenId), "NRC721: approved query for nonexistent token");
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param _operator operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _operator, bool _approved) public {
require(_operator != msg.sender, "NRC721: approve to caller");
operatorApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev beeMint
* call _safeMint to generate new NFT token
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted
*/
function beeMint(string memory _ethAddress, address _to, uint256 _tokenId) public onlyOwner {
// 检查_ethAddress和_nchAddress的绑定关系
address addr = addrs[_ethAddress];
if (addr != address(0)) {
require(addr == _to, "eth address and nch address not match");
}
_safeMint(_to, _tokenId);
addrs[_ethAddress] = _to;
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* Requires the msg.sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public {
require(_isApprovedOrOwner(msg.sender, _tokenId), "NRC721: transfer caller is not owner nor approved");
_safeTransfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* Requires the msg.sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _safeTransfer(address _from, address _to, uint256 _tokenId) internal {
_transfer(_from, _to, _tokenId);
// require(_checkOnNRC721Received(_from, _to, _tokenId, _data), "NRC721: transfer to non NRC721Receiver implementer");
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
require(_exists(_tokenId), "NRC721: operator query for nonexistent token");
address owner = ownerOf(_tokenId);
return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted
*/
function _safeMint(address _to, uint256 _tokenId) internal {
_mint(_to, _tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0), "NRC721: mint to the zero address");
require(!_exists(_tokenId), "NRC721: token already minted");
_beforeTokenTransfer(address(0), _to, _tokenId);
holderTokens[_to].add(_tokenId);
tokenOwners.set(_tokenId, _to);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal {
require(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);
holderTokens[_from].remove(_tokenId);
holderTokens[_to].add(_tokenId);
tokenOwners.set(_tokenId, _to);
emit Transfer(_from, _to, _tokenId);
}
/**
* @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 returns (bool) {
return tokenOwners.contains(_tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
*/
function _setTokenURI(uint256 _tokenId, string memory _tokenURI) internal {
require(_exists(_tokenId), "NRC721Metadata: URI set of nonexistent token");
tokenURIs[_tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI}.
*/
function _setBaseURI(string memory _baseURI) internal {
baseURI = _baseURI;
}
// function _checkOnNRC721Received(address _from, address _to, uint256 _tokenId, bytes memory _data)
// private returns (bool)
// {
// if (!_to.isContract()) {
// return true;
// }
// }
function _approve(address _to, uint256 _tokenId) private {
tokenApprovals[_tokenId] = _to;
emit Approval(ownerOf(_tokenId), _to, _tokenId);
}
function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal { }
}
|
Approves another address to transfer the given token ID The zero address indicates there is no approved address. There can only be one approved address per token at a given time. Can only be called by the token owner or an approved operator. _to address to be approved for the given token ID _tokenId uint256 ID of the token to be approved/
|
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner, "NRC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"NRC721: approve caller is not owner nor approved for all"
);
_approve(_to, _tokenId);
}
| 12,732,117
|
./full_match/1/0xDC14f5dba4eA0175ce8C5351396CE8406d21fb4b/sources/contracts/Auction.sol
|
Ends the auction and transfers the NFT to the highest bidder or back to the seller. The auction must have started and not have ended. The current time must be greater than or equal to the end time./
|
function settleAuction() external whenNotPaused validConfig nonReentrant {
if (block.timestamp < _config.endTime) {
revert AuctionNotEnded();
}
if (auctionData.highestBidder != address(0)) {
IERC721(nftAddress).transferFrom(
address(this),
auctionData.highestBidder,
nftId
);
require(success, 'Transfer failed.');
emit AuctionSettled(auctionData.highestBidder, auctionData.highestBid);
IERC721(nftAddress).safeTransferFrom(address(this), treasury, nftId);
emit AuctionSettled(treasury, 0);
}
}
| 2,933,172
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} 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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-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 ERC20 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 {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-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 virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
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 {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-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 virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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 virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += 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 virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This 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 virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount) internal virtual { }
}
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
}
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.8.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
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);
}
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;
}
}
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping (address => bool) members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping (bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
//
// d8b
// ?88
// 88b
// .d888b,?88,.d88b, d8888b 88bd88b 888 d88'
// ?8b, `?88' ?88d8P' ?88 88P' ` 888bd8P'
// `?8b 88b d8P88b d88 d88 d88888b
// `?888P' 888888P'`?8888P'd88' d88' `?88b,
// 88P'
// d88
// ?8P
//
pragma solidity ^0.8.0;
contract Spork is
Context,
AccessControlEnumerable,
ERC20Burnable,
ERC20Pausable
{
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account set as `owner`.
*
* See {ERC20-constructor}.
*/
constructor(
string memory name,
string memory symbol,
address owner
) ERC20(name, symbol) {
_mint(owner, 528000000 * 10**18);
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to pause"
);
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to unpause"
);
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
|
Unpauses all token transfers. See {ERC20Pausable} and {Pausable-_unpause}. Requirements: - the caller must have the `PAUSER_ROLE`./
|
function unpause() public virtual {
require(
hasRole(PAUSER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have pauser role to unpause"
);
_unpause();
}
| 490,427
|
./full_match/5/0x05a26D772EBA3096a969165f8c9daE766C78976f/sources/src/erc1155/ChronosInventory.sol
|
Fetch supply for multiple tokens/
|
function totalSupplyBatch(uint256[] memory ids) public view returns (uint256[] memory) {
uint256[] memory batchSupply = new uint256[](ids.length);
for (uint256 i = 0; i < ids.length; ++i) {
batchSupply[i] = totalSupply(ids[i]);
}
return batchSupply;
}
| 11,617,752
|
./full_match/4/0x712782565cCa33f2f3F2f267ea07EA66a8C618D5/sources/UniswapV2Router.sol
|
assert(IWETH(WETH).transfer(UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0])); refund dust eth, if any
|
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
_transferInETH(UniswapV2Library.pairFor(factory, path[0], path[1]),amounts[0]);
_swap(amounts, path, to);
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
| 746,152
|
// Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE
pragma solidity >=0.5.10;
import 'ROOT/reporting/IDisputeWindow.sol';
import 'ROOT/libraries/Initializable.sol';
import 'ROOT/reporting/IUniverse.sol';
import 'ROOT/reporting/IReputationToken.sol';
import 'ROOT/reporting/IMarket.sol';
import 'ROOT/ICash.sol';
import 'ROOT/factories/MarketFactory.sol';
import 'ROOT/libraries/math/SafeMathUint256.sol';
import 'ROOT/reporting/IDisputeWindow.sol';
import 'ROOT/libraries/token/VariableSupplyToken.sol';
import 'ROOT/IAugur.sol';
/**
* @title Dispute Window
* @notice A contract used to encapsulate a window of time in which markets can be disputed as well as the pot where reporting fees are collected and distributed.
*/
contract DisputeWindow is Initializable, VariableSupplyToken, IDisputeWindow {
using SafeMathUint256 for uint256;
IAugur public augur;
IUniverse private universe;
ICash public cash;
address public buyParticipationTokens;
uint256 private startTime;
bool public participationTokensEnabled;
uint256 public windowId;
uint256 public duration;
function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, bool _participationTokensEnabled, uint256 _duration, uint256 _startTime, address _erc1820RegistryAddress) public beforeInitialized {
endInitialization();
augur = _augur;
universe = _universe;
duration = _duration;
windowId = _disputeWindowId;
cash = ICash(augur.lookup("Cash"));
buyParticipationTokens = augur.lookup("BuyParticipationTokens");
startTime = _startTime;
participationTokensEnabled = _participationTokensEnabled;
erc1820Registry = IERC1820Registry(_erc1820RegistryAddress);
initialize1820InterfaceImplementations();
}
function onMarketFinalized() public {
IMarket _market = IMarket(msg.sender);
require(universe.isContainerForMarket(_market));
uint256 _currentValidityBond = universe.getOrCacheValidityBond();
uint256 _currentInitialReportBond = universe.getOrCacheDesignatedReportStake();
uint256 _currentNoShowBond = universe.getOrCacheDesignatedReportNoShowBond();
uint256 _validityBond = _market.getValidityBondAttoCash();
uint256 _repBond = _market.getInitialReporter().getSize();
if (_validityBond >= _currentValidityBond / 2) {
validityBondTotal = validityBondTotal.add(_validityBond);
if (_market.isInvalid()) {
invalidMarketsTotal = invalidMarketsTotal.add(_validityBond);
}
}
if (_repBond >= _currentInitialReportBond / 2) {
initialReportBondTotal = initialReportBondTotal.add(_repBond);
if (!_market.designatedReporterWasCorrect()) {
incorrectDesignatedReportTotal = incorrectDesignatedReportTotal.add(_repBond);
}
}
if (_repBond >= _currentNoShowBond / 2) {
designatedReporterNoShowBondTotal = designatedReporterNoShowBondTotal.add(_repBond);
if (!_market.designatedReporterShowed()) {
designatedReportNoShowsTotal = designatedReportNoShowsTotal.add(_repBond);
}
}
}
/**
* @notice Buy tokens which can be redeemed for reporting fees
* @param _attotokens The number of tokens to purchase
* @return bool True
*/
function buy(uint256 _attotokens) public returns (bool) {
buyInternal(msg.sender, _attotokens);
return true;
}
function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool) {
require(msg.sender == buyParticipationTokens);
buyInternal(_buyer, _attotokens);
return true;
}
function buyInternal(address _buyer, uint256 _attotokens) private {
require(participationTokensEnabled, "Cannot buy Participation tokens in initial market dispute windows");
require(_attotokens > 0, "DisputeWindow.buy: amount cannot be 0");
require(isActive(), "DisputeWindow.buy: window is not active");
require(!universe.isForking(), "DisputeWindow.buy: universe is forking");
getReputationToken().trustedDisputeWindowTransfer(_buyer, address(this), _attotokens);
mint(_buyer, _attotokens);
}
/**
* @notice Redeem tokens for reporting fees
* @param _account The account to redeem tokens for
* @return bool True
*/
function redeem(address _account) public returns (bool) {
require(isOver() || universe.isForking(), "DisputeWindow.redeem: window is not over");
uint256 _attoParticipationTokens = balances[_account];
if (_attoParticipationTokens == 0) {
return true;
}
uint256 _cashBalance = cash.balanceOf(address(this));
// Burn tokens and send back REP
uint256 _supply = totalSupply();
burn(_account, _attoParticipationTokens);
require(getReputationToken().transfer(_account, _attoParticipationTokens));
uint256 _feePayoutShare = 0;
if (_cashBalance != 0) {
// Pay out fees
_feePayoutShare = _cashBalance.mul(_attoParticipationTokens).div(_supply);
cash.transfer(_account, _feePayoutShare);
}
augur.logParticipationTokensRedeemed(universe, _account, _attoParticipationTokens, _feePayoutShare);
return true;
}
function getTypeName() public view returns (bytes32) {
return "DisputeWindow";
}
/**
* @return The universe associated with this window
*/
function getUniverse() public view returns (IUniverse) {
return universe;
}
/**
* @return The reputation token associated with this window
*/
function getReputationToken() public view returns (IReputationToken) {
return universe.getReputationToken();
}
/**
* @return When the window begins as a uint256 timestamp
*/
function getStartTime() public view returns (uint256) {
return startTime;
}
/**
* @return When the window ends as a uint256 timestamp
*/
function getEndTime() public view returns (uint256) {
return getStartTime().add(duration);
}
function getWindowId() public view returns (uint256) {
return windowId;
}
/**
* @return Bool indicating if the window has begun and has not yet ended
*/
function isActive() public view returns (bool) {
if (augur.getTimestamp() <= getStartTime()) {
return false;
}
if (augur.getTimestamp() >= getEndTime()) {
return false;
}
return true;
}
/**
* @return Bool indicating if the window has ended
*/
function isOver() public view returns (bool) {
return augur.getTimestamp() >= getEndTime();
}
function onTokenTransfer(address _from, address _to, uint256 _value) internal {
augur.logParticipationTokensTransferred(universe, _from, _to, _value, balances[_from], balances[_to]);
}
function onMint(address _target, uint256 _amount) internal {
augur.logParticipationTokensMinted(universe, _target, _amount, totalSupply(), balances[_target]);
}
function onBurn(address _target, uint256 _amount) internal {
augur.logParticipationTokensBurned(universe, _target, _amount, totalSupply(), balances[_target]);
}
}
|
return When the window begins as a uint256 timestamp/
|
function getStartTime() public view returns (uint256) {
return startTime;
}
| 6,453,361
|
./full_match/5/0xbD6f49305069Ad9285d1673a3b6e2c9e41f480F9/sources/browser/GCLub.sol
|
Generate the uniswap pair path of token -> weth Make the swap
|
function swapTokensForEth() private lockTheSwap {
uint256 tokenAmount = balanceOf(address(this));
uint256 ethAmount = address(this).balance;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
ethAmount = address(this).balance.sub(ethAmount);
emit SwappedTokenForEth(tokenAmount,ethAmount);
}
| 1,948,764
|
./full_match/1/0x6879dD64E7B17690cd8fd9fF9A86C0F73331B7f1/sources/NftInatorDemoContract.sol
|
PUBLIC MINT FUNCTIONS Mints tokens to an address in batch. fee may or may not be required _to address of the future owner of the token _amount number of tokens to mint/
|
function mintToMultiple(address _to, uint256 _amount) public payable {
if(onlyERC20MintingMode) revert OnlyERC20MintingEnabled();
if(_amount == 0) revert MintZeroQuantity();
if(_amount > maxBatchSize) revert TransactionCapExceeded();
if(!mintingOpen) revert PublicMintClosed();
if(mintingOpen && onlyAllowlistMode) revert PublicMintClosed();
if(currentTokenId() + _amount > collectionSize) revert CapExceeded();
if(msg.value != getPrice(_amount, _to)) revert InvalidPayment();
_safeMint(_to, _amount, false);
}
| 8,407,330
|
pragma solidity >=0.6.0 <0.8.0;
// SPDX-License-Identifier: MIT
/*
* @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.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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);
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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/introspection/ERC165.sol
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @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) {
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, reverting 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) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* 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);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* 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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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;
}
}
/**
* @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;
// solhint-disable-next-line no-inline-assembly
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");
// 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(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");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private 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
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @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_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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 _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @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 _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @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 || ERC721.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 _tokenOwners.contains(tokenId);
}
/**
* @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 || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
_holderTokens[to].add(tokenId);
_tokenOwners.set(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); // internal owner
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
}
/**
* @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 () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), 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 {
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 virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ArtisticalLandscape contract
* @dev Extends ERC721 Non-Fungible Token Standard basic implementation
*/
contract ArtisticalLandscape is ERC721, Ownable {
using SafeMath for uint256;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
}
/**
* Set some Bored Apes aside
*/
function grantTokens(address[] calldata recipients) public onlyOwner {
uint l = totalSupply();
for (uint i = 0; i < recipients.length; i++) {
_mint(recipients[i], l + i);
}
}
/**
* Set the base URI to display metadata.
*/
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals Clear metadata (if any)
|
function _burn(uint256 tokenId) internal virtual {
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
| 13,809,032
|
./full_match/62621/0x2f189E99C10FD27D7Be3cBce624be7C90D82c6b6/sources/src2/WindfallOC.sol
|
Check if a user is eligible for rewards. index The index of the user. condition A cached boolean conditon that can be used in _isEligible logic return A boolean indicating if the user is eligible for rewards. solc-disable-next-line unused-vars
|
function _isEligible(uint index, bool condition) internal view virtual returns (bool) {
return (users[index].eligibleForRewards);
}
| 16,310,381
|
// SPDX-License-Identifier: MIT
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Copyright (c) 2020 Ditto Money
Copyright (c) 2021 Goes Up Higher
Copyright (c) 2021 Cryptographic Ultra Money
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.5.17 <0.8.0;
import "./lib/SafeMath.sol";
import "./lib/SafeMathInt.sol";
import "./lib/UInt256Lib.sol";
import "./mocks/Ownable.sol";
import "./mocks/IOracle.sol";
interface ICum {
function totalSupply() external view returns (uint256);
function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256);
}
/**
* @title Cum's Master
* @dev Controller for an elastic supply currency based on the uFragments Ideal Money protocol a.k.a. Ampleforth.
* uFragments operates symmetrically on expansion and contraction. It will both split and
* combine coins to maintain a stable unit price.
*
* This component regulates the token supply of the uFragments ERC20 token in response to
* market oracles.
*/
contract Master is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
// Stable ordering is not guaranteed.
Transaction[] public transactions;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
ICum public cum;
// Market oracle provides the CUM/USD exchange rate as an 18 decimal fixed point number.
IOracle public marketOracle;
// If the current exchange rate is within this fractional distance from the target, no supply
// update is performed. Fixed point number--same format as the rate.
// (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change.
// DECIMALS Fixed point number.
uint256 public deviationThreshold;
// More than this much time must pass between rebase operations.
uint256 public rebaseCooldown;
// Block timestamp of last rebase operation
uint256 public lastRebaseTimestampSec;
// The number of rebase cycles since inception
uint256 public epoch;
uint256 private constant DECIMALS = 18;
// Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256.
// Both are 18 decimals fixed point numbers.
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
// MAX_SUPPLY = MAX_INT256 / MAX_RATE
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
// Rebase will remain restricted to the owner until the final Oracle is deployed and battle-tested.
// Ownership will be renounced after this inital period.
// Start at $.000001
uint256 public targetRate;
int256 public posDamp;
int256 public negDamp;
bool public posRebaseEnabled;
bool public rebaseLocked;
constructor(address _cum) public {
deviationThreshold = 5 * 10 ** (DECIMALS-2);
// Start at .0000142 cents
targetRate = (142 * 10 ** (DECIMALS-8));
negDamp = 2;
posDamp = 20;
rebaseCooldown = 24 hours;
lastRebaseTimestampSec = 1627848000;
epoch = 1;
rebaseLocked = true;
posRebaseEnabled = true;
cum = ICum(_cum);
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Override to ensure that rebases aren't locked when this happens.
*/
function renounceOwnership() public onlyOwner {
require(!rebaseLocked, "Cannot renounce ownership if rebase is locked");
super.renounceOwnership();
}
function setRebaseLocked(bool _locked) external onlyOwner {
rebaseLocked = _locked;
}
function setPosRebaseEnabled() external onlyOwner {
posRebaseEnabled = true;
}
function setPosRebaseDisabled() external onlyOwner {
posRebaseEnabled = false;
}
/**
* @notice Returns true if the cooldown timer has expired since the last rebase.
*
*/
function canRebase() public view returns (bool) {
return ((!rebaseLocked || isOwner()) && lastRebaseTimestampSec.add(rebaseCooldown) < now);
}
function cooldownExpiryTimestamp() public view returns (uint256) {
return lastRebaseTimestampSec.add(rebaseCooldown);
}
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
*/
function rebase() external {
require(tx.origin == msg.sender);
require(canRebase(), "Rebase not allowed");
lastRebaseTimestampSec = now;
epoch = epoch.add(1);
(uint256 exchangeRate, int256 supplyDelta) = getRebaseValues();
if (supplyDelta > 0 && !posRebaseEnabled) {
supplyDelta = 0;
}
uint256 supplyAfterRebase = cum.rebase(epoch, supplyDelta);
assert(supplyAfterRebase <= MAX_SUPPLY);
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
marketOracle.update();
if (epoch < 80) {
incrementTargetRate();
} else {
finalRate();
}
emit LogRebase(epoch, exchangeRate, supplyDelta, now);
}
// Increment by 42%
function incrementTargetRate() internal {
targetRate = targetRate.mul(71).div(50);
}
// Final rate of $1,000,000 per coin
function finalRate() internal {
targetRate = (1 * 10 ** (DECIMALS+6));
}
function setPosDampFactor(int256 pdf) external onlyOwner {
posDamp = pdf;
}
function setNegDampFactor(int256 ndf) external onlyOwner {
negDamp = ndf;
}
/**
* @notice Calculates the supplyDelta and returns the current set of values for the rebase
*
* @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
*
*/
function getRebaseValues() public view returns (uint256, int256) {
uint256 exchangeRate = marketOracle.getData();
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate);
// Apply the dampening factor.
if (supplyDelta < 0) {
supplyDelta = supplyDelta.div(negDamp);
} else {
supplyDelta = supplyDelta.div(posDamp);
}
if (supplyDelta > 0 && cum.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(cum.totalSupply())).toInt256Safe();
}
return (exchangeRate, supplyDelta);
}
/**
* @return Computes the total supply adjustment in response to the exchange rate
* and the targetRate.
*/
function computeSupplyDelta(uint256 rate)
internal
view
returns (int256)
{
if (withinDeviationThreshold(rate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return cum.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
/**
* @param rate The current exchange rate, an 18 decimal fixed point number.
* @return If the rate is within the deviation threshold from the target rate, returns true.
* Otherwise, returns false.
*/
function withinDeviationThreshold(uint256 rate)
internal
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
/**
* @notice Sets the reference to the market oracle.
* @param marketOracle_ The address of the market oracle contract.
*/
function setMarketOracle(IOracle marketOracle_)
external
onlyOwner
{
marketOracle = marketOracle_;
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes calldata data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes memory data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
sub(gas(), 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
}
|
Apply the dampening factor.
|
function getRebaseValues() public view returns (uint256, int256) {
uint256 exchangeRate = marketOracle.getData();
if (exchangeRate > MAX_RATE) {
exchangeRate = MAX_RATE;
}
int256 supplyDelta = computeSupplyDelta(exchangeRate);
if (supplyDelta < 0) {
supplyDelta = supplyDelta.div(negDamp);
supplyDelta = supplyDelta.div(posDamp);
}
if (supplyDelta > 0 && cum.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(cum.totalSupply())).toInt256Safe();
}
return (exchangeRate, supplyDelta);
}
| 12,989,479
|
./partial_match/1/0xB85C245d8A7D651dBf592C6d862FeF014Ab1852e/sources/src/core/organization/modules/Charge.sol
|
Errors / State vars / Gap array, for further state variable changes/ Functions start /
|
function charge(ChargeStruct calldata chargeRequest, Signature calldata signature) external onlyDiagonalBot {
_verifyAndSetNewOperationId(chargeRequest.id);
_verifyChargeSignature(chargeRequest, signature);
_safeCall(
chargeRequest.token,
abi.encodeWithSelector(
ERC20.transferFrom.selector,
chargeRequest.source,
address(this),
chargeRequest.amount
)
);
}
| 16,080,905
|
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
// Inheritance
import "./BaseRewardEscrowV2.sol";
// /contracts/RewardEscrow
contract ImportableRewardEscrowV2 is BaseRewardEscrowV2 {
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_PYNTHETIX_BRIDGE_BASE = "PeriFinBridgeToBase";
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, address _resolver) public BaseRewardEscrowV2(_owner, _resolver) {}
/* ========== VIEWS ======================= */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BaseRewardEscrowV2.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_PYNTHETIX_BRIDGE_BASE;
return combineArrays(existingAddresses, newAddresses);
}
function perifinBridgeToBase() internal view returns (address) {
return requireAndGetAddress(CONTRACT_PYNTHETIX_BRIDGE_BASE);
}
/* ========== MUTATIVE FUNCTIONS ========== */
function importVestingEntries(
address account,
uint256 escrowedAmount,
VestingEntries.VestingEntry[] calldata vestingEntries
) external onlyPeriFinBridge {
// There must be enough balance in the contract to provide for the escrowed balance.
totalEscrowedBalance = totalEscrowedBalance.add(escrowedAmount);
require(
totalEscrowedBalance <= IERC20(address(perifin())).balanceOf(address(this)),
"Insufficient balance in the contract to provide for escrowed balance"
);
/* Add escrowedAmount to account's escrowed balance */
totalEscrowedAccountBalance[account] = totalEscrowedAccountBalance[account].add(escrowedAmount);
for (uint i = 0; i < vestingEntries.length; i++) {
_importVestingEntry(account, vestingEntries[i]);
}
}
function _importVestingEntry(address account, VestingEntries.VestingEntry memory entry) internal {
uint entryID = nextEntryId;
vestingSchedules[account][entryID] = entry;
/* append entryID to list of entries for account */
accountVestingEntryIDs[account].push(entryID);
/* Increment the next entry id. */
nextEntryId = nextEntryId.add(1);
}
modifier onlyPeriFinBridge() {
require(msg.sender == perifinBridgeToBase(), "Can only be invoked by PeriFinBridgeToBase contract");
_;
}
}
|
========== VIEWS ======================= /
|
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = BaseRewardEscrowV2.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](1);
newAddresses[0] = CONTRACT_PYNTHETIX_BRIDGE_BASE;
return combineArrays(existingAddresses, newAddresses);
}
| 15,875,266
|
// File: contracts/interfaces/IDiamondCut.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/******************************************************************************\
* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {Add, Replace, Remove}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// File: contracts/libraries/LibDiamond.sol
pragma solidity 0.8.12;
/******************************************************************************\
* Author: Nick Mudge <nick@perfectabstractions.com> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
//
// The number of function selectors in selectorSlots
uint16 selectorCount;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(msg.sender == diamondStorage().contractOwner, "Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
bytes32 constant CLEAR_ADDRESS_MASK = bytes32(uint256(0xffffffffffffffffffffffff));
bytes32 constant CLEAR_SELECTOR_MASK = bytes32(uint256(0xffffffff << 224));
// Internal function version of diamondCut
// This code is almost the same as the external diamondCut,
// except it is using 'Facet[] memory _diamondCut' instead of
// 'Facet[] calldata _diamondCut'.
// The code is duplicated to prevent copying calldata to memory which
// causes an error for a two dimensional array.
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
DiamondStorage storage ds = diamondStorage();
uint256 originalSelectorCount = ds.selectorCount;
uint256 selectorCount = originalSelectorCount;
bytes32 selectorSlot;
// Check if last selector slot is not full
// "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
if (selectorCount & 7 > 0) {
// get last selectorSlot
// "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
selectorSlot = ds.selectorSlots[selectorCount >> 3];
}
// loop through diamond cut
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
(selectorCount, selectorSlot) = addReplaceRemoveFacetSelectors(
selectorCount,
selectorSlot,
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].action,
_diamondCut[facetIndex].functionSelectors
);
}
if (selectorCount != originalSelectorCount) {
ds.selectorCount = uint16(selectorCount);
}
// If last selector slot is not full
// "selectorCount & 7" is a gas efficient modulo by eight "selectorCount % 8"
if (selectorCount & 7 > 0) {
// "selectorSlot >> 3" is a gas efficient division by 8 "selectorSlot / 8"
ds.selectorSlots[selectorCount >> 3] = selectorSlot;
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addReplaceRemoveFacetSelectors(
uint256 _selectorCount,
bytes32 _selectorSlot,
address _newFacetAddress,
IDiamondCut.FacetCutAction _action,
bytes4[] memory _selectors
) internal returns (uint256, bytes32) {
DiamondStorage storage ds = diamondStorage();
require(_selectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
if (_action == IDiamondCut.FacetCutAction.Add) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Add facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) == address(0), "LibDiamondCut: Can't add function that already exists");
// add facet for selector
ds.facets[selector] = bytes20(_newFacetAddress) | bytes32(_selectorCount);
// "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
uint256 selectorInSlotPosition = (_selectorCount & 7) << 5;
// clear selector position in slot and add selector
_selectorSlot = (_selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) | (bytes32(selector) >> selectorInSlotPosition);
// if slot is full then write it to storage
if (selectorInSlotPosition == 224) {
// "_selectorSlot >> 3" is a gas efficient division by 8 "_selectorSlot / 8"
ds.selectorSlots[_selectorCount >> 3] = _selectorSlot;
_selectorSlot = 0;
}
_selectorCount++;
}
} else if (_action == IDiamondCut.FacetCutAction.Replace) {
enforceHasContractCode(_newFacetAddress, "LibDiamondCut: Replace facet has no code");
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
address oldFacetAddress = address(bytes20(oldFacet));
// only useful if immutable functions exist
require(oldFacetAddress != address(this), "LibDiamondCut: Can't replace immutable function");
require(oldFacetAddress != _newFacetAddress, "LibDiamondCut: Can't replace function with same function");
require(oldFacetAddress != address(0), "LibDiamondCut: Can't replace function that doesn't exist");
// replace old facet address
ds.facets[selector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(_newFacetAddress);
}
} else if (_action == IDiamondCut.FacetCutAction.Remove) {
require(_newFacetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
// "_selectorCount >> 3" is a gas efficient division by 8 "_selectorCount / 8"
uint256 selectorSlotCount = _selectorCount >> 3;
// "_selectorCount & 7" is a gas efficient modulo by eight "_selectorCount % 8"
uint256 selectorInSlotIndex = _selectorCount & 7;
for (uint256 selectorIndex; selectorIndex < _selectors.length; selectorIndex++) {
if (_selectorSlot == 0) {
// get last selectorSlot
selectorSlotCount--;
_selectorSlot = ds.selectorSlots[selectorSlotCount];
selectorInSlotIndex = 7;
} else {
selectorInSlotIndex--;
}
bytes4 lastSelector;
uint256 oldSelectorsSlotCount;
uint256 oldSelectorInSlotPosition;
// adding a block here prevents stack too deep error
{
bytes4 selector = _selectors[selectorIndex];
bytes32 oldFacet = ds.facets[selector];
require(address(bytes20(oldFacet)) != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// only useful if immutable functions exist
require(address(bytes20(oldFacet)) != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector in ds.facets
// gets the last selector
lastSelector = bytes4(_selectorSlot << (selectorInSlotIndex << 5));
if (lastSelector != selector) {
// update last selector slot position info
ds.facets[lastSelector] = (oldFacet & CLEAR_ADDRESS_MASK) | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
uint256 oldSelectorCount = uint16(uint256(oldFacet));
// "oldSelectorCount >> 3" is a gas efficient division by 8 "oldSelectorCount / 8"
oldSelectorsSlotCount = oldSelectorCount >> 3;
// "oldSelectorCount & 7" is a gas efficient modulo by eight "oldSelectorCount % 8"
oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5;
}
if (oldSelectorsSlotCount != selectorSlotCount) {
bytes32 oldSelectorSlot = ds.selectorSlots[oldSelectorsSlotCount];
// clears the selector we are deleting and puts the last selector in its place.
oldSelectorSlot =
(oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
// update storage with the modified slot
ds.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
} else {
// clears the selector we are deleting and puts the last selector in its place.
_selectorSlot =
(_selectorSlot & ~(CLEAR_SELECTOR_MASK >> oldSelectorInSlotPosition)) |
(bytes32(lastSelector) >> oldSelectorInSlotPosition);
}
if (selectorInSlotIndex == 0) {
delete ds.selectorSlots[selectorSlotCount];
_selectorSlot = 0;
}
}
_selectorCount = selectorSlotCount * 8 + selectorInSlotIndex;
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
return (_selectorCount, _selectorSlot);
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function isContract(address _contract) internal view returns (bool) {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
return contractSize > 0;
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
require(isContract(_contract), _errorMessage);
}
}
// File: @openzeppelin/contracts/token/ERC777/IERC777.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// File: @openzeppelin/contracts/token/ERC777/IERC777Sender.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// File: @openzeppelin/contracts/token/ERC777/IERC777Recipient.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC1820Registry.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// File: contracts/facets/MNFTERC777Facet.sol
pragma solidity 0.8.12;
struct ERC777Storage {
mapping(address => uint256) _balances;
uint256 _totalSupply;
string _name;
string _symbol;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) _operators;
mapping(address => mapping(address => bool)) _revokedDefaultOperators;
// ERC20-allowances
mapping(address => mapping(address => uint256)) _allowances;
// Disable reentrancy
uint256 _entered;
// Mapping of partners with associated cashback rate multiplied by 100
// mapping(address => uint16) _partners;
}
contract MNFTERC777Facet is IERC777, IERC20 {
event PartnerAdded(address indexed partner, uint16 cashbackRate);
event PartnerUpdated(address indexed partner, uint16 cashbackRate);
event PartnerRemoved(address indexed partner);
function getERC777Storage() internal pure returns(ERC777Storage storage es) {
// es.slot = keccak256("mnft.erc777.storage")
assembly {
es.slot := 0x8fb040e626dc81be524f960fd04848fa1f8d9000e8b837b9a8ed86951edba988
}
}
/**
* @dev See {IERC777-name}.
*/
function name() external view override returns (string memory) {
ERC777Storage storage es = getERC777Storage();
return es._name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() external view override returns (string memory) {
ERC777Storage storage es = getERC777Storage();
return es._symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() external pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() external pure override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() external view override(IERC20, IERC777) returns (uint256) {
ERC777Storage storage es = getERC777Storage();
return es._totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) external view override(IERC20, IERC777) returns (uint256) {
ERC777Storage storage es = getERC777Storage();
return es._balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(
address recipient,
uint256 amount,
bytes memory data
) external override {
_send(msg.sender, recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(getERC777Storage()._entered == 0, 'Undergoing transaction');
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) external override {
_burn(msg.sender, amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(address operator, address tokenHolder) external view override returns (bool) {
return _isOperatorFor(operator, tokenHolder);
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function _isOperatorFor(address operator, address tokenHolder) internal view returns (bool) {
ERC777Storage storage es = getERC777Storage();
return
operator == tokenHolder ||
(es._defaultOperators[operator] && !es._revokedDefaultOperators[tokenHolder][operator]) ||
es._operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external override {
require(msg.sender != operator, "ERC777: authorizing self as operator");
ERC777Storage storage es = getERC777Storage();
if (es._defaultOperators[operator]) {
delete es._revokedDefaultOperators[msg.sender][operator];
} else {
es._operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external override {
require(operator != msg.sender, "ERC777: revoking self as operator");
ERC777Storage storage es = getERC777Storage();
if (es._defaultOperators[operator]) {
es._revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete es._operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() external view override returns (address[] memory) {
ERC777Storage storage es = getERC777Storage();
return es._defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
) external override {
require(_isOperatorFor(msg.sender, sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(
address account,
uint256 amount,
bytes memory data,
bytes memory operatorData
) external override {
require(_isOperatorFor(msg.sender, account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) external view override returns (uint256) {
ERC777Storage storage es = getERC777Storage();
return es._allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external override returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(
address holder,
address recipient,
uint256 amount
) external override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
ERC777Storage storage es = getERC777Storage();
require(es._entered == 0, 'Undergoing transaction');
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
uint256 currentAllowance = es._allowances[holder][spender];
require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance");
_approve(holder, spender, currentAllowance - amount);
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) external {
LibDiamond.enforceIsContractOwner();
_mint(account, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If `requireReceptionAck` is set to true, and if a send hook is
* registered for `account`, the corresponding function will be called with
* `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal {
require(account != address(0), "ERC777: mint to the zero address");
ERC777Storage storage es = getERC777Storage();
require((es._totalSupply + amount) <= 4200000000000000000000000000 , 'Mint amount exceed total supply');
address operator = msg.sender;
_beforeTokenTransfer(operator, address(0), account, amount);
unchecked {
es._totalSupply += amount;
es._balances[account] += amount;
}
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) internal {
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
require(getERC777Storage()._entered == 0, 'Undergoing transaction');
address operator = msg.sender;
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
) internal {
LibDiamond.enforceIsContractOwner();
require(from != address(0), "ERC777: burn from the zero address");
ERC777Storage storage es = getERC777Storage();
require(es._entered == 0, "Undergoing account transaction");
address operator = msg.sender;
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_beforeTokenTransfer(operator, from, address(0), amount);
// Update state variables
uint256 fromBalance = es._balances[from];
require(fromBalance >= amount, "ERC777: burn amount exceeds balance");
unchecked {
es._balances[from] = fromBalance - amount;
es._totalSupply -= amount;
}
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
_beforeTokenTransfer(operator, from, to, amount);
ERC777Storage storage es = getERC777Storage();
// unchecked {
// amount = amount * 1000 * (10000 - es._partners[to]) / 10000 / 1000;
// }
uint256 fromBalance = es._balances[from];
require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
unchecked {
es._balances[from] = fromBalance - amount;
es._balances[to] += amount;
}
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(
address holder,
address spender,
uint256 value
) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
ERC777Storage storage es = getERC777Storage();
es._allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
address implementer = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24)
.getInterfaceImplementer(from, 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895);
if (implementer != address(0)) {
ERC777Storage storage es = getERC777Storage();
es._entered = 1;
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
es._entered = 0;
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
) private {
address implementer = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24)
.getInterfaceImplementer(to, 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!LibDiamond.isContract(to), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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 operator,
address from,
address to,
uint256 amount
) internal {}
// /**
// @notice Add a new partner with a specific cashback rate
// @param partner The partner's account address.
// @param cashbackRate The cashback rate on transaction with this partner
// */
// function addPartner(address partner, uint16 cashbackRate) external {
// LibDiamond.enforceIsContractOwner();
// require(cashbackRate > 0 && cashbackRate < 10000, "Cashback rate must >0 and <10000");
// ERC777Storage storage es = getERC777Storage();
// require(es._partners[partner] == 0, "Partner already exists.");
// es._partners[partner] = cashbackRate;
// emit PartnerAdded(partner, cashbackRate);
// }
// /**
// @notice Update a partner with a new cashback rate
// @param partner The partner's account address.
// @param cashbackRate The cashback rate on transaction with this partner
// */
// function updatePartner(address partner, uint16 cashbackRate) external {
// LibDiamond.enforceIsContractOwner();
// require(cashbackRate > 0 && cashbackRate < 10000, "Cashback rate must >0 and <10000");
// ERC777Storage storage es = getERC777Storage();
// require(cashbackRate != es._partners[partner], "Cashback rate not modified.");
// es._partners[partner] = cashbackRate;
// emit PartnerUpdated(partner, cashbackRate);
// }
// /**
// @notice Remove partner
// @param partner The partner's account address.
// */
// function removePartner(address partner) external {
// LibDiamond.enforceIsContractOwner();
// ERC777Storage storage es = getERC777Storage();
// delete es._partners[partner];
// emit PartnerRemoved(partner);
// }
function withdrawEth() external {
LibDiamond.enforceIsContractOwner();
(bool os, ) = payable(LibDiamond.diamondStorage().contractOwner).call{value: address(this).balance}("");
require(os);
}
}
// File: contracts/facets/MNFTStakingFacet.sol
pragma solidity 0.8.12;
struct StakingStorage {
uint256 _totalTokensStaked;
address _stakingAccount;
}
contract MNFTStakingFacet {
event Stake(address indexed from, uint256 amount);
event Release(address indexed to, uint256 amount);
event Claim(address indexed from, uint256 amount);
event ClaimAll(address indexed from);
/// @notice Returns the StakingStorage struct pointer.
function getStakingStorage() internal pure returns(StakingStorage storage ss) {
// ss.slot = keccak256("mnft.staking.storage")
assembly {
ss.slot := 0x9d94a552b79e041387c81ff6ef283d25141878a49159d618301326183d77fd04
}
}
/// @notice Returns the ERC777Storage struct pointer.
function getERC777Storage() internal pure returns(ERC777Storage storage es) {
// es.slot = keccak256("mnft.erc777.storage")
assembly {
es.slot := 0x8fb040e626dc81be524f960fd04848fa1f8d9000e8b837b9a8ed86951edba988
}
}
/**
@notice Stake a specific amount of tokens.
@param amount The amount of token to stake.
*/
function stake(uint256 amount) external {
StakingStorage storage ss = getStakingStorage();
ERC777Storage storage es = getERC777Storage();
require(amount <= es._balances[msg.sender], "Unsufficient account balance.");
ss._totalTokensStaked += amount;
(bool success, ) = address(this).delegatecall(abi.encodeWithSignature("send(address,uint256,bytes)", ss._stakingAccount, amount, ""));
require(success, "Send failed");
emit Stake(msg.sender, amount);
}
/**
@notice Claim a specific amount of staked tokens of the sender
(if amount is superior to number of tokens staked by the account, the amount of tokens staked will be released instead).
@param amount The amount of token claimed.
*/
function claim(uint256 amount) external payable {
// require(msg.value > 0.002 ether, "Not enough eth for transaction.");
emit Claim(msg.sender, amount);
}
/// @notice Claim all staked tokens of the sender.
function claimAll() external payable {
// require(msg.value > 0.002 ether, "Not enough eth for transaction.");
emit ClaimAll(msg.sender);
}
/**
@notice Release claimed tokens to the corresponding account.
@param amount The address of the account.
@param amount The amount of token released.
*/
function releaseClaimedTokens(address account, uint256 amount) external {
LibDiamond.enforceIsContractOwner();
StakingStorage storage ss = getStakingStorage();
require(amount <= ss._totalTokensStaked, "Unsufficient tokens staked.");
ss._totalTokensStaked -= amount;
(bool success, ) = address(this).delegatecall(abi.encodeWithSignature("operatorSend(address,address,uint256,bytes,bytes)", ss._stakingAccount, account, amount, "", ""));
require(success, "OperatorSend failed");
emit Release(account, amount);
}
/**
@notice Update staking account.
@param newAccount The address of the new staking account.
*/
function updateStakingAccount(address newAccount) external {
LibDiamond.enforceIsContractOwner();
StakingStorage storage ss = getStakingStorage();
address oldAccount = ss._stakingAccount;
ss._stakingAccount = newAccount;
(bool success, ) = address(this).delegatecall(abi.encodeWithSignature("operatorSend(address,address,uint256,bytes,bytes)", oldAccount, newAccount, ss._totalTokensStaked, "", ""));
require(success, "OperatorSend failed");
}
}
|
unchecked { amount = amount 1000 (10000 - es._partners[to]) / 10000 / 1000; }
|
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
) private {
_beforeTokenTransfer(operator, from, to, amount);
ERC777Storage storage es = getERC777Storage();
uint256 fromBalance = es._balances[from];
require(fromBalance >= amount, "ERC777: transfer amount exceeds balance");
unchecked {
es._balances[from] = fromBalance - amount;
es._balances[to] += amount;
}
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
| 1,690,115
|
./full_match/3/0x3b6b2E390319981311B65E806e3eCFee0CeCC9c1/sources/browser/AMCCoin.sol
|
Run an Air-Drop It requires an array of all the addresses and amount of tokens to distribute It will only process first 150 recipients. That limit is fixed to prevent gas limit/This will loop through all the recipients and send them the specified tokens
|
function airdrop(address[] memory recipients,uint tokenAmount) public onlyOwner {
uint256 addressCount = recipients.length;
require(addressCount <= 150);
for(uint i = 0; i < addressCount; i++)
{
_transfer(address(this), recipients[i], tokenAmount);
}
}
| 8,169,184
|
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
import { Ownable } from "zeppelin-solidity/contracts/ownership/Ownable.sol";
import { SafeMath } from "zeppelin-solidity/contracts/math/SafeMath.sol";
import { AddressArrayUtils } from "cryptofin-solidity/contracts/array-utils/AddressArrayUtils.sol";
/**
* @title Authorizable
* @author Set Protocol
*
* The Authorizable contract is an inherited contract that sets permissions on certain function calls
* through the onlyAuthorized modifier. Permissions can be managed only by the Owner of the contract.
*/
contract Authorizable is
Ownable
{
using SafeMath for uint256;
using AddressArrayUtils for address[];
/* ============ State Variables ============ */
// Time in which authorized addresses can no longer be changed
uint256 public gracePeriodEnd;
// Mapping of addresses to bool indicator of authorization
mapping (address => bool) public authorized;
// Array of authorized addresses
address[] public authorities;
/* ============ Modifiers ============ */
// Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
require(authorized[msg.sender], "SENDER_NOT_AUTHORIZED");
_;
}
/* ============ Events ============ */
// Event emitted when new address is authorized.
event AddressAuthorized (
address indexed authAddress,
address authorizedBy
);
// Event emitted when address is deauthorized.
event AuthorizedAddressRemoved (
address indexed addressRemoved,
address authorizedBy
);
/* ============ Constructor ============ */
/**
* @param _gracePeriod Time period in which authorizations can be added or removed
*/
constructor
(
uint256 _gracePeriod
)
public
{
gracePeriodEnd = block.timestamp.add(_gracePeriod);
}
/* ============ Setters ============ */
/**
* Add authorized address to contract. Can only be set by owner.
*
* @param _authTarget The address of the new authorized contract
*/
function addAuthorizedAddress(address _authTarget)
external
onlyOwner
{
// Require that timestamp is before grace period
require(block.timestamp < gracePeriodEnd, "ADD_GRACE_PERIOD_PASSED");
// Require that address is not already authorized
require(!authorized[_authTarget], "ADDRESS_ALREADY_AUTHORIZED");
// Set address authority to true
authorized[_authTarget] = true;
// Add address to authorities array
authorities.push(_authTarget);
// Emit authorized address event
emit AddressAuthorized(
_authTarget,
msg.sender
);
}
/**
* Remove authorized address from contract. Can only be set by owner.
*
* @param _authTarget The address to be de-permissioned
*/
function removeAuthorizedAddress(address _authTarget)
external
onlyOwner
{
// Require that timestamp is before grace period
require(block.timestamp < gracePeriodEnd, "REMOVE_GRACE_PERIOD_PASSED");
// Require address is authorized
require(authorized[_authTarget], "ADDRESS_NOT_AUTHORIZED"); // Target address must be authorized.
// Delete address from authorized mapping
delete authorized[_authTarget];
authorities = authorities.remove(_authTarget);
// Emit AuthorizedAddressRemoved event.
emit AuthorizedAddressRemoved(
_authTarget,
msg.sender
);
}
/**
* More efficiently remove authorized address from contract. Can only be set by owner.
*
* @param _authTarget The address to be de-permissioned
* @param _index The index of the _authTarget address in authorities
*/
function removeAuthorizedAddressAtIndex(
address _authTarget,
uint256 _index
)
external
onlyOwner
{
// Require that timestamp is before grace period
require(block.timestamp < gracePeriodEnd, "INDEX_REMOVE_GRACE_PERIOD_PASSED");
// Require index is less than length of authorities
require(_index < authorities.length, "INDEX_TOO_LARGE");
// Require address at index of authorities matches target address
require(authorities[_index] == _authTarget, "MISMATCHED_TARGET_ADDRESS");
// Delete address from authorized mapping
delete authorized[_authTarget];
// Replace address at index with address at end of array
authorities[_index] = authorities[authorities.length.sub(1)];
// Remove last address from array
authorities.length = authorities.length.sub(1);
// Emit AuthorizedAddressRemoved event.
emit AuthorizedAddressRemoved(
_authTarget,
msg.sender
);
}
/* ============ Getters ============ */
/**
* Get array of authorized addresses.
*
* @return address[] Array of authorized addresses
*/
function getAuthorizedAddresses()
external
view
returns (address[] memory)
{
// Return array of authorized addresses
return authorities;
}
}
|
Require that timestamp is before grace period Require index is less than length of authorities Require address at index of authorities matches target address Delete address from authorized mapping Replace address at index with address at end of array Remove last address from array Emit AuthorizedAddressRemoved event.
|
function removeAuthorizedAddressAtIndex(
address _authTarget,
uint256 _index
)
external
onlyOwner
{
require(block.timestamp < gracePeriodEnd, "INDEX_REMOVE_GRACE_PERIOD_PASSED");
require(_index < authorities.length, "INDEX_TOO_LARGE");
require(authorities[_index] == _authTarget, "MISMATCHED_TARGET_ADDRESS");
delete authorized[_authTarget];
authorities[_index] = authorities[authorities.length.sub(1)];
authorities.length = authorities.length.sub(1);
emit AuthorizedAddressRemoved(
_authTarget,
msg.sender
);
}
| 1,011,839
|
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping(address => mapping(address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function _burn(address _burner, uint256 _value) internal {
require(_value <= balances[_burner]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_burner] = balances[_burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(_burner, _value);
Transfer(_burner, address(0), _value);
}
}
contract DividendPayoutToken is BurnableToken, MintableToken {
// Dividends already claimed by investor
mapping(address => uint256) public dividendPayments;
// Total dividends claimed by all investors
uint256 public totalDividendPayments;
// invoke this function after each dividend payout
function increaseDividendPayments(address _investor, uint256 _amount) onlyOwner public {
dividendPayments[_investor] = dividendPayments[_investor].add(_amount);
totalDividendPayments = totalDividendPayments.add(_amount);
}
//When transfer tokens decrease dividendPayments for sender and increase for receiver
function transfer(address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[msg.sender];
// invoke super function with requires
bool isTransferred = super.transfer(_to, _value);
uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom);
dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims);
dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);
return isTransferred;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// balance before transfer
uint256 oldBalanceFrom = balances[_from];
// invoke super function with requires
bool isTransferred = super.transferFrom(_from, _to, _value);
uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom);
dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims);
dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);
return isTransferred;
}
function burn() public {
address burner = msg.sender;
// balance before burning tokens
uint256 oldBalance = balances[burner];
super._burn(burner, oldBalance);
uint256 burnedClaims = dividendPayments[burner];
dividendPayments[burner] = dividendPayments[burner].sub(burnedClaims);
totalDividendPayments = totalDividendPayments.sub(burnedClaims);
SaleInterface(owner).refund(burner);
}
}
contract RicoToken is DividendPayoutToken {
string public constant name = "CFE";
string public constant symbol = "CFE";
uint8 public constant decimals = 18;
}
// Interface for PreSale and CrowdSale contracts with refund function
contract SaleInterface {
function refund(address _to) public;
}
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancy_lock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancy_lock);
reentrancy_lock = true;
_;
reentrancy_lock = false;
}
}
contract PreSale is Ownable, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
RicoToken public token;
address tokenContractAddress;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// Address where funds are transferred after success end of PreSale
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
uint256 public minimumInvest; // in wei
uint256 public softCap; // in wei
uint256 public hardCap; // in wei
// investors => amount of money
mapping(address => uint) public balances;
// Amount of wei raised
uint256 public weiRaised;
// PreSale bonus in percent
uint256 bonusPercent;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function PreSale(
uint256 _startTime,
uint256 _period,
address _wallet,
address _token,
uint256 _minimumInvest) public
{
require(_period != 0);
require(_token != address(0));
startTime = _startTime;
endTime = startTime + _period * 1 days;
wallet = _wallet;
token = RicoToken(_token);
tokenContractAddress = _token;
// minimumInvest in wei
minimumInvest = _minimumInvest;
// 1 token for approximately 0,000666666666667 eth
rate = 1000;
softCap = 150 * 1 ether;
hardCap = 1500 * 1 ether;
bonusPercent = 50;
}
// @return true if the transaction can buy tokens
modifier saleIsOn() {
bool withinPeriod = now >= startTime && now <= endTime;
require(withinPeriod);
_;
}
modifier isUnderHardCap() {
require(weiRaised < hardCap);
_;
}
modifier refundAllowed() {
require(weiRaised < softCap && now > endTime);
_;
}
// @return true if PreSale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// Refund ether to the investors (invoke from only token)
function refund(address _to) public refundAllowed {
require(msg.sender == tokenContractAddress);
uint256 valueToReturn = balances[_to];
// update states
balances[_to] = 0;
weiRaised = weiRaised.sub(valueToReturn);
_to.transfer(valueToReturn);
}
// Get amount of tokens
// @param value weis paid for tokens
function getTokenAmount(uint256 _value) internal view returns (uint256) {
return _value.mul(rate);
}
// Send weis to the wallet
function forwardFunds(uint256 _value) internal {
wallet.transfer(_value);
}
// Success finish of PreSale
function finishPreSale() public onlyOwner {
require(weiRaised >= softCap);
require(weiRaised >= hardCap || now > endTime);
if (now < endTime) {
endTime = now;
}
forwardFunds(this.balance);
token.transferOwnership(owner);
}
// Change owner of token after end of PreSale if Soft Cap has not raised
function changeTokenOwner() public onlyOwner {
require(now > endTime && weiRaised < softCap);
token.transferOwnership(owner);
}
// low level token purchase function
function buyTokens(address _beneficiary) saleIsOn isUnderHardCap nonReentrant public payable {
require(_beneficiary != address(0));
require(msg.value >= minimumInvest);
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
tokens = tokens.add(tokens.mul(bonusPercent).div(100));
token.mint(_beneficiary, tokens);
// update states
weiRaised = weiRaised.add(weiAmount);
balances[_beneficiary] = balances[_beneficiary].add(weiAmount);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
}
function() external payable {
buyTokens(msg.sender);
}
}
contract rICO is Ownable, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
RicoToken public token;
address tokenContractAddress;
// PreSale
PreSale public preSale;
// Timestamps of periods
uint256 public startTime;
uint256 public endCrowdSaleTime;
uint256 public endRefundableTime;
// Address where funds are transferred
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
uint256 public minimumInvest; // in wei
uint256 public softCap; // in wei
uint256 public hardCap; // in wei
// investors => amount of money
mapping(address => uint) public balances;
mapping(address => uint) public balancesInToken;
// Amount of wei raised
uint256 public weiRaised;
// Rest amount of wei after refunding by investors and withdraws by owner
uint256 public restWei;
// Amount of wei which reserved for withdraw by owner
uint256 public reservedWei;
// stages of Refundable part
bool public firstStageRefund = false; // allow 500 eth to withdraw
bool public secondStageRefund = false; // allow 30 percent of rest wei to withdraw
bool public finalStageRefund = false; // allow all rest wei to withdraw
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function rICO(
address _wallet,
address _token,
address _preSale) public
{
require(_token != address(0));
startTime = 1525075200;
endCrowdSaleTime = startTime + 60 * 1 minutes;
endRefundableTime = endCrowdSaleTime + 130 * 1 minutes;
wallet = _wallet;
token = RicoToken(_token);
tokenContractAddress = _token;
preSale = PreSale(_preSale);
// minimumInvest in wei
minimumInvest = 1000000000000;
// 1 token rate
rate = 1000;
softCap = 1500 * 0.000001 ether;
hardCap = 15000 * 0.000001 ether;
}
// @return true if the transaction can buy tokens
modifier saleIsOn() {
bool withinPeriod = now >= startTime && now <= endCrowdSaleTime;
require(withinPeriod);
_;
}
modifier isUnderHardCap() {
require(weiRaised.add(preSale.weiRaised()) < hardCap);
_;
}
// @return true if CrowdSale event has ended
function hasEnded() public view returns (bool) {
return now > endRefundableTime;
}
// Get bonus percent
function getBonusPercent() internal view returns(uint256) {
uint256 collectedWei = weiRaised.add(preSale.weiRaised());
if (collectedWei < 1500 * 0.000001 ether) {
return 20;
}
if (collectedWei < 5000 * 0.000001 ether) {
return 10;
}
if (collectedWei < 10000 * 0.000001 ether) {
return 5;
}
return 0;
}
// Get real value to return to investor
function getRealValueToReturn(uint256 _value) internal view returns(uint256) {
return _value.mul(restWei).div(weiRaised);
}
// Update of reservedWei for withdraw
function updateReservedWei() public {
require(weiRaised.add(preSale.weiRaised()) >= softCap && now > endCrowdSaleTime);
uint256 curWei;
if (!firstStageRefund && now > endCrowdSaleTime) {
curWei = 500 * 0.000001 ether;
reservedWei = curWei;
restWei = weiRaised.sub(curWei);
firstStageRefund = true;
}
if (!secondStageRefund && now > endCrowdSaleTime + 99 * 1 minutes) {
curWei = restWei.mul(30).div(100);
reservedWei = reservedWei.add(curWei);
restWei = restWei.sub(curWei);
secondStageRefund = true;
}
if (!finalStageRefund && now > endRefundableTime) {
reservedWei = reservedWei.add(restWei);
restWei = 0;
finalStageRefund = true;
}
}
// Refund ether to the investors (invoke from only token)
function refund(address _to) public {
require(msg.sender == tokenContractAddress);
require(weiRaised.add(preSale.weiRaised()) < softCap && now > endCrowdSaleTime
|| weiRaised.add(preSale.weiRaised()) >= softCap && now > endCrowdSaleTime && now <= endRefundableTime);
// unsuccessful end of CrowdSale
if (weiRaised.add(preSale.weiRaised()) < softCap && now > endCrowdSaleTime) {
refundAll(_to);
return;
}
// successful end of CrowdSale
if (weiRaised.add(preSale.weiRaised()) >= softCap && now > endCrowdSaleTime && now <= endRefundableTime) {
refundPart(_to);
return;
}
}
// Refund ether to the investors in case of unsuccessful end of CrowdSale
function refundAll(address _to) internal {
uint256 valueToReturn = balances[_to];
// update states
balances[_to] = 0;
balancesInToken[_to] = 0;
weiRaised = weiRaised.sub(valueToReturn);
_to.transfer(valueToReturn);
}
// Refund part of ether to the investors in case of successful end of CrowdSale
function refundPart(address _to) internal {
uint256 valueToReturn = balances[_to];
// get real value to return
updateReservedWei();
valueToReturn = getRealValueToReturn(valueToReturn);
// update states
balances[_to] = 0;
balancesInToken[_to] = 0;
restWei = restWei.sub(valueToReturn);
_to.transfer(valueToReturn);
}
// Get amount of tokens
// @param value weis paid for tokens
function getTokenAmount(uint256 _value) internal view returns (uint256) {
return _value.mul(rate);
}
// Send weis to the wallet
function forwardFunds(uint256 _value) internal {
wallet.transfer(_value);
}
// Withdrawal eth to owner
function withdrawal() public onlyOwner {
updateReservedWei();
uint256 withdrawalWei = reservedWei;
reservedWei = 0;
forwardFunds(withdrawalWei);
}
// Success finish of CrowdSale
function finishCrowdSale() public onlyOwner {
require(now > endRefundableTime);
// withdrawal all eth from contract
updateReservedWei();
reservedWei = 0;
forwardFunds(this.balance);
// mint tokens to owner - wallet
token.mint(wallet, (token.totalSupply().mul(65).div(100)));
token.finishMinting();
token.transferOwnership(owner);
}
// Change owner of token after end of CrowdSale if Soft Cap has not raised
function changeTokenOwner() public onlyOwner {
require(now > endRefundableTime && weiRaised.add(preSale.weiRaised()) < softCap);
token.transferOwnership(owner);
}
// low level token purchase function
function buyTokens(address _beneficiary) saleIsOn isUnderHardCap nonReentrant public payable {
require(_beneficiary != address(0));
require(msg.value >= minimumInvest);
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
uint256 bonusPercent = getBonusPercent();
tokens = tokens.add(tokens.mul(bonusPercent).div(100));
token.mint(_beneficiary, tokens);
// update states
weiRaised = weiRaised.add(weiAmount);
balances[_beneficiary] = balances[_beneficiary].add(weiAmount);
balancesInToken[_beneficiary] = balancesInToken[_beneficiary].add(tokens);
// update timestamps and begin Refundable stage
if (weiRaised >= hardCap) {
endCrowdSaleTime = now;
endRefundableTime = endCrowdSaleTime + 130 * 1 minutes;
}
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
}
function() external payable {
buyTokens(msg.sender);
}
}
|
Refund part of ether to the investors in case of successful end of CrowdSale get real value to return update states
|
function refundPart(address _to) internal {
uint256 valueToReturn = balances[_to];
updateReservedWei();
valueToReturn = getRealValueToReturn(valueToReturn);
balances[_to] = 0;
balancesInToken[_to] = 0;
restWei = restWei.sub(valueToReturn);
_to.transfer(valueToReturn);
}
| 241,476
|
// SPDX-License-Identifier: MIT
// P1 - P3: OK
pragma solidity 0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
library SafeGothMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "SafeMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "SafeMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "SafeMath: Mul Overflow");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "SafeMath: Div by Zero");
c = a / b;
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "SafeMath: uint128 Overflow");
c = uint128(a);
}
}
library SafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "SafeMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "SafeMath: Underflow");
}
}
library SafeERC20 {
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03));
return success && data.length > 0 ? abi.decode(data, (string)) : "???";
}
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed");
}
function safeTransferFrom(
IERC20 token,
address from,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(0x23b872dd, from, address(this), amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed");
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
interface IGothPair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IGothFactory {
//event PairCreated(address indexed token0, address indexed token1, address pair, uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
library GothLibrary {
using SafeGothMath for uint256;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "GothLibrary: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "GothLibrary: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"21f4cd6f7674ba53a1c9795041b68067494058bba06f534b348c3d806d2386d8" // init code fuji
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(
address factory,
address tokenA,
address tokenB
) internal view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IGothPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) internal pure returns (uint256 amountB) {
require(amountA > 0, "GothLibrary: INSUFFICIENT_AMOUNT");
require(reserveA > 0 && reserveB > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
require(amountIn > 0, "GothLibrary: INSUFFICIENT_INPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
require(amountOut > 0, "GothLibrary: INSUFFICIENT_OUTPUT_AMOUNT");
require(reserveIn > 0 && reserveOut > 0, "GothLibrary: INSUFFICIENT_LIQUIDITY");
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(
address factory,
uint256 amountIn,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "GothLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[0] = amountIn;
for (uint256 i; i < path.length - 1; i++) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(
address factory,
uint256 amountOut,
address[] memory path
) internal view returns (uint256[] memory amounts) {
require(path.length >= 2, "GothLibrary: INVALID_PATH");
amounts = new uint256[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint256 i = path.length - 1; i > 0; i--) {
(uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
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() public {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// This is forked from Trader Joe's joe-core repository found here
// https://github.com/traderjoe-xyz/joe-core/blob/main/contracts/MoneyMaker.sol
/// @title Money Maker
/// @author Trader Joe
/// @notice MoneyMaker receives 0.05% of the swaps done on Trader Joe(SIGIL) in the form of an LP. It swaps those LPs
/// to a token of choice and sends it to the JoeBar(SigilStake)
contract MoneyMaker is Ownable {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using SafeMath for uint256;
IGothFactory public immutable factory;
address public immutable bar;
address private immutable wavax;
/// @notice Any ERC20
address public tokenTo;
/// @notice In basis points aka parts per 10,000 so 5000 is 50%, cap of 50%, default is 0
uint256 public devCut = 0;
address public devAddr;
// @notice Set of addresses that can perform certain functions
EnumerableSet.AddressSet private _isAuth;
modifier onlyAuth() {
require(_isAuth.contains(_msgSender()), "MoneyMaker: FORBIDDEN");
_;
}
/// @dev Maps a token `token` to another token `bridge` so that it uses `token/bridge` pair to convert token
mapping(address => address) internal _bridges;
event AddAuthorizedAddress(address indexed _addr);
event RemoveAuthorizedAddress(address indexed _addr);
event SetDevAddr(address _addr);
event SetDevCut(uint256 _amount);
event SetTokenTo(address _tokenTo);
event LogBridgeSet(address indexed token, address indexed oldBridge, address indexed bridge);
event LogConvert(
address indexed server,
address indexed token0,
address indexed token1,
uint256 amount0,
uint256 amount1,
uint256 amountTOKEN
);
/// @notice Constructor
/// @param _factory The address of GothFactory
/// @param _bar The address of SigilStake
/// @param _tokenTo The address of the token we want to convert to
/// @param _wavax The address of wavax
constructor(
address _factory,
address _bar,
address _tokenTo,
address _wavax
) public {
require(_factory != address(0), "MoneyMaker: factory can't be address(0)");
require(_bar != address(0), "MoneyMaker: bar can't be address(0)");
require(_tokenTo != address(0), "MoneyMaker: token can't be address(0)");
require(_wavax != address(0), "MoneyMaker: wavax can't be address(0)");
factory = IGothFactory(_factory);
bar = _bar;
tokenTo = _tokenTo;
wavax = _wavax;
devAddr = _msgSender();
_isAuth.add(_msgSender());
}
/// @notice Adds a user to the authorized addresses
/// @param _auth The address to add
function addAuth(address _auth) external onlyOwner {
require(_isAuth.add(_auth), "MoneyMaker: Address is already authorized");
emit AddAuthorizedAddress(_auth);
}
/// @notice Remove a user of authorized addresses
/// @param _auth The address to remove
function removeAuth(address _auth) external onlyOwner {
require(_isAuth.remove(_auth), "MoneyMaker: Address is not authorized");
emit RemoveAuthorizedAddress(_auth);
}
/// @notice Return the list of authorized addresses
/// @param index Index of the returned address
/// @return The authorized address at `index`
function getAuth(uint256 index) external view returns (address) {
return _isAuth.at(index);
}
/// @notice Return the length of authorized addresses
/// @return The number of authorized addresses
function lenAuth() external view returns (uint256) {
return _isAuth.length();
}
/// @notice Force using `pair/bridge` pair to convert `token`
/// @param token The address of the tokenFrom
/// @param bridge The address of the tokenTo
function setBridge(address token, address bridge) external onlyAuth {
// Checks
require(token != tokenTo && token != wavax && token != bridge, "MoneyMaker: Invalid bridge");
// Effects
address oldBridge = _bridges[token];
_bridges[token] = bridge;
emit LogBridgeSet(token, oldBridge, bridge);
}
/// @notice Sets dev cut, which will be sent to `devAddr`, can't be greater than 50%
/// @param _amount The new devCut value
function setDevCut(uint256 _amount) external onlyOwner {
require(_amount <= 5000, "setDevCut: cut too high");
devCut = _amount;
emit SetDevCut(_amount);
}
/// @notice Sets `devAddr`, the address that will receive the `devCut`
/// @param _addr The new dev address
function setDevAddr(address _addr) external onlyOwner {
require(_addr != address(0), "setDevAddr, address cannot be zero address");
devAddr = _addr;
emit SetDevAddr(_addr);
}
/// @notice Sets token that we're buying back
/// @param _tokenTo The new token address
function setTokenToAddress(address _tokenTo) external onlyOwner {
require(_tokenTo != address(0), "setTokenToAddress, address cannot be zero address");
tokenTo = _tokenTo;
emit SetTokenTo(_tokenTo);
}
/// @notice Returns the `bridge` of a `token`
/// @param token The tokenFrom address
/// @return bridge The tokenTo address
function bridgeFor(address token) public view returns (address bridge) {
bridge = _bridges[token];
if (bridge == address(0)) {
bridge = wavax;
}
}
// C6: It's not a fool proof solution, but it prevents flash loans, so here it's ok to use tx.origin
modifier onlyEOA() {
// Try to make flash-loan exploit harder to do by only allowing externally owned addresses.
require(_msgSender() == tx.origin, "MoneyMaker: must use EOA");
_;
}
/// @notice Converts a pair of tokens to tokenTo
/// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple
/// @param token0 The address of the first token of the pair that will be converted
/// @param token1 The address of the second token of the pair that will be converted
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
function convert(
address token0,
address token1,
uint256 slippage
) external onlyEOA onlyAuth {
require(slippage < 5_000, "MoneyMaker: slippage needs to be lower than 50%");
_convert(token0, token1, slippage);
}
/// @notice Converts a list of pairs of tokens to tokenTo
/// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple
/// @param token0 The list of addresses of the first token of the pairs that will be converted
/// @param token1 The list of addresses of the second token of the pairs that will be converted
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
function convertMultiple(
address[] calldata token0,
address[] calldata token1,
uint256 slippage
) external onlyEOA onlyAuth {
// TODO: This can be optimized a fair bit, but this is safer and simpler for now
require(slippage < 5_000, "MoneyMaker: slippage needs to be lower than 50%");
require(token0.length == token1.length, "MoneyMaker: arrays length don't match");
uint256 len = token0.length;
for (uint256 i = 0; i < len; i++) {
_convert(token0[i], token1[i], slippage);
}
}
/// @notice Converts a pair of tokens to tokenTo
/// @dev _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple
/// @param token0 The address of the first token of the pair that is currently being converted
/// @param token1 The address of the second token of the pair that is currently being converted
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
function _convert(
address token0,
address token1,
uint256 slippage
) internal {
uint256 amount0;
uint256 amount1;
// handle case where non-LP tokens need to be converted
if (token0 == token1) {
amount0 = IERC20(token0).balanceOf(address(this));
amount1 = 0;
} else {
IGothPair pair = IGothPair(factory.getPair(token0, token1));
require(address(pair) != address(0), "MoneyMaker: Invalid pair");
IERC20(address(pair)).safeTransfer(address(pair), pair.balanceOf(address(this)));
// take balance of tokens in this contract before burning the pair, incase there are already some here
uint256 tok0bal = IERC20(token0).balanceOf(address(this));
uint256 tok1bal = IERC20(token1).balanceOf(address(this));
pair.burn(address(this));
// subtract old balance of tokens from new balance
// the return values of pair.burn cant be trusted due to transfer tax tokens
amount0 = IERC20(token0).balanceOf(address(this)).sub(tok0bal);
amount1 = IERC20(token1).balanceOf(address(this)).sub(tok1bal);
}
emit LogConvert(
_msgSender(),
token0,
token1,
amount0,
amount1,
_convertStep(token0, token1, amount0, amount1, slippage)
);
}
/// @notice Used to convert two tokens to `tokenTo`, step by step, called recursively
/// @param token0 The address of the first token
/// @param token1 The address of the second token
/// @param amount0 The amount of the `token0`
/// @param amount1 The amount of the `token1`
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
/// @return tokenOut The amount of token
function _convertStep(
address token0,
address token1,
uint256 amount0,
uint256 amount1,
uint256 slippage
) internal returns (uint256 tokenOut) {
// Interactions
if (token0 == token1) {
uint256 amount = amount0.add(amount1);
if (token0 == tokenTo) {
IERC20(tokenTo).safeTransfer(bar, amount);
tokenOut = amount;
} else if (token0 == wavax) {
tokenOut = _toToken(wavax, amount, slippage);
} else {
address bridge = bridgeFor(token0);
amount = _swap(token0, bridge, amount, address(this), slippage);
tokenOut = _convertStep(bridge, bridge, amount, 0, slippage);
}
} else if (token0 == tokenTo) {
// eg. TOKEN - AVAX
IERC20(tokenTo).safeTransfer(bar, amount0);
tokenOut = _toToken(token1, amount1, slippage).add(amount0);
} else if (token1 == tokenTo) {
// eg. USDT - TOKEN
IERC20(tokenTo).safeTransfer(bar, amount1);
tokenOut = _toToken(token0, amount0, slippage).add(amount1);
} else if (token0 == wavax) {
// eg. AVAX - USDC
tokenOut = _toToken(wavax, _swap(token1, wavax, amount1, address(this), slippage).add(amount0), slippage);
} else if (token1 == wavax) {
// eg. USDT - AVAX
tokenOut = _toToken(wavax, _swap(token0, wavax, amount0, address(this), slippage).add(amount1), slippage);
} else {
// eg. MIC - USDT
address bridge0 = bridgeFor(token0);
address bridge1 = bridgeFor(token1);
if (bridge0 == token1) {
// eg. MIC - USDT - and bridgeFor(MIC) = USDT
tokenOut = _convertStep(
bridge0,
token1,
_swap(token0, bridge0, amount0, address(this), slippage),
amount1,
slippage
);
} else if (bridge1 == token0) {
// eg. WBTC - DSD - and bridgeFor(DSD) = WBTC
tokenOut = _convertStep(
token0,
bridge1,
amount0,
_swap(token1, bridge1, amount1, address(this), slippage),
slippage
);
} else {
tokenOut = _convertStep(
bridge0,
bridge1, // eg. USDT - DSD - and bridgeFor(DSD) = WBTC
_swap(token0, bridge0, amount0, address(this), slippage),
_swap(token1, bridge1, amount1, address(this), slippage),
slippage
);
}
}
}
/// @notice Swaps `amountIn` `fromToken` to `toToken` and sends it to `to`, `amountOut` is required to be greater
/// than allowed `slippage`
/// @param fromToken The address of token that will be swapped
/// @param toToken The address of the token that will be received
/// @param amountIn The amount of the `fromToken`
/// @param to The address that will receive the `toToken`
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
/// @return amountOut The amount of `toToken` sent to `to`
function _swap(
address fromToken,
address toToken,
uint256 amountIn,
address to,
uint256 slippage
) internal returns (uint256 amountOut) {
// Checks
// X1 - X5: OK
IGothPair pair = IGothPair(factory.getPair(fromToken, toToken));
require(address(pair) != address(0), "MoneyMaker: Cannot convert");
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = fromToken == pair.token0()
? (reserve0, reserve1)
: (reserve1, reserve0);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
uint256 amountInput = IERC20(fromToken).balanceOf(address(pair)).sub(reserveInput); // calculate amount that was transferred, this accounts for transfer taxes
amountOut = GothLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
{
uint256 rest = uint256(10_000).sub(slippage);
/// @dev We simulate the amount received if we did a swapIn and swapOut without updating the reserves,
/// hence why we do rest^2, i.e. calculating the slippage twice cause we actually do two swaps.
/// This allows us to catch if a pair has low liquidity
require(
GothLibrary.getAmountOut(amountOut, reserveOutput, reserveInput) >=
amountInput.mul(rest).mul(rest).div(100_000_000),
"MoneyMaker: Slippage caught"
);
}
(uint256 amount0Out, uint256 amount1Out) = fromToken == pair.token0()
? (uint256(0), amountOut)
: (amountOut, uint256(0));
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
/// @notice Swaps an amount of token to another token, `tokenTo`
/// @dev `amountOut` is required to be greater after slippage
/// @param token The address of token that will be swapped
/// @param amountIn The amount of the `token`
/// @param slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50%
/// @return amountOut The amount of `toToken` sent to JoeBar
function _toToken(
address token,
uint256 amountIn,
uint256 slippage
) internal returns (uint256 amountOut) {
uint256 amount = amountIn;
if (devCut > 0) {
amount = amount.mul(devCut).div(10000);
IERC20(token).safeTransfer(devAddr, amount);
amount = amountIn.sub(amount);
}
amountOut = _swap(token, tokenTo, amount, bar, slippage);
}
}
|
Converts a pair of tokens to tokenTo _convert is separate to save gas by only checking the 'onlyEOA' modifier once in case of convertMultiple token0 The address of the first token of the pair that is currently being converted token1 The address of the second token of the pair that is currently being converted slippage The accepted slippage, in basis points aka parts per 10,000 so 5000 is 50% handle case where non-LP tokens need to be converted take balance of tokens in this contract before burning the pair, incase there are already some here subtract old balance of tokens from new balance the return values of pair.burn cant be trusted due to transfer tax tokens
|
function _convert(
address token0,
address token1,
uint256 slippage
) internal {
uint256 amount0;
uint256 amount1;
if (token0 == token1) {
amount0 = IERC20(token0).balanceOf(address(this));
amount1 = 0;
IGothPair pair = IGothPair(factory.getPair(token0, token1));
require(address(pair) != address(0), "MoneyMaker: Invalid pair");
IERC20(address(pair)).safeTransfer(address(pair), pair.balanceOf(address(this)));
uint256 tok0bal = IERC20(token0).balanceOf(address(this));
uint256 tok1bal = IERC20(token1).balanceOf(address(this));
pair.burn(address(this));
amount0 = IERC20(token0).balanceOf(address(this)).sub(tok0bal);
amount1 = IERC20(token1).balanceOf(address(this)).sub(tok1bal);
}
emit LogConvert(
_msgSender(),
token0,
token1,
amount0,
amount1,
_convertStep(token0, token1, amount0, amount1, slippage)
);
}
| 13,068,350
|
pragma solidity 0.4.18;
library SafeMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Owned {
address public owner;
function Owned()
public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner)
onlyOwner
public {
owner = newOwner;
}
}
contract BalanceHolder {
mapping(address => uint256) public balanceOf;
event LogWithdraw(
address indexed user,
uint256 amount
);
function withdraw()
public {
uint256 bal = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
msg.sender.transfer(bal);
LogWithdraw(msg.sender, bal);
}
}
contract RealityCheck is BalanceHolder {
using SafeMath for uint256;
using SafeMath32 for uint32;
address constant NULL_ADDRESS = address(0);
// History hash when no history is created, or history has been cleared
bytes32 constant NULL_HASH = bytes32(0);
// An unitinalized finalize_ts for a question will indicate an unanswered question.
uint32 constant UNANSWERED = 0;
// An unanswered reveal_ts for a commitment will indicate that it does not exist.
uint256 constant COMMITMENT_NON_EXISTENT = 0;
// Commit->reveal timeout is 1/8 of the question timeout (rounded down).
uint32 constant COMMITMENT_TIMEOUT_RATIO = 8;
event LogSetQuestionFee(
address arbitrator,
uint256 amount
);
event LogNewTemplate(
uint256 indexed template_id,
address indexed user,
string question_text
);
event LogNewQuestion(
bytes32 indexed question_id,
address indexed user,
uint256 template_id,
string question,
bytes32 indexed content_hash,
address arbitrator,
uint32 timeout,
uint32 opening_ts,
uint256 nonce,
uint256 created
);
event LogFundAnswerBounty(
bytes32 indexed question_id,
uint256 bounty_added,
uint256 bounty,
address indexed user
);
event LogNewAnswer(
bytes32 answer,
bytes32 indexed question_id,
bytes32 history_hash,
address indexed user,
uint256 bond,
uint256 ts,
bool is_commitment
);
event LogAnswerReveal(
bytes32 indexed question_id,
address indexed user,
bytes32 indexed answer_hash,
bytes32 answer,
uint256 nonce,
uint256 bond
);
event LogNotifyOfArbitrationRequest(
bytes32 indexed question_id,
address indexed user
);
event LogFinalize(
bytes32 indexed question_id,
bytes32 indexed answer
);
event LogClaim(
bytes32 indexed question_id,
address indexed user,
uint256 amount
);
struct Question {
bytes32 content_hash;
address arbitrator;
uint32 opening_ts;
uint32 timeout;
uint32 finalize_ts;
bool is_pending_arbitration;
uint256 bounty;
bytes32 best_answer;
bytes32 history_hash;
uint256 bond;
}
// Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond.
struct Commitment {
uint32 reveal_ts;
bool is_revealed;
bytes32 revealed_answer;
}
// Only used when claiming more bonds than fits into a transaction
// Stored in a mapping indexed by question_id.
struct Claim {
address payee;
uint256 last_bond;
uint256 queued_funds;
}
uint256 nextTemplateID = 0;
mapping(uint256 => uint256) public templates;
mapping(uint256 => bytes32) public template_hashes;
mapping(bytes32 => Question) public questions;
mapping(bytes32 => Claim) question_claims;
mapping(bytes32 => Commitment) public commitments;
mapping(address => uint256) public arbitrator_question_fees;
modifier onlyArbitrator(bytes32 question_id) {
require(msg.sender == questions[question_id].arbitrator);
_;
}
modifier stateAny() {
_;
}
modifier stateNotCreated(bytes32 question_id) {
require(questions[question_id].timeout == 0);
_;
}
modifier stateOpen(bytes32 question_id) {
require(questions[question_id].timeout > 0); // Check existence
require(!questions[question_id].is_pending_arbitration);
uint32 finalize_ts = questions[question_id].finalize_ts;
require(finalize_ts == UNANSWERED || finalize_ts > uint32(now));
uint32 opening_ts = questions[question_id].opening_ts;
require(opening_ts == 0 || opening_ts <= uint32(now));
_;
}
modifier statePendingArbitration(bytes32 question_id) {
require(questions[question_id].is_pending_arbitration);
_;
}
modifier stateOpenOrPendingArbitration(bytes32 question_id) {
require(questions[question_id].timeout > 0); // Check existence
uint32 finalize_ts = questions[question_id].finalize_ts;
require(finalize_ts == UNANSWERED || finalize_ts > uint32(now));
uint32 opening_ts = questions[question_id].opening_ts;
require(opening_ts == 0 || opening_ts <= uint32(now));
_;
}
modifier stateFinalized(bytes32 question_id) {
require(isFinalized(question_id));
_;
}
modifier bondMustBeZero() {
require(msg.value == 0);
_;
}
modifier bondMustDouble(bytes32 question_id) {
require(msg.value > 0);
require(msg.value >= (questions[question_id].bond.mul(2)));
_;
}
modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) {
if (max_previous > 0) {
require(questions[question_id].bond <= max_previous);
}
_;
}
/// @notice Constructor, sets up some initial templates
/// @dev Creates some generalized templates for different question types used in the DApp.
function RealityCheck()
public {
createTemplate('{"title": "%s", "type": "bool", "category": "%s"}');
createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "category": "%s"}');
createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "category": "%s"}');
createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "category": "%s"}');
createTemplate('{"title": "%s", "type": "datetime", "category": "%s"}');
}
/// @notice Function for arbitrator to set an optional per-question fee.
/// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure.
/// @param fee The fee to be charged by the arbitrator when a question is asked
function setQuestionFee(uint256 fee)
stateAny()
external {
arbitrator_question_fees[msg.sender] = fee;
LogSetQuestionFee(msg.sender, fee);
}
/// @notice Create a reusable template, which should be a JSON document.
/// Placeholders should use gettext() syntax, eg %s.
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplate(string content)
stateAny()
public returns (uint256) {
uint256 id = nextTemplateID;
templates[id] = block.number;
template_hashes[id] = keccak256(content);
LogNewTemplate(id, msg.sender, content);
nextTemplateID = id.add(1);
return id;
}
/// @notice Create a new reusable template and use it to ask a question
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param content The template content
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created template, which is created sequentially.
function createTemplateAndAskQuestion(
string content,
string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce
)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
uint256 template_id = createTemplate(content);
return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce);
}
/// @notice Ask a new question and return the ID
/// @dev Template data is only stored in the event logs, but its block number is kept in contract storage.
/// @param template_id The ID number of the template the question will use
/// @param question A string containing the parameters that will be passed into the template to make the question
/// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute
/// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer
/// @param opening_ts If set, the earliest time it should be possible to answer the question.
/// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question.
/// @return The ID of the newly-created question, created deterministically.
function askQuestion(uint256 template_id, string question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce)
// stateNotCreated is enforced by the internal _askQuestion
public payable returns (bytes32) {
require(templates[template_id] > 0); // Template must exist
bytes32 content_hash = keccak256(template_id, opening_ts, question);
bytes32 question_id = keccak256(content_hash, arbitrator, timeout, msg.sender, nonce);
_askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts);
LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now);
return question_id;
}
function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts)
stateNotCreated(question_id)
internal {
// A timeout of 0 makes no sense, and we will use this to check existence
require(timeout > 0);
require(timeout < 365 days);
require(arbitrator != NULL_ADDRESS);
uint256 bounty = msg.value;
// The arbitrator can set a fee for asking a question.
// This is intended as an anti-spam defence.
// The fee is waived if the arbitrator is asking the question.
// This allows them to set an impossibly high fee and make users proxy the question through them.
// This would allow more sophisticated pricing, question whitelisting etc.
if (msg.sender != arbitrator) {
uint256 question_fee = arbitrator_question_fees[arbitrator];
require(bounty >= question_fee);
bounty = bounty.sub(question_fee);
balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee);
}
questions[question_id].content_hash = content_hash;
questions[question_id].arbitrator = arbitrator;
questions[question_id].opening_ts = opening_ts;
questions[question_id].timeout = timeout;
questions[question_id].bounty = bounty;
}
/// @notice Add funds to the bounty for a question
/// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized.
/// @param question_id The ID of the question you wish to fund
function fundAnswerBounty(bytes32 question_id)
stateOpen(question_id)
external payable {
questions[question_id].bounty = questions[question_id].bounty.add(msg.value);
LogFundAnswerBounty(question_id, msg.value, questions[question_id].bounty, msg.sender);
}
/// @notice Submit an answer for a question.
/// @dev Adds the answer to the history and updates the current "best" answer.
/// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function submitAnswer(bytes32 question_id, bytes32 answer, uint256 max_previous)
stateOpen(question_id)
bondMustDouble(question_id)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external payable {
_addAnswerToHistory(question_id, answer, msg.sender, msg.value, false);
_updateCurrentAnswer(question_id, answer, questions[question_id].timeout);
}
/// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction.
/// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond.
/// The commitment_id is stored in the answer history where the answer would normally go.
/// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction.
/// @param question_id The ID of the question
/// @param answer_hash The hash of your answer, plus a nonce that you will later reveal
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
/// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender.
/// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party.
function submitAnswerCommitment(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer)
stateOpen(question_id)
bondMustDouble(question_id)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external payable {
bytes32 commitment_id = keccak256(question_id, answer_hash, msg.value);
address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer;
require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT);
uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO;
commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout);
_addAnswerToHistory(question_id, commitment_id, answerer, msg.value, true);
}
/// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction
/// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer
/// Updates the current answer unless someone has since supplied a new answer with a higher bond
/// msg.sender is intentionally not restricted to the user who originally sent the commitment;
/// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx
/// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent
/// @param question_id The ID of the question
/// @param answer The answer, encoded as bytes32
/// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment()
/// @param bond The bond that you paid in your submitAnswerCommitment() transaction
function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond)
stateOpenOrPendingArbitration(question_id)
external {
bytes32 answer_hash = keccak256(answer, nonce);
bytes32 commitment_id = keccak256(question_id, answer_hash, bond);
require(!commitments[commitment_id].is_revealed);
require(commitments[commitment_id].reveal_ts > uint32(now)); // Reveal deadline must not have passed
commitments[commitment_id].revealed_answer = answer;
commitments[commitment_id].is_revealed = true;
if (bond == questions[question_id].bond) {
_updateCurrentAnswer(question_id, answer, questions[question_id].timeout);
}
LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond);
}
function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment)
internal
{
bytes32 new_history_hash = keccak256(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment);
questions[question_id].bond = bond;
questions[question_id].history_hash = new_history_hash;
LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, now, is_commitment);
}
function _updateCurrentAnswer(bytes32 question_id, bytes32 answer, uint32 timeout_secs)
internal {
questions[question_id].best_answer = answer;
questions[question_id].finalize_ts = uint32(now).add(timeout_secs);
}
/// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision.
/// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them.
/// @param question_id The ID of the question
/// @param requester The account that requested arbitration
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous)
onlyArbitrator(question_id)
stateOpen(question_id)
previousBondMustNotBeatMaxPrevious(question_id, max_previous)
external {
questions[question_id].is_pending_arbitration = true;
LogNotifyOfArbitrationRequest(question_id, requester);
}
/// @notice Submit the answer for a question, for use by the arbitrator.
/// @dev Doesn't require (or allow) a bond.
/// If the current final answer is correct, the account should be whoever submitted it.
/// If the current final answer is wrong, the account should be whoever paid for arbitration.
/// However, the answerer stipulations are not enforced by the contract.
/// @param question_id The ID of the question
/// @param answer The answer, encoded into bytes32
/// @param answerer The account credited with this answer for the purpose of bond claims
function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyArbitrator(question_id)
statePendingArbitration(question_id)
bondMustBeZero
external {
require(answerer != NULL_ADDRESS);
LogFinalize(question_id, answer);
questions[question_id].is_pending_arbitration = false;
_addAnswerToHistory(question_id, answer, answerer, 0, false);
_updateCurrentAnswer(question_id, answer, 0);
}
/// @notice Report whether the answer to the specified question is finalized
/// @param question_id The ID of the question
/// @return Return true if finalized
function isFinalized(bytes32 question_id)
constant public returns (bool) {
uint32 finalize_ts = questions[question_id].finalize_ts;
return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(now)) );
}
/// @notice Return the final answer to the specified question, or revert if there isn't one
/// @param question_id The ID of the question
/// @return The answer formatted as a bytes32
function getFinalAnswer(bytes32 question_id)
stateFinalized(question_id)
external constant returns (bytes32) {
return questions[question_id].best_answer;
}
/// @notice Return the final answer to the specified question, provided it matches the specified criteria.
/// @dev Reverts if the question is not finalized, or if it does not match the specified criteria.
/// @param question_id The ID of the question
/// @param content_hash The hash of the question content (template ID + opening time + question parameter string)
/// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate)
/// @param min_timeout The timeout set in the initial question settings must be this high or higher
/// @param min_bond The bond sent with the final answer must be this high or higher
/// @return The answer formatted as a bytes32
function getFinalAnswerIfMatches(
bytes32 question_id,
bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond
)
stateFinalized(question_id)
external constant returns (bytes32) {
require(content_hash == questions[question_id].content_hash);
require(arbitrator == questions[question_id].arbitrator);
require(min_timeout <= questions[question_id].timeout);
require(min_bond <= questions[question_id].bond);
return questions[question_id].best_answer;
}
/// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer
/// Caller must provide the answer history, in reverse order
/// @dev Works up the chain and assign bonds to the person who gave the right answer
/// If someone gave the winning answer earlier, they must get paid from the higher bond
/// That means we can't pay out the bond added at n until we have looked at n-1
/// The first answer is authenticated by checking against the stored history_hash.
/// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc
/// Once we get to a null hash we'll know we're done and there are no more answers.
/// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later.
/// @param question_id The ID of the question
/// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty).
/// @param addrs Last-to-first, the address of each answerer or commitment sender
/// @param bonds Last-to-first, the bond supplied with each answer or commitment
/// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal
function claimWinnings(
bytes32 question_id,
bytes32[] history_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
stateFinalized(question_id)
public {
require(history_hashes.length > 0);
// These are only set if we split our claim over multiple transactions.
address payee = question_claims[question_id].payee;
uint256 last_bond = question_claims[question_id].last_bond;
uint256 queued_funds = question_claims[question_id].queued_funds;
// Starts as the hash of the final answer submitted. It'll be cleared when we're done.
// If we're splitting the claim over multiple transactions, it'll be the hash where we left off last time
bytes32 last_history_hash = questions[question_id].history_hash;
bytes32 best_answer = questions[question_id].best_answer;
uint256 i;
for (i = 0; i < history_hashes.length; i++) {
// Check input against the history hash, and see which of 2 possible values of is_commitment fits.
bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]);
queued_funds = queued_funds.add(last_bond);
(queued_funds, payee) = _processHistoryItem(
question_id, best_answer, queued_funds, payee,
addrs[i], bonds[i], answers[i], is_commitment);
// Line the bond up for next time, when it will be added to somebody's queued_funds
last_bond = bonds[i];
last_history_hash = history_hashes[i];
}
if (last_history_hash != NULL_HASH) {
// We haven't yet got to the null hash (1st answer), ie the caller didn't supply the full answer chain.
// Persist the details so we can pick up later where we left off later.
// If we know who to pay we can go ahead and pay them out, only keeping back last_bond
// (We always know who to pay unless all we saw were unrevealed commits)
if (payee != NULL_ADDRESS) {
_payPayee(question_id, payee, queued_funds);
queued_funds = 0;
}
question_claims[question_id].payee = payee;
question_claims[question_id].last_bond = last_bond;
question_claims[question_id].queued_funds = queued_funds;
} else {
// There is nothing left below us so the payee can keep what remains
_payPayee(question_id, payee, queued_funds.add(last_bond));
delete question_claims[question_id];
}
questions[question_id].history_hash = last_history_hash;
}
function _payPayee(bytes32 question_id, address payee, uint256 value)
internal {
balanceOf[payee] = balanceOf[payee].add(value);
LogClaim(question_id, payee, value);
}
function _verifyHistoryInputOrRevert(
bytes32 last_history_hash,
bytes32 history_hash, bytes32 answer, uint256 bond, address addr
)
internal pure returns (bool) {
if (last_history_hash == keccak256(history_hash, answer, bond, addr, true) ) {
return true;
}
if (last_history_hash == keccak256(history_hash, answer, bond, addr, false) ) {
return false;
}
revert();
}
function _processHistoryItem(
bytes32 question_id, bytes32 best_answer,
uint256 queued_funds, address payee,
address addr, uint256 bond, bytes32 answer, bool is_commitment
)
internal returns (uint256, address) {
// For commit-and-reveal, the answer history holds the commitment ID instead of the answer.
// We look at the referenced commitment ID and switch in the actual answer.
if (is_commitment) {
bytes32 commitment_id = answer;
// If it's a commit but it hasn't been revealed, it will always be considered wrong.
if (!commitments[commitment_id].is_revealed) {
delete commitments[commitment_id];
return (queued_funds, payee);
} else {
answer = commitments[commitment_id].revealed_answer;
delete commitments[commitment_id];
}
}
if (answer == best_answer) {
if (payee == NULL_ADDRESS) {
// The entry is for the first payee we come to, ie the winner.
// They get the question bounty.
payee = addr;
queued_funds = queued_funds.add(questions[question_id].bounty);
questions[question_id].bounty = 0;
} else if (addr != payee) {
// Answerer has changed, ie we found someone lower down who needs to be paid
// The lower answerer will take over receiving bonds from higher answerer.
// They should also be paid the takeover fee, which is set at a rate equivalent to their bond.
// (This is our arbitrary rule, to give consistent right-answerers a defence against high-rollers.)
// There should be enough for the fee, but if not, take what we have.
// There's an edge case involving weird arbitrator behaviour where we may be short.
uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds;
// Settle up with the old (higher-bonded) payee
_payPayee(question_id, payee, queued_funds.sub(answer_takeover_fee));
// Now start queued_funds again for the new (lower-bonded) payee
payee = addr;
queued_funds = answer_takeover_fee;
}
}
return (queued_funds, payee);
}
/// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds.
/// Caller must provide the answer history for each question, in reverse order
/// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call.
/// @param question_ids The IDs of the questions you want to claim for
/// @param lengths The number of history entries you will supply for each question ID
/// @param hist_hashes In a single list for all supplied questions, the hash of each history entry.
/// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender
/// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment
/// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID
function claimMultipleAndWithdrawBalance(
bytes32[] question_ids, uint256[] lengths,
bytes32[] hist_hashes, address[] addrs, uint256[] bonds, bytes32[] answers
)
stateAny() // The finalization checks are done in the claimWinnings function
public {
uint256 qi;
uint256 i;
for (qi = 0; qi < question_ids.length; qi++) {
bytes32 qid = question_ids[qi];
uint256 ln = lengths[qi];
bytes32[] memory hh = new bytes32[](ln);
address[] memory ad = new address[](ln);
uint256[] memory bo = new uint256[](ln);
bytes32[] memory an = new bytes32[](ln);
uint256 j;
for (j = 0; j < ln; j++) {
hh[j] = hist_hashes[i];
ad[j] = addrs[i];
bo[j] = bonds[i];
an[j] = answers[i];
i++;
}
claimWinnings(qid, hh, ad, bo, an);
}
withdraw();
}
}
contract Arbitrator is Owned {
RealityCheck public realitycheck;
mapping(bytes32 => uint256) public arbitration_bounties;
uint256 dispute_fee;
mapping(bytes32 => uint256) custom_dispute_fees;
event LogRequestArbitration(
bytes32 indexed question_id,
uint256 fee_paid,
address requester,
uint256 remaining
);
event LogSetRealityCheck(
address realitycheck
);
event LogSetQuestionFee(
uint256 fee
);
event LogSetDisputeFee(
uint256 fee
);
event LogSetCustomDisputeFee(
bytes32 indexed question_id,
uint256 fee
);
/// @notice Constructor. Sets the deploying address as owner.
function Arbitrator()
public {
owner = msg.sender;
}
/// @notice Set the Reality Check contract address
/// @param addr The address of the Reality Check contract
function setRealityCheck(address addr)
onlyOwner
public {
realitycheck = RealityCheck(addr);
LogSetRealityCheck(addr);
}
/// @notice Set the default fee
/// @param fee The default fee amount
function setDisputeFee(uint256 fee)
onlyOwner
public {
dispute_fee = fee;
LogSetDisputeFee(fee);
}
/// @notice Set a custom fee for this particular question
/// @param question_id The question in question
/// @param fee The fee amount
function setCustomDisputeFee(bytes32 question_id, uint256 fee)
onlyOwner
public {
custom_dispute_fees[question_id] = fee;
LogSetCustomDisputeFee(question_id, fee);
}
/// @notice Return the dispute fee for the specified question. 0 indicates that we won't arbitrate it.
/// @param question_id The question in question
/// @dev Uses a general default, but can be over-ridden on a question-by-question basis.
function getDisputeFee(bytes32 question_id)
public constant returns (uint256) {
return (custom_dispute_fees[question_id] > 0) ? custom_dispute_fees[question_id] : dispute_fee;
}
/// @notice Set a fee for asking a question with us as the arbitrator
/// @param fee The fee amount
/// @dev Default is no fee. Unlike the dispute fee, 0 is an acceptable setting.
/// You could set an impossibly high fee if you want to prevent us being used as arbitrator unless we submit the question.
/// (Submitting the question ourselves is not implemented here.)
/// This fee can be used as a revenue source, an anti-spam measure, or both.
function setQuestionFee(uint256 fee)
onlyOwner
public {
realitycheck.setQuestionFee(fee);
LogSetQuestionFee(fee);
}
/// @notice Submit the arbitrator's answer to a question.
/// @param question_id The question in question
/// @param answer The answer
/// @param answerer The answerer. If arbitration changed the answer, it should be the payer. If not, the old answerer.
function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer)
onlyOwner
public {
delete arbitration_bounties[question_id];
realitycheck.submitAnswerByArbitrator(question_id, answer, answerer);
}
/// @notice Request arbitration, freezing the question until we send submitAnswerByArbitrator
/// @dev The bounty can be paid only in part, in which case the last person to pay will be considered the payer
/// Will trigger an error if the notification fails, eg because the question has already been finalized
/// @param question_id The question in question
/// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
function requestArbitration(bytes32 question_id, uint256 max_previous)
external payable returns (bool) {
uint256 arbitration_fee = getDisputeFee(question_id);
require(arbitration_fee > 0);
arbitration_bounties[question_id] += msg.value;
uint256 paid = arbitration_bounties[question_id];
if (paid >= arbitration_fee) {
realitycheck.notifyOfArbitrationRequest(question_id, msg.sender, max_previous);
LogRequestArbitration(question_id, msg.value, msg.sender, 0);
return true;
} else {
require(!realitycheck.isFinalized(question_id));
LogRequestArbitration(question_id, msg.value, msg.sender, arbitration_fee - paid);
return false;
}
}
/// @notice Withdraw any accumulated fees to the specified address
/// @param addr The address to which the balance should be sent
function withdraw(address addr)
onlyOwner
public {
addr.transfer(this.balance);
}
function()
public payable {
}
/// @notice Withdraw any accumulated question fees from the specified address into this contract
/// @dev Funds can then be liberated from this contract with our withdraw() function
function callWithdraw()
onlyOwner
public {
realitycheck.withdraw();
}
}
|
Request arbitration, freezing the question until we send submitAnswerByArbitrator The bounty can be paid only in part, in which case the last person to pay will be considered the payer Will trigger an error if the notification fails, eg because the question has already been finalized question_id The question in question max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction.
|
function requestArbitration(bytes32 question_id, uint256 max_previous)
external payable returns (bool) {
uint256 arbitration_fee = getDisputeFee(question_id);
require(arbitration_fee > 0);
arbitration_bounties[question_id] += msg.value;
uint256 paid = arbitration_bounties[question_id];
if (paid >= arbitration_fee) {
realitycheck.notifyOfArbitrationRequest(question_id, msg.sender, max_previous);
LogRequestArbitration(question_id, msg.value, msg.sender, 0);
return true;
require(!realitycheck.isFinalized(question_id));
LogRequestArbitration(question_id, msg.value, msg.sender, arbitration_fee - paid);
return false;
}
}
| 14,952,115
|
pragma solidity ^0.6.0;
/// @title Unifi contract - EthLondon Hackathon
/// @author Extropy.io team
/// @notice You can use this contract to get paid for sharing your wifi
/// @dev Are we going to implement ERC20 Token?
contract UniFi {
// Minimum topup is 10 MB = 10,000,000,000,000 wei
uint constant minimum_topup = 10_000_000_000_000 wei;
uint8 base_rating = 3;
struct User {
bool is_connected; // to the wifi?
bool is_registered; // have he ever used Uni-Fi
uint256 balance;
}
struct Host {
uint256 balance;
uint256 longitude;
uint256 latitude;
uint256 users_connected;
uint256 base_fee;
string ssid;
string mac_address;
uint8[5] rating;
}
mapping(address => Host) host_array;
mapping(address => User) public user_array;
mapping(address => uint) pendingWithdrawals;
constructor() public {
// set owner
}
modifier isConnected(address user) {
require(user_array[user].is_connected == true);
_;
}
modifier isNotConnected(address user) {
require(user_array[user].is_connected == false);
_;
}
/// Get user balance
/// @return the user balance
function getUserBalance() public view returns(uint) {
return user_array[msg.sender].balance;
}
/// @notice registering host (SSID: `_ssid`, MAC: `_mac_address`)
/// @dev
/// @param _longitude wifi longitude (geolocation)
/// @param _latitude wifi latitude (geolocation)
/// @param _ssid SSID of the wifi host
/// @param _mac_address Mac Address
function registerHost(
uint256 _longitude,
uint256 _latitude,
uint256 _base_fee,
string memory _ssid,
string memory _mac_address
) public {
host_array[msg.sender].base_fee = _base_fee;
host_array[msg.sender].longitude = _longitude;
host_array[msg.sender].latitude = _latitude;
host_array[msg.sender].ssid = _ssid;
host_array[msg.sender].mac_address = _mac_address;
host_array[msg.sender].balance = 0;
}
/// @notice Congrats have been registered !
/// @dev Set the balance to 0 by default
function registerUser() private isNotConnected(msg.sender){
user_array[msg.sender] = User({
is_connected: false,
is_registered: true,
balance: 0
});
}
/// @notice Congrats `_host`, you have been granted some reputation! New reputation = `_rep` + 1
/// @dev Set rep
/// @param _host The host to reward reputation
/// @param _rep the number of reputation to grant
function repHost(address _host, uint8 _rep) internal {
host_array[_host].rating[_rep] += 1;
}
/// @notice Log-in successfully to the host
/// @dev Shouldn't we define to which host the user is logged in?
function login() public isNotConnected(msg.sender) {
if ( user_array[msg.sender].is_registered == false ) {
registerUser();
}
// here we login
user_array[msg.sender].is_connected = true;
}
/// @notice You have been logged out
/// @dev Same, shouldn't we specify the host that we log-out from?
/// @param user the user to log-out
/// @param charge the charge to apply
function logout(address user, uint charge) public isConnected(user) {
// subtract the charge
user_array[user].balance -= charge;
withdrawUser();
//address(this).transfer(due_to_contract);
// user.transfer(due_to_user);
user_array[user].is_connected = false;
}
/// @notice you are about to top up your balance
/// @dev we shouldn't use the keyword `balance` for struct member
/// since it's a reserved keyword in Solidity (for clarity)
function deposit() public payable {
user_array[msg.sender].balance += msg.value;
}
/// @notice
/// @dev Use the pending withdraw pattern
function withdrawHost() public {
// subtract user usage from host balance
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
/// @notice
/// @dev
function withdrawUser() public {
// subtract user usage from user balance
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
msg.sender.transfer(amount);
pendingWithdrawals[msg.sender] = 0;
}
/// Handle ethers received by the contract
receive() external payable {}
/// Handle undefined function calls
fallback() external {
revert();
}
}
|
subtract user usage from user balance Remember to zero the pending refund before sending to prevent re-entrancy attacks
|
function withdrawUser() public {
uint amount = pendingWithdrawals[msg.sender];
msg.sender.transfer(amount);
pendingWithdrawals[msg.sender] = 0;
}
| 15,865,863
|
// PixelCoins Source code
pragma solidity ^0.4.11;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title A facet of PixelCore that manages special access privileges.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io)
contract PixelAuthority {
/// @dev Emited when contract is upgraded
event ContractUpgrade(address newContract);
address public authorityAddress;
uint public authorityBalance = 0;
/// @dev Access modifier for authority-only functionality
modifier onlyAuthority() {
require(msg.sender == authorityAddress);
_;
}
/// @dev Assigns a new address to act as the authority. Only available to the current authority.
/// @param _newAuthority The address of the new authority
function setAuthority(address _newAuthority) external onlyAuthority {
require(_newAuthority != address(0));
authorityAddress = _newAuthority;
}
}
/// @title Base contract for PixelCoins. Holds all common structs, events and base variables.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io)
/// @dev See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelBase is PixelAuthority {
/*** EVENTS ***/
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a Pixel
/// ownership is assigned.
event Transfer(address from, address to, uint256 tokenId);
/*** CONSTANTS ***/
uint32 public WIDTH = 1000;
uint32 public HEIGHT = 1000;
/*** STORAGE ***/
/// @dev A mapping from pixel ids to the address that owns them. A pixel address of 0 means,
/// that the pixel can still be bought.
mapping (uint256 => address) public pixelIndexToOwner;
/// Address that is approved to change ownship
mapping (uint256 => address) public pixelIndexToApproved;
/// Stores the color of an pixel, indexed by pixelid
mapping (uint256 => uint32) public colors;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Assigns ownership of a specific Pixel to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Can no overflowe since the number of Pixels is capped.
// transfer ownership
ownershipTokenCount[_to]++;
pixelIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete pixelIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev Checks if a given address is the current owner of a particular Pixel.
/// @param _claimant the address we are validating against.
/// @param _tokenId Pixel id
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Pixel.
/// @param _claimant the address we are confirming pixel is approved for.
/// @param _tokenId pixel id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return pixelIndexToApproved[_tokenId] == _claimant;
}
}
/// @title The facet of the PixelCoins core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PixelCore contract documentation to understand how the various contract facets are arranged.
contract PixelOwnership is PixelBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "PixelCoins";
string public constant symbol = "PXL";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
string public metaBaseUrl = "https://pixelcoins.io/meta/";
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @notice Returns the number ofd Pixels owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a Pixel to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// PixelCoins specifically) or your Pixel may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Pixel to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any pixel (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// You can only send your own pixel.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific pixel via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the pixel that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// address is not currently managed by the contract (it is in an auction)
require(pixelIndexToApproved[_tokenId] != address(this));
// Register the approval (replacing any previous approval).
pixelIndexToApproved[_tokenId] = _to;
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Pixel owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the pixel to be transfered.
/// @param _to The address that should take ownership of the Pixel. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Pixel to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own anyd Pixels (except very briefly
// after a gen0 cat is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of pixels currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return WIDTH * HEIGHT;
}
/// @notice Returns the address currently assigned ownership of a given Pixel.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = pixelIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns the addresses currently assigned ownership of the given pixel area.
function ownersOfArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (address[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new address[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = pixelIndexToOwner[tokenId + j];
r++;
}
}
}
/// @notice Returns a list of all Pixel IDs assigned to an address.
/// @param _owner The owner whosed Pixels we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Pixel array looking for pixels belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPixels = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all pixels have IDs starting at 0 and increasing
// sequentially up to the totalCat count.
uint256 pixelId;
for (pixelId = 0; pixelId <= totalPixels; pixelId++) {
if (pixelIndexToOwner[pixelId] == _owner) {
result[resultIndex] = pixelId;
resultIndex++;
}
}
return result;
}
}
// Taken from https://ethereum.stackexchange.com/a/10929
function uintToString(uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
// Taken from https://ethereum.stackexchange.com/a/10929
function appendUintToString(string inStr, uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
function setMetaBaseUrl(string _metaBaseUrl) external onlyAuthority {
metaBaseUrl = _metaBaseUrl;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Pixel whose metadata should be returned.
function tokenMetadata(uint256 _tokenId) external view returns (string infoUrl) {
return appendUintToString(metaBaseUrl, _tokenId);
}
}
contract PixelPainting is PixelOwnership {
event Paint(uint256 tokenId, uint32 color);
// Sets the color of an individual pixel
function setPixelColor(uint256 _tokenId, uint32 _color) external {
// check that the token id is in the range
require(_tokenId < HEIGHT * WIDTH);
// check that the sender is owner of the pixel
require(_owns(msg.sender, _tokenId));
colors[_tokenId] = _color;
}
// Sets the color of the pixels in an area, left to right and then top to bottom
function setPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2, uint32[] _colors) external {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(_colors.length == (y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
if (_owns(msg.sender, tokenId + j)) {
uint32 color = _colors[r];
colors[tokenId + j] = color;
Paint(tokenId + j, color);
}
r++;
}
}
}
// Returns the color of a given pixel
function getPixelColor(uint256 _tokenId) external view returns (uint32 color) {
require(_tokenId < HEIGHT * WIDTH);
color = colors[_tokenId];
}
// Returns the colors of the pixels in an area, left to right and then top to bottom
function getPixelAreaColor(uint256 x, uint256 y, uint256 x2, uint256 y2) external view returns (uint32[] result) {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
result = new uint32[]((y2 - y) * (x2 - x));
uint256 r = 0;
for (uint256 i = y; i < y2; i++) {
uint256 tokenId = i * WIDTH;
for (uint256 j = x; j < x2; j++) {
result[r] = colors[tokenId + j];
r++;
}
}
}
}
/// @title all functions for buying empty pixels
contract PixelMinting is PixelPainting {
uint public pixelPrice = 3030 szabo;
// Set the price for a pixel
function setNewPixelPrice(uint _pixelPrice) external onlyAuthority {
pixelPrice = _pixelPrice;
}
// buy en empty pixel
function buyEmptyPixel(uint256 _tokenId) external payable {
require(msg.value == pixelPrice);
require(_tokenId < HEIGHT * WIDTH);
require(pixelIndexToOwner[_tokenId] == address(0));
// increase authority balance
authorityBalance += msg.value;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, msg.sender, _tokenId);
}
// buy an area of pixels, left to right, top to bottom
function buyEmptyPixelArea(uint256 x, uint256 y, uint256 x2, uint256 y2) external payable {
require(x2 > x && y2 > y);
require(x2 <= WIDTH && y2 <= HEIGHT);
require(msg.value == pixelPrice * (x2-x) * (y2-y));
uint256 i;
uint256 tokenId;
uint256 j;
// check that all pixels to buy are available
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
require(pixelIndexToOwner[tokenId + j] == address(0));
}
}
authorityBalance += msg.value;
// Do the actual transfer
for (i = y; i < y2; i++) {
tokenId = i * WIDTH;
for (j = x; j < x2; j++) {
_transfer(0, msg.sender, tokenId + j);
}
}
}
}
/// @title all functions for managing pixel auctions
contract PixelAuction is PixelMinting {
// Represents an auction on an NFT
struct Auction {
// Current state of the auction.
address highestBidder;
uint highestBid;
uint256 endTime;
bool live;
}
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
// Allowed withdrawals of previous bids
mapping (address => uint) pendingReturns;
// Duration of an auction
uint256 public duration = 60 * 60 * 24 * 4;
// Auctions will be enabled later
bool public auctionsEnabled = false;
// Change the duration for new auctions
function setDuration(uint _duration) external onlyAuthority {
duration = _duration;
}
// Enable or disable auctions
function setAuctionsEnabled(bool _auctionsEnabled) external onlyAuthority {
auctionsEnabled = _auctionsEnabled;
}
// create a new auctions for a given pixel, only owner or authority can do this
// The authority will only do this if pixels are misused or lost
function createAuction(
uint256 _tokenId
)
external payable
{
// only authority or owner can start auction
require(auctionsEnabled);
require(_owns(msg.sender, _tokenId) || msg.sender == authorityAddress);
// No auction is currently running
require(!tokenIdToAuction[_tokenId].live);
uint startPrice = pixelPrice;
if (msg.sender == authorityAddress) {
startPrice = 0;
}
require(msg.value == startPrice);
// this prevents transfers during the auction
pixelIndexToApproved[_tokenId] = address(this);
tokenIdToAuction[_tokenId] = Auction(
msg.sender,
startPrice,
block.timestamp + duration,
true
);
AuctionStarted(_tokenId);
}
// bid for an pixel auction
function bid(uint256 _tokenId) external payable {
// No arguments are necessary, all
// information is already part of
// the transaction. The keyword payable
// is required for the function to
// be able to receive Ether.
Auction storage auction = tokenIdToAuction[_tokenId];
// Revert the call if the bidding
// period is over.
require(auction.live);
require(auction.endTime > block.timestamp);
// If the bid is not higher, send the
// money back.
require(msg.value > auction.highestBid);
if (auction.highestBidder != 0) {
// Sending back the money by simply using
// highestBidder.send(highestBid) is a security risk
// because it could execute an untrusted contract.
// It is always safer to let the recipients
// withdraw their money themselves.
pendingReturns[auction.highestBidder] += auction.highestBid;
}
auction.highestBidder = msg.sender;
auction.highestBid = msg.value;
HighestBidIncreased(_tokenId, msg.sender, msg.value);
}
/// Withdraw a bid that was overbid.
function withdraw() external returns (bool) {
uint amount = pendingReturns[msg.sender];
if (amount > 0) {
// It is important to set this to zero because the recipient
// can call this function again as part of the receiving call
// before `send` returns.
pendingReturns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
// No need to call throw here, just reset the amount owing
pendingReturns[msg.sender] = amount;
return false;
}
}
return true;
}
// /// End the auction and send the highest bid
// /// to the beneficiary.
function endAuction(uint256 _tokenId) external {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
Auction storage auction = tokenIdToAuction[_tokenId];
// 1. Conditions
require(auction.endTime < block.timestamp);
require(auction.live); // this function has already been called
// 2. Effects
auction.live = false;
AuctionEnded(_tokenId, auction.highestBidder, auction.highestBid);
// 3. Interaction
address owner = pixelIndexToOwner[_tokenId];
// transfer money without
uint amount = auction.highestBid * 9 / 10;
pendingReturns[owner] += amount;
authorityBalance += (auction.highestBid - amount);
// transfer token
_transfer(owner, auction.highestBidder, _tokenId);
}
// // Events that will be fired on changes.
event AuctionStarted(uint256 _tokenId);
event HighestBidIncreased(uint256 _tokenId, address bidder, uint amount);
event AuctionEnded(uint256 _tokenId, address winner, uint amount);
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address highestBidder,
uint highestBid,
uint endTime,
bool live
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.highestBidder,
auction.highestBid,
auction.endTime,
auction.live
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getHighestBid(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
return auction.highestBid;
}
}
/// @title PixelCore: Pixels in the blockchain
/// @author Oliver Schneider <info@pixelcoins.io> (https://pixelcoins.io), based on Axiom Zen (https://www.axiomzen.co)
/// @dev The main PixelCoins contract
contract PixelCore is PixelAuction {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main PixelCore smart contract instance.
function PixelCore() public {
// the creator of the contract is the initial authority
authorityAddress = msg.sender;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyAuthority {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
// @dev Allows the authority to capture the balance available to the contract.
function withdrawBalance() external onlyAuthority returns (bool) {
uint amount = authorityBalance;
if (amount > 0) {
authorityBalance = 0;
if (!authorityAddress.send(amount)) {
authorityBalance = amount;
return false;
}
}
return true;
}
}
|
Returns auction info for an NFT on auction. _tokenId - ID of NFT on auction.
|
function getAuction(uint256 _tokenId)
external
view
returns
(
address highestBidder,
uint highestBid,
uint endTime,
bool live
) {
Auction storage auction = tokenIdToAuction[_tokenId];
return (
auction.highestBidder,
auction.highestBid,
auction.endTime,
auction.live
);
}
| 10,120,732
|
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
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;
}
}
interface sbCommunityInterface {
function getTokenData(address token, uint256 day)
external
view
returns (
uint256,
uint256,
uint256
);
function receiveRewards(uint256 day, uint256 amount) external;
function serviceAccepted(address service) external view returns (bool);
function getMinerRewardPercentage() external view returns (uint256);
}
contract sbControllerV3 {
event CommunityAdded(address indexed community);
event RewardsReleased(
address indexed receiver,
uint256 amount,
uint256 indexed day
);
using SafeMath for uint256;
bool internal initDone;
address internal sbTimelock;
IERC20 internal strongToken;
sbTokensInterface internal sbTokens;
sbStrongPoolInterface internal sbStrongPool;
sbVotesInterface internal sbVotes;
uint256 internal startDay;
mapping(uint256 => uint256) internal COMMUNITY_DAILY_REWARDS_BY_YEAR;
mapping(uint256 => uint256) internal STRONGPOOL_DAILY_REWARDS_BY_YEAR;
mapping(uint256 => uint256) internal VOTER_DAILY_REWARDS_BY_YEAR;
uint256 internal MAX_YEARS;
address[] internal communities;
mapping(uint256 => uint256) internal dayMineSecondsUSDTotal;
mapping(address => mapping(uint256 => uint256))
internal communityDayMineSecondsUSD;
mapping(address => mapping(uint256 => uint256))
internal communityDayRewards;
mapping(address => uint256) internal communityDayStart;
uint256 internal dayLastReleasedRewardsFor;
address internal superAdmin;
address internal pendingSuperAdmin;
function removeTokens(address account, uint256 amount) public {
require(msg.sender == superAdmin, "not superAdmin");
strongToken.transfer(account, amount);
}
function setPendingSuperAdmin(address newPendingSuperAdmin) public {
require(
msg.sender == superAdmin && msg.sender != address(0),
"not superAdmin"
);
pendingSuperAdmin = newPendingSuperAdmin;
}
function acceptSuperAdmin() public {
require(
msg.sender == pendingSuperAdmin && msg.sender != address(0),
"not pendingSuperAdmin"
);
superAdmin = pendingSuperAdmin;
pendingSuperAdmin = address(0);
}
function getSuperAdminAddressUsed() public view returns (address) {
return superAdmin;
}
function getPendingSuperAdminAddressUsed() public view returns (address) {
return pendingSuperAdmin;
}
function updateCommunityDailyRewardsByYear(uint256 amount) public {
require(
msg.sender == superAdmin && msg.sender != address(0),
"not superAdmin"
);
uint256 year = _getYearDayIsIn(_getCurrentDay());
require(year <= MAX_YEARS, "invalid year");
COMMUNITY_DAILY_REWARDS_BY_YEAR[year] = amount;
}
function updateStrongPoolDailyRewardsByYear(uint256 amount) public {
require(
msg.sender == superAdmin && msg.sender != address(0),
"not superAdmin"
);
uint256 year = _getYearDayIsIn(_getCurrentDay());
require(year <= MAX_YEARS, "invalid year");
STRONGPOOL_DAILY_REWARDS_BY_YEAR[year] = amount;
}
function updateVoterDailyRewardsByYear(uint256 amount) public {
require(
msg.sender == superAdmin && msg.sender != address(0),
"not superAdmin"
);
uint256 year = _getYearDayIsIn(_getCurrentDay());
require(year <= MAX_YEARS, "invalid year");
VOTER_DAILY_REWARDS_BY_YEAR[year] = amount;
}
function upToDate() external pure returns (bool) {
return true;
// return dayLastReleasedRewardsFor == _getCurrentDay().sub(1);
}
function addCommunity(address community) external {
require(msg.sender == sbTimelock, "not sbTimelock");
require(community != address(0), "community not zero address");
require(!_communityExists(community), "community exists");
communities.push(community);
communityDayStart[community] = _getCurrentDay();
emit CommunityAdded(community);
}
function getCommunities() external view returns (address[] memory) {
return communities;
}
function getDayMineSecondsUSDTotal(uint256 day)
external
view
returns (uint256)
{
// require(day >= startDay, '1: invalid day');
// require(day <= dayLastReleasedRewardsFor, '2: invalid day');
return dayMineSecondsUSDTotal[day];
}
function getCommunityDayMineSecondsUSD(address community, uint256 day)
external
view
returns (uint256)
{
require(_communityExists(community), "invalid community");
// require(day >= communityDayStart[community], '1: invalid day');
// require(day <= dayLastReleasedRewardsFor, '2: invalid day');
return communityDayMineSecondsUSD[community][day];
}
function getCommunityDayRewards(address community, uint256 day)
external
view
returns (uint256)
{
require(_communityExists(community), "invalid community");
// require(day >= communityDayStart[community], '1: invalid day');
// require(day <= dayLastReleasedRewardsFor, '2: invalid day');
return communityDayRewards[community][day];
}
function getCommunityDailyRewards(uint256 day)
external
view
returns (uint256)
{
require(day >= startDay, "invalid day");
uint256 year = _getYearDayIsIn(day);
require(year <= MAX_YEARS, "invalid year");
return COMMUNITY_DAILY_REWARDS_BY_YEAR[year];
}
function getStrongPoolDailyRewards(uint256 day)
external
view
returns (uint256)
{
require(day >= startDay, "invalid day");
uint256 year = _getYearDayIsIn(day);
require(year <= MAX_YEARS, "invalid year");
return STRONGPOOL_DAILY_REWARDS_BY_YEAR[year];
}
function getVoterDailyRewards(uint256 day) external view returns (uint256) {
require(day >= startDay, "invalid day");
uint256 year = _getYearDayIsIn(day);
require(year <= MAX_YEARS, "invalid year");
return VOTER_DAILY_REWARDS_BY_YEAR[year];
}
function getStartDay() external view returns (uint256) {
return startDay;
}
function communityAccepted(address community) external view returns (bool) {
return _communityExists(community);
}
function getMaxYears() public view returns (uint256) {
return MAX_YEARS;
}
function getCommunityDayStart(address community)
public
view
returns (uint256)
{
require(_communityExists(community), "invalid community");
return communityDayStart[community];
}
function getSbTimelockAddressUsed() public view returns (address) {
return sbTimelock;
}
function getStrongAddressUsed() public view returns (address) {
return address(strongToken);
}
function getSbTokensAddressUsed() public view returns (address) {
return address(sbTokens);
}
function getSbStrongPoolAddressUsed() public view returns (address) {
return address(sbStrongPool);
}
function getSbVotesAddressUsed() public view returns (address) {
return address(sbVotes);
}
function getCurrentYear() public view returns (uint256) {
uint256 day = _getCurrentDay().sub(startDay);
return _getYearDayIsIn(day == 0 ? startDay : day);
}
function getYearDayIsIn(uint256 day) public view returns (uint256) {
require(day >= startDay, "invalid day");
return _getYearDayIsIn(day);
}
function getCurrentDay() public view returns (uint256) {
return _getCurrentDay();
}
function getDayLastReleasedRewardsFor() public view returns (uint256) {
return dayLastReleasedRewardsFor;
}
// function releaseRewards() public {
// uint256 currentDay = _getCurrentDay();
// require(currentDay > dayLastReleasedRewardsFor.add(1), 'already released');
// require(sbTokens.upToDate(), 'need token prices');
// dayLastReleasedRewardsFor = dayLastReleasedRewardsFor.add(1);
// uint256 year = _getYearDayIsIn(dayLastReleasedRewardsFor);
// require(year <= MAX_YEARS, 'invalid year');
// address[] memory tokenAddresses = sbTokens.getTokens();
// uint256[] memory tokenPrices = sbTokens.getTokenPrices(dayLastReleasedRewardsFor);
// for (uint256 i = 0; i < communities.length; i++) {
// address community = communities[i];
// uint256 sum = 0;
// for (uint256 j = 0; j < tokenAddresses.length; j++) {
// address token = tokenAddresses[j];
// (, , uint256 minedSeconds) = sbCommunityInterface(community).getTokenData(token, dayLastReleasedRewardsFor);
// uint256 tokenPrice = tokenPrices[j];
// uint256 minedSecondsUSD = tokenPrice.mul(minedSeconds).div(1e18);
// sum = sum.add(minedSecondsUSD);
// }
// communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor] = sum;
// dayMineSecondsUSDTotal[dayLastReleasedRewardsFor] = dayMineSecondsUSDTotal[dayLastReleasedRewardsFor].add(sum);
// }
// for (uint256 i = 0; i < communities.length; i++) {
// address community = communities[i];
// if (communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor] == 0) {
// continue;
// }
// communityDayRewards[community][dayLastReleasedRewardsFor] = communityDayMineSecondsUSD[community][dayLastReleasedRewardsFor]
// .mul(COMMUNITY_DAILY_REWARDS_BY_YEAR[year])
// .div(dayMineSecondsUSDTotal[dayLastReleasedRewardsFor]);
// uint256 amount = communityDayRewards[community][dayLastReleasedRewardsFor];
// strongToken.approve(community, amount);
// sbCommunityInterface(community).receiveRewards(dayLastReleasedRewardsFor, amount);
// emit RewardsReleased(community, amount, currentDay);
// }
// (, , uint256 strongPoolMineSeconds) = sbStrongPool.getMineData(dayLastReleasedRewardsFor);
// if (strongPoolMineSeconds != 0) {
// strongToken.approve(address(sbStrongPool), STRONGPOOL_DAILY_REWARDS_BY_YEAR[year]);
// sbStrongPool.receiveRewards(dayLastReleasedRewardsFor, STRONGPOOL_DAILY_REWARDS_BY_YEAR[year]);
// emit RewardsReleased(address(sbStrongPool), STRONGPOOL_DAILY_REWARDS_BY_YEAR[year], currentDay);
// }
// bool hasVoteSeconds = false;
// for (uint256 i = 0; i < communities.length; i++) {
// address community = communities[i];
// (, , uint256 voteSeconds) = sbVotes.getCommunityData(community, dayLastReleasedRewardsFor);
// if (voteSeconds > 0) {
// hasVoteSeconds = true;
// break;
// }
// }
// if (hasVoteSeconds) {
// strongToken.approve(address(sbVotes), VOTER_DAILY_REWARDS_BY_YEAR[year]);
// sbVotes.receiveVoterRewards(dayLastReleasedRewardsFor, VOTER_DAILY_REWARDS_BY_YEAR[year]);
// emit RewardsReleased(address(sbVotes), VOTER_DAILY_REWARDS_BY_YEAR[year], currentDay);
// }
// }
function _getCurrentDay() internal view returns (uint256) {
return block.timestamp.div(1 days).add(1);
}
function _communityExists(address community) internal view returns (bool) {
for (uint256 i = 0; i < communities.length; i++) {
if (communities[i] == community) {
return true;
}
}
return false;
}
function _getYearDayIsIn(uint256 day) internal view returns (uint256) {
return day.sub(startDay).div(366).add(1); // dividing by 366 makes day 1 and 365 be in year 1
}
}
interface sbStrongPoolInterface {
function serviceMinMined(address miner) external view returns (bool);
function minerMinMined(address miner) external view returns (bool);
function mineFor(address miner, uint256 amount) external;
function getMineData(uint256 day)
external
view
returns (
uint256,
uint256,
uint256
);
function receiveRewards(uint256 day, uint256 amount) external;
}
interface sbTokensInterface {
function getTokens() external view returns (address[] memory);
function getTokenPrices(uint256 day) external view returns (uint256[] memory);
function tokenAccepted(address token) external view returns (bool);
function upToDate() external view returns (bool);
function getTokenPrice(address token, uint256 day) external view returns (uint256);
}
interface sbVotesInterface {
function getCommunityData(address community, uint256 day)
external
view
returns (
uint256,
uint256,
uint256
);
function getPriorProposalVotes(address account, uint256 blockNumber) external view returns (uint96);
function receiveServiceRewards(uint256 day, uint256 amount) external;
function receiveVoterRewards(uint256 day, uint256 amount) external;
function updateVotes(
address staker,
uint256 rawAmount,
bool adding
) external;
}
|
require(day >= communityDayStart[community], '1: invalid day'); require(day <= dayLastReleasedRewardsFor, '2: invalid day');
|
function getCommunityDayRewards(address community, uint256 day)
external
view
returns (uint256)
{
require(_communityExists(community), "invalid community");
return communityDayRewards[community][day];
}
| 7,485,552
|
//Address: 0xd1670c55f5e68fede5fddd8ace64a3329f778b89
//Contract name: ATSTokenReservation
//Balance: 215.853806028 Ether
//Verification Date: 5/30/2018
//Transacion Count: 81
// CODE STARTS HERE
pragma solidity ^0.4.23;
/*
* Contract accepting reservations for ATS tokens.
* The actual tokens are not yet created and distributed due to non-technical reasons.
* This contract is used to collect funds for the ATS token sale and to transparently document that on a blockchain.
* It is tailored to allow a simple user journey while keeping complexity minimal.
* Once the privileged "state controller" sets the state to "Open", anybody can send Ether to the contract.
* Only Ether sent from whitelisted addresses is accepted for future ATS token conversion.
* The whitelisting is done by a dedicated whitelist controller.
* Whitelisting can take place asynchronously - that is, participants don't need to wait for the whitelisting to
* succeed before sending funds. This is a technical detail which allows for a smoother user journey.
* The state controller can switch to synchronous whitelisting (no Ether accepted from accounts not whitelisted before).
* Participants can trigger refunding during the Open state by making a transfer of 0 Ether.
* Funds of those not whitelisted (not accepted) are never locked, they can trigger refund beyond Open state.
* Only in Over state can whitelisted Ether deposits be fetched from the contract.
*
* When setting the state to Open, the state controller specifies a minimal timeframe for this state.
* Transition to the next state (Locked) is not possible (enforced by the contract).
* This gives participants the guarantee that they can get their full deposits refunded anytime and independently
* of the will of anybody else during that timeframe.
* (Note that this is true only as long as the whole process takes place before the date specified by FALLBACK_FETCH_FUNDS_TS)
*
* Ideally, there's no funds left in the contract once the state is set to Over and the accepted deposits were fetched.
* Since this can't really be foreseen, there's a fallback which allows to fetch all remaining Ether
* to a pre-specified address after a pre-specified date.
*
* Static analysis: block.timestamp is not used in a way which gives miners leeway for taking advantage.
*
* see https://code.lab10.io/graz/04-artis/artis/issues/364 for task evolution
*/
contract ATSTokenReservation {
// ################### DATA STRUCTURES ###################
enum States {
Init, // initial state. Contract is deployed, but deposits not yet accepted
Open, // open for token reservations. Refunds possible for all
Locked, // open for token reservations. Refunds locked for accepted deposits
Over // contract has done its duty. Funds payout can be triggered by state controller
}
// ################### CONSTANTS ###################
// 1. Oct 2018
uint32 FALLBACK_PAYOUT_TS = 1538352000;
// ################### STATE VARIABLES ###################
States public state = States.Init;
// privileged account: switch contract state, change config, whitelisting, trigger payout, ...
address public stateController;
// privileged account: whitelisting
address public whitelistController;
// Collected funds can be transferred only to this address. Is set in constructor.
address public payoutAddress;
// accepted deposits (received from whitelisted accounts)
uint256 public cumAcceptedDeposits = 0;
// not (yet) accepted deposits (received from non-whitelisted accounts)
uint256 public cumAlienDeposits = 0;
// cap for how much we accept (since the amount of tokens sold is also capped)
uint256 public maxCumAcceptedDeposits = 1E9 * 1E18; // pre-set to effectively unlimited (> existing ETH)
uint256 public minDeposit = 0.1 * 1E18; // lower bound per participant (can be a kind of spam protection)
uint256 minLockingTs; // earliest possible start of "locked" phase
// whitelisted addresses (those having "accepted" deposits)
mapping (address => bool) public whitelist;
// the state controller can set this in order to disallow deposits from addresses not whitelisted before
bool public requireWhitelistingBeforeDeposit = false;
// tracks accepted deposits (whitelisted accounts)
mapping (address => uint256) public acceptedDeposits;
// tracks alien (not yet accepted) deposits (non-whitelisted accounts)
mapping (address => uint256) public alienDeposits;
// ################### EVENTS ###################
// emitted events transparently document the open funding activities.
// only deposits made by whitelisted accounts (and not followed by a refund) count.
event StateTransition(States oldState, States newState);
event Whitelisted(address addr);
event Deposit(address addr, uint256 amount);
event Refund(address addr, uint256 amount);
// emitted when the accepted deposits are fetched to an account controlled by the ATS token provider
event FetchedDeposits(uint256 amount);
// ################### MODIFIERS ###################
modifier onlyStateControl() { require(msg.sender == stateController, "no permission"); _; }
modifier onlyWhitelistControl() {
require(msg.sender == stateController || msg.sender == whitelistController, "no permission");
_;
}
modifier requireState(States _requiredState) { require(state == _requiredState, "wrong state"); _; }
// ################### CONSTRUCTOR ###################
// the contract creator is set as stateController
constructor(address _whitelistController, address _payoutAddress) public {
whitelistController = _whitelistController;
payoutAddress = _payoutAddress;
stateController = msg.sender;
}
// ################### FALLBACK FUNCTION ###################
// implements the deposit and refund actions.
function () payable public {
if(msg.value > 0) {
require(state == States.Open || state == States.Locked);
if(requireWhitelistingBeforeDeposit) {
require(whitelist[msg.sender] == true, "not whitelisted");
}
tryDeposit();
} else {
tryRefund();
}
}
// ################### PUBLIC FUNCTIONS ###################
function stateSetOpen(uint32 _minLockingTs) public
onlyStateControl
requireState(States.Init)
{
minLockingTs = _minLockingTs;
setState(States.Open);
}
function stateSetLocked() public
onlyStateControl
requireState(States.Open)
{
require(block.timestamp >= minLockingTs);
setState(States.Locked);
}
function stateSetOver() public
onlyStateControl
requireState(States.Locked)
{
setState(States.Over);
}
// state controller can change the cap. Reducing possible only if not below current deposits
function updateMaxAcceptedDeposits(uint256 _newMaxDeposits) public onlyStateControl {
require(cumAcceptedDeposits <= _newMaxDeposits);
maxCumAcceptedDeposits = _newMaxDeposits;
}
// new limit to be enforced for future deposits
function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl {
minDeposit = _newMinDeposit;
}
// option to switch between async and sync whitelisting
function setRequireWhitelistingBeforeDeposit(bool _newState) public onlyStateControl {
requireWhitelistingBeforeDeposit = _newState;
}
// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether.
// In this case the deposit is converted form alien to accepted.
// Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially,
// it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that
// the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted).
// This function is idempotent.
function addToWhitelist(address _addr) public onlyWhitelistControl {
if(whitelist[_addr] != true) {
// if address has alien deposit: convert it to accepted
if(alienDeposits[_addr] > 0) {
cumAcceptedDeposits += alienDeposits[_addr];
acceptedDeposits[_addr] += alienDeposits[_addr];
cumAlienDeposits -= alienDeposits[_addr];
delete alienDeposits[_addr]; // needs to be the last statement in this block!
}
whitelist[_addr] = true;
emit Whitelisted(_addr);
}
}
// Option for batched whitelisting (for times with crowded chain).
// caller is responsible to not blow gas limit with too many addresses at once
function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl {
for (uint i = 0; i < _addresses.length; i++) {
addToWhitelist(_addresses[i]);
}
}
// transfers an alien deposit back to the sender
function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
// payout of the accepted deposits to the pre-designated address, available once it's all over
function payout() public
onlyStateControl
requireState(States.Over)
{
uint256 amount = cumAcceptedDeposits;
cumAcceptedDeposits = 0;
emit FetchedDeposits(amount);
payoutAddress.transfer(amount);
// not idempotent, but multiple invocation would just trigger zero-transfers
}
// After the specified date, any of the privileged/special accounts can trigger payment of remaining funds
// to the payoutAddress. This is a safety net to minimize the risk of funds remaining stuck.
// It's not yet clear what we can / should / are allowed to do with alien deposits which aren't reclaimed.
// With this fallback in place, we have for example the option to donate them at some point.
function fallbackPayout() public {
require(msg.sender == stateController || msg.sender == whitelistController || msg.sender == payoutAddress);
require(block.timestamp > FALLBACK_PAYOUT_TS);
payoutAddress.transfer(address(this).balance);
}
// ################### INTERNAL FUNCTIONS ###################
// rule enforcement and book-keeping for incoming deposits
function tryDeposit() internal {
require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits);
if(whitelist[msg.sender] == true) {
require(acceptedDeposits[msg.sender] + msg.value >= minDeposit);
acceptedDeposits[msg.sender] += msg.value;
cumAcceptedDeposits += msg.value;
} else {
require(alienDeposits[msg.sender] + msg.value >= minDeposit);
alienDeposits[msg.sender] += msg.value;
cumAlienDeposits += msg.value;
}
emit Deposit(msg.sender, msg.value);
}
// rule enforcement and book-keeping for refunding requests
function tryRefund() internal {
// Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type.
// With a complex type, this code would produce dangling references.
uint256 withdrawAmount;
if(whitelist[msg.sender] == true) {
require(state == States.Open);
withdrawAmount = acceptedDeposits[msg.sender];
require(withdrawAmount > 0);
delete acceptedDeposits[msg.sender]; // implies setting the value to 0
cumAcceptedDeposits -= withdrawAmount;
} else {
// alien deposits can be withdrawn anytime (we prefer to not touch them)
withdrawAmount = alienDeposits[msg.sender];
require(withdrawAmount > 0);
delete alienDeposits[msg.sender]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
}
emit Refund(msg.sender, withdrawAmount);
// do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern)
msg.sender.transfer(withdrawAmount); // throws on failure
}
function setState(States _newState) internal {
state = _newState;
emit StateTransition(state, _newState);
}
}
|
new limit to be enforced for future deposits
|
function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl {
minDeposit = _newMinDeposit;
}
| 1,041,360
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on 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-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event TransferWithData(address indexed from, address indexed to, uint value, bytes data);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transfer(address _to, uint _value, bytes _data) external returns (bool) {
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
uint codeLength;
require(_value / 1000000000000000000 >= 1);
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _to);
}
emit TransferWithData(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) external returns (bool) {
uint codeLength;
bytes memory empty;
require(_value / 1000000000000000000 >= 1);
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, address(this));
}
emit Transfer(msg.sender, _to, _value);
emit TransferWithData(msg.sender, _to, _value, empty);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transferByCrowdSale(address _to, uint _value) external returns (bool) {
bytes memory empty;
require(_value / 1000000000000000000 >= 1);
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
emit TransferWithData(msg.sender, _to, _value, empty);
return true;
}
function _transferGasByOwner(address _from, address _to, uint256 _value) internal {
_balances[_from] = _balances[_from].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(_from, _to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* 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
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit TransferWithData(from, to, value, '');
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit TransferWithData(address(0), account, value, '');
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit TransferWithData(account, address(0), value, '');
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
function transferGasByOwner(address _from, address _to, uint256 _value) public onlyMinter returns (bool) {
super._transferGasByOwner(_from, _to, _value);
return true;
}
}
/**
* @title SimpleToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `ERC20` functions.
*/
contract CryptoMusEstate is ERC20Mintable {
string public constant name = "Mus#1";
string public constant symbol = "MUS#1";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
mint(msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title SimpleToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `ERC20` functions.
*/
contract CryptoMusKRW is ERC20Mintable {
string public constant name = "CryptoMus KRW Stable Token";
string public constant symbol = "KRWMus";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 10000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
mint(msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
_owner = msg.sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract ERC223ReceivingContract is Ownable {
using SafeMath for uint256;
// The token being sold
CryptoMusEstate private _token;
// The token being sold
CryptoMusKRW private _krwToken;
// Address where funds are collected
address private _wallet;
address private _krwTokenAddress;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param token Address of the token being sold
*/
constructor(uint256 rate, CryptoMusEstate token, CryptoMusKRW krwToken) public {
require(rate > 0);
require(token != address(0));
_rate = rate;
_wallet = msg.sender;
_token = token;
_krwToken = krwToken;
_krwTokenAddress = krwToken;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
function tokenFallback(address _from, uint _value, address _to) public {
if(_krwTokenAddress != _to) {
} else {
buyTokens(_from, _value);
}
}
/**
* @return the token being sold.
*/
function token() public view returns (CryptoMusEstate) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
function setRate(uint256 setRate) public onlyOwner returns (uint256)
{
_rate = setRate;
return _rate;
}
/**
* @return the mount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param beneficiary Address performing the token purchase
*/
function buyTokens(address beneficiary, uint _value) public {
uint256 weiAmount = _value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds(_value);
_postValidatePurchase(beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
_token.transferByCrowdSale(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address beneficiary,
uint256 weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(uint _value) internal {
_krwToken.transferByCrowdSale(_wallet, _value);
}
}
|
Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. beneficiary Address receiving the tokens tokenAmount Number of tokens to be purchased/
|
function _processPurchase(
address beneficiary,
uint256 tokenAmount
)
internal
{
_deliverTokens(beneficiary, tokenAmount);
}
| 5,531,281
|
./full_match/1/0x965737c66c68486b499ad726387f158514a69d15/sources/browser/PotatoMaster.sol
|
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 potatoReward = multiplier.mul(potatoPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accPotatoPerShare = pool.accPotatoPerShare.add(potatoReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
potato.mint(address(this), potatoReward.div(1e18));
}
| 8,319,607
|
pragma solidity ^0.4.24;
contract EthGods {
// imported contracts
EthGodsName private eth_gods_name;
function set_eth_gods_name_contract_address(address eth_gods_name_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_name = EthGodsName(eth_gods_name_contract_address);
return true;
}
EthGodsDice private eth_gods_dice;
function set_eth_gods_dice_contract_address(address eth_gods_dice_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_dice = EthGodsDice(eth_gods_dice_contract_address);
return true;
}
// end of imported contracts
// start of database
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private contact_email = "ethgods@gmail.com";
string private official_url = "swarm-gateways.net/bzz:/ethgods.eth";
address private admin; // public when testing
address private controller1 = 0xcA5A9Db0EF9a0Bf5C38Fc86fdE6CB897d9d86adD; // controller can change admin at once;
address private controller2 = 0x8396D94046a099113E5fe5CBad7eC95e96c2B796; // controller can change admin at once;
address private v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
uint private block_hash_duration = 255; // can't get block hash, after 256 blocks, adjustable
// god
struct god {
uint god_id;
uint level;
uint exp;
uint pet_type;// 12 animals or zodiacs
uint pet_level;
uint listed; // 0 not a god, 1 - ... rank_score in god list
uint invite_price;
uint blessing_player_id;
bool hosted_pray; // auto waitlist, when enlisted. others can invite, once hosted pray
uint bid_eth; // bid to host pray
uint credit; // gained from the amulet invitation spending of invited fellows
uint count_amulets_generated;
uint first_amulet_generated;
uint count_amulets_at_hand;
uint count_amulets_selling;
uint amulets_start_id;
uint amulets_end_id;
uint count_token_orders;
uint first_active_token_order;
uint allowed_block; // allow another account to use my egst
uint block_number; // for pray
bytes32 gene;
bool gene_created;
bytes32 pray_hash; //hash created for each pray
uint inviter_id; // who invited this fellow to this world
uint count_gods_invited; // gods invited to this game by this god.
}
uint private count_gods = 0; // Used when generating id for a new player,
mapping(address => god) private gods; // everyone is a god
mapping(uint => address) private gods_address; // gods' address => god_id
uint [] private listed_gods; // id of listed gods
uint private max_listed_gods = 10000; // adjustable
uint private initial_invite_price = 0.02 ether; // grows with each invitation for this god
uint private invite_price_increase = 0.02 ether; // grows by this amount with each invitation
uint private max_invite_price = 1000 ether; // adjustable
uint private max_extra_eth = 0.001 ether; // adjustable
uint private list_level = 10; // start from level 10
uint private max_gas_price = 100000000000; // 100 gwei for invite and pray, adjustable
// amulet
struct amulet {
uint god_id;
address owner;
uint level;
uint bound_start_block;// can't sell, if just got
// bool selling;
uint start_selling_block; // can't bind & use in pk, if selling
uint price; // set to 0, when withdraw from selling or bought
// uint order_id; // should be 0, if not selling
}
uint private count_amulets = 0;
mapping(uint => amulet) private amulets; // public when testing
uint private bound_duration = 9000; // once bought, wait a while before sell it again, adjustable
uint private order_duration = 20000; // valid for about 3 days, then not to show to public in selling amulets/token orders, but still show in my_selling amulets/token orders. adjustable
// pray
address private pray_host_god; // public when testing
bool private pray_reward_top100; // if hosted by new god, reward top 100 gods egst
uint private pray_start_block; // public when testing
bool private rewarded_pray_winners = false;
uint private count_hosted_gods; // gods hosted pray (event started). If less than bidding gods, there are new gods waiting to host pray,
mapping (uint => address) private bidding_gods; // every listed god and bid to host pray
uint private initializer_reward = 36; // reward the god who burned gas to send pray rewards to community, adjustable
mapping(uint => uint) private max_winners; // max winners for each prize
uint private min_pray_interval = 2000; // 2000, 36 in CBT, 2 in dev, adjustable
uint private min_pray_duration = 6000; // 6000, 600 in CBT, 60 in dev, adjustable
uint private max_pray_duration = 9000; // 9000, 900 in CBT, 90 in dev, adjustable
uint private count_waiting_prayers;
mapping (uint => address) private waiting_prayers; // uint is waiting sequence
uint private waiting_prayer_index = 1; // waiting sequence of the prayer ready to draw lot
mapping(uint => uint) private pk_positions; // public when testing
mapping(uint => uint) private count_listed_winners; // count for 5 prizes, public in testing
mapping (uint => mapping(uint => address)) private listed_winners; // winners for 5 prizes
bool private reEntrancyMutex = false; // for sendnig eth to msg.sender
uint private pray_egses = 0; // 10% from reward pool to top 3 winners in each round of pray events
uint private pray_egst = 0; // 10% from reward pool to 3rd & 4th prize winners in each round of pray events
mapping(address => uint) egses_balances;
// eth_gods_token (EGST)
string public name = "EthGodsToken";
string public symbol = "EGST";
uint8 public decimals = 18; //same as ethereum
uint private _totalSupply;
mapping(address => uint) balances; // bought or gained from pray or revenue share
mapping(address => mapping(address => uint)) allowed;
uint private allowed_use_CD = 20; // if used allowed amount, have to wait a while before approve new allowed amount again, prevent cheating, adjustable
struct token_order {
uint id;
uint start_selling_block;
address seller;
uint unit_price;
uint egst_amount;
}
uint private count_token_orders = 0;
mapping (uint => token_order) token_orders;
uint private first_active_token_order = 0;
uint private min_unit_price = 20; // 1 egst min value is 0.0002 ether, adjustable
uint private max_unit_price = 200; // 1 egst max value is 0.002 ether, adjustable
uint private max_egst_amount = 1000000 ether; // for create_token_order, adjustable
uint private min_egst_amount = 0.00001 ether; // for create_token_order, adjustable
//logs
uint private count_rounds = 0;
struct winner_log { // win a prize and if pk
uint god_block_number;
bytes32 block_hash;
address prayer;
address previous_winner;
uint prize;
bool pk_result;
}
mapping (uint => uint) private count_rounds_winner_logs;
mapping(uint => mapping(uint => winner_log)) private winner_logs;
struct change_log {
uint block_number;
uint asset_type; // 1 egst, 2 eth_surplus
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token,
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward
uint reason; // > 10 is buy token unit_price
uint change_amount;
uint after_amount;
address _from;
address _to;
}
mapping (uint => uint) private count_rounds_change_logs;
mapping(uint => mapping(uint => change_log)) private change_logs;
// end of database
// start of constructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
create_god(admin, 0);
create_god(v_god, 0);
gods[v_god].level = 10;
enlist_god(v_god);
max_winners[1] = 1; // 1
max_winners[2] = 2; // 2
max_winners[3] = 8; // 8
max_winners[4] = 16; // 16
max_winners[5] = 100; // 100
_totalSupply = 6000000 ether;
pray_egst = 1000 ether;
balances[admin] = sub(_totalSupply, pray_egst);
initialize_pray();
}
// destruct for testing contracts. can't destruct since round 3
function finalize() public {
require(msg.sender == admin && count_rounds <= 3);
selfdestruct(admin);
}
function () public payable {
revert ();
}
// end of constructor
//start of contract information & administration
function get_controller () public view returns (address, address){
require (msg.sender == admin || msg.sender == controller1 || msg.sender == controller2);
return (controller1, controller2);
}
function set_controller (uint controller_index, address new_controller_address) public returns (bool){
if (controller_index == 1){
require(msg.sender == controller2);
controller1 = new_controller_address;
} else {
require(msg.sender == controller1);
controller2 = new_controller_address;
}
return true;
}
function set_admin (address new_admin_address) public returns (bool) {
require (msg.sender == controller1 || msg.sender == controller2);
// admin don't have game attributes, such as level'
// no need to transfer egses and egst to new_admin_address
delete gods[admin];
admin = new_admin_address;
gods_address[0] = admin;
gods[admin].god_id = 0;
return true;
}
// update system parameters
function set_parameters (uint parameter_type, uint new_parameter) public returns (bool){
require (msg.sender == admin);
if (parameter_type == 1) {
max_pray_duration = new_parameter;
} else if (parameter_type == 2) {
min_pray_duration = new_parameter;
} else if (parameter_type == 3) {
block_hash_duration = new_parameter;
} else if (parameter_type == 4) {
min_pray_interval = new_parameter;
} else if (parameter_type == 5) {
order_duration = new_parameter;
} else if (parameter_type == 6) {
bound_duration = new_parameter;
} else if (parameter_type == 7) {
initializer_reward = new_parameter;
} else if (parameter_type == 8) {
allowed_use_CD = new_parameter;
} else if (parameter_type == 9) {
min_unit_price = new_parameter;
} else if (parameter_type == 10) {
max_unit_price = new_parameter;
} else if (parameter_type == 11) {
max_listed_gods = new_parameter;
} else if (parameter_type == 12) {
max_gas_price = new_parameter;
} else if (parameter_type == 13) {
max_invite_price = new_parameter;
} else if (parameter_type == 14) {
min_egst_amount = new_parameter;
} else if (parameter_type == 15) {
max_egst_amount = new_parameter;
} else if (parameter_type == 16) {
max_extra_eth = new_parameter;
}
return true;
}
function set_strings (uint string_type, string new_string) public returns (bool){
require (msg.sender == admin);
if (string_type == 1){
official_url = new_string;
} else if (string_type == 2){
name = new_string; // egst name
} else if (string_type == 3){
symbol = new_string; // egst symbol
}
return true;
}
// for basic information to show to players, and to update parameter in sub-contracts
function query_contract () public view returns(uint, uint, address, uint, string, uint, uint){
return (count_gods,
listed_gods.length,
admin,
block_hash_duration,
official_url,
bound_duration,
min_pray_interval
);
}
function query_uints () public view returns (uint[7] uints){
uints[0] = max_invite_price;
uints[1] = list_level;
uints[2] = max_pray_duration;
uints[3] = min_pray_duration;
uints[4] = initializer_reward;
uints[5] = min_unit_price;
uints[6] = max_unit_price;
return uints;
}
function query_uints2 () public view returns (uint[6] uints){
uints[0] = allowed_use_CD;
uints[1] = max_listed_gods;
uints[2] = max_gas_price;
uints[3] = min_egst_amount;
uints[4] = max_egst_amount;
uints[5] = max_extra_eth;
return uints;
}
//end of contract information & administration
// god related functions: register, create_god, upgrade_pet, add_exp, burn_gas, invite, enlist
// if a new player comes when a round just completed, the new player may not want to initialize the next round
function register_god (uint inviter_id) public returns (uint) {
return create_god(msg.sender, inviter_id);
}
function create_god (address god_address, uint inviter_id) private returns(uint god_id){ // created by the contract // public when testing
// check if the god is already created
if (gods[god_address].credit == 0) { // create admin as god[0]
gods[god_address].credit = 1; // give 1 credit, so we know this address has a god
god_id = count_gods; // 1st god's id is admin 0
count_gods = add(count_gods, 1) ;
gods_address[god_id] = god_address;
gods[god_address].god_id = god_id;
if (god_id > 0){ // not admin
add_exp(god_address, 100);
set_inviter(inviter_id);
}
return god_id;
}
}
function set_inviter (uint inviter_id) public returns (bool){
if (inviter_id > 0 && gods_address[inviter_id] != address(0)
&& gods[msg.sender].inviter_id == 0
&& gods[gods_address[inviter_id]].inviter_id != gods[msg.sender].god_id){
gods[msg.sender].inviter_id = inviter_id;
address inviter_address = gods_address[inviter_id];
gods[inviter_address].count_gods_invited = add(gods[inviter_address].count_gods_invited, 1);
return true;
}
}
function add_exp (address god_address, uint exp_up) private returns(uint new_level, uint new_exp) { // public when testing
if (god_address == admin){
return (0,0);
}
if (gods[god_address].god_id == 0){
uint inviter_id = gods[god_address].inviter_id;
create_god(god_address, inviter_id);
}
new_exp = add(gods[god_address].exp, exp_up);
uint current_god_level = gods[god_address].level;
uint level_up_exp;
new_level = current_god_level;
for (uint i=0;i<10;i++){ // if still have extra exp, level up next time
if (current_god_level < 99){
level_up_exp = mul(10, add(new_level, 1));
} else {
level_up_exp = 1000;
}
if (new_exp >= level_up_exp){
new_exp = sub(new_exp, level_up_exp);
new_level = add(new_level, 1);
} else {
break;
}
}
gods[god_address].exp = new_exp;
if(new_level > current_god_level) {
gods[god_address].level = new_level;
if (gods[god_address].listed > 0) {
if (listed_gods.length > 1) {
sort_gods(gods[god_address].god_id);
}
} else if (new_level >= list_level && listed_gods.length < max_listed_gods) {
enlist_god(god_address);
}
}
return (new_level, new_exp);
}
function enlist_god (address god_address) private returns (uint) { // public when testing
require(gods[god_address].level >= list_level && god_address != admin);
// if the god is not listed yet, enlist and add level requirement for the next enlist
if (gods[god_address].listed == 0) {
uint god_id = gods[god_address].god_id;
if (god_id == 0){
god_id = create_god(god_address, 0); // get a god_id and set inviter as v god
}
gods[god_address].listed = listed_gods.push(god_id); // start from 1, 0 is not listed
gods[god_address].invite_price = initial_invite_price;
list_level = add(list_level, 1);
bidding_gods[listed_gods.length] = god_address;
}
return list_level;
}
function sort_gods_admin(uint god_id) public returns (bool){
require (msg.sender == admin);
sort_gods(god_id);
return true;
}
// when a listed god level up and is not top 1 of the list, compare power with higher god, if higher than the higher god, swap position
function sort_gods (uint god_id) private returns (uint){
require (god_id > 0);
uint list_length = listed_gods.length;
if (list_length > 1) {
address god_address = gods_address[god_id];
uint this_god_listed = gods[god_address].listed;
if (this_god_listed < list_length) {
uint higher_god_listed = add(this_god_listed, 1);
uint higher_god_id = listed_gods[sub(higher_god_listed, 1)];
address higher_god = gods_address[higher_god_id];
if(gods[god_address].level > gods[higher_god].level
|| (gods[god_address].level == gods[higher_god].level
&& gods[god_address].exp > gods[higher_god].exp)){
listed_gods[sub(this_god_listed, 1)] = higher_god_id;
listed_gods[sub(higher_god_listed, 1)] = god_id;
gods[higher_god].listed = this_god_listed;
gods[god_address].listed = higher_god_listed;
}
}
}
return gods[god_address].listed;
}
function burn_gas (uint god_id) public returns (uint god_new_level, uint god_new_exp) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].listed > 0);
add_exp(god_address, 1);
add_exp(msg.sender, 1);
return (gods[god_address].level, gods[god_address].exp); // return bool, if out of gas
}
function invite (uint god_id) public payable returns (uint new_invite_price) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].hosted_pray == true
&& tx.gasprice <= max_gas_price
);
uint invite_price = gods[god_address].invite_price;
require(msg.value >= invite_price);
if (gods[god_address].invite_price < max_invite_price) {
gods[god_address].invite_price = add(invite_price, invite_price_increase);
}
uint exp_up = div(invite_price, (10 ** 15)); // 1000 exp for each eth
add_exp(god_address, exp_up);
add_exp(msg.sender, exp_up);
//generate a new amulet of this god for the inviter
count_amulets ++;
amulets[count_amulets].god_id = god_id;
amulets[count_amulets].owner = msg.sender;
gods[god_address].count_amulets_generated = add(gods[god_address].count_amulets_generated, 1);
if (gods[god_address].count_amulets_generated == 1){
gods[god_address].first_amulet_generated = count_amulets;
}
gods[msg.sender].count_amulets_at_hand = add(gods[msg.sender].count_amulets_at_hand, 1);
update_amulets_count(msg.sender, count_amulets, true);
// invite_price to egses: 60% to pray_egses, 20% to god, changed
// pray_egses = add(pray_egses, div(mul(60, invite_price), 100));
// egses_from_contract(gods_address[god_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited
// reduce reward pool share from 60 to 50%, reduce god reward from 20% to 10%
// add 20% share to blessing player (the last player invited this god)
pray_egses = add(pray_egses, div(mul(50, invite_price), 100));
egses_from_contract(god_address, div(mul(10, invite_price), 100), 2); //2 reward god for being invited
egses_from_contract(gods_address[gods[god_address].blessing_player_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited, no need to check if blessing player id is > 0
gods[god_address].blessing_player_id = gods[msg.sender].god_id;
reward_inviter(msg.sender, invite_price);
emit invited_god (msg.sender, god_id);
return gods[god_address].invite_price;
}
event invited_god (address msg_sender, uint god_id);
function reward_inviter (address inviter_address, uint invite_price) private returns (bool){
// the fellow spending eth also get credit and share
uint previous_share = 0;
uint inviter_share = 0;
uint share_diff;
// uint invite_credit = div(invite_price, 10 ** 15);
for (uint i = 0; i < 9; i++){ // max trace 9 layers of inviter
if (inviter_address != address(0) && inviter_address != admin){ // admin doesn't get reward or credit
share_diff = 0;
// gods[inviter_address].credit = add(gods[inviter_address].credit, invite_credit);
gods[inviter_address].credit = add(gods[inviter_address].credit, invite_price);
inviter_share = get_vip_level(inviter_address);
if (inviter_share > previous_share) {
share_diff = sub(inviter_share, previous_share);
if (share_diff > 18) {
share_diff = 18;
}
previous_share = inviter_share;
}
if (share_diff > 0) {
egses_from_contract(inviter_address, div(mul(share_diff, invite_price), 100), 3); // 3 inviter_reward
}
inviter_address = gods_address[gods[inviter_address].inviter_id]; // get the address of inviter's inviter'
} else{
break;
}
}
// invite_price to egses: sub(20%, previous_share) to admin
share_diff = sub(20, inviter_share);
egses_from_contract(admin, div(mul(share_diff, invite_price), 100), 2); // remaining goes to admin, 2 god_reward for being invited
return true;
}
function upgrade_pet () public returns(bool){
//use egst to level up pet;
uint egst_cost = mul(add(gods[msg.sender].pet_level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 6);// 6 upgrade_pet
gods[msg.sender].pet_level = add(gods[msg.sender].pet_level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
emit upgradeAmulet(msg.sender, 0, gods[msg.sender].pet_level);
return true;
}
event upgradeAmulet (address owner, uint amulet_id, uint new_level);
function set_pet_type (uint new_type) public returns (bool){
if (gods[msg.sender].pet_type != new_type) {
gods[msg.sender].pet_type = new_type;
return true;
}
}
function get_vip_level (address god_address) public view returns (uint vip_level){
uint inviter_credit = gods[god_address].credit;
if (inviter_credit > 500 ether){
vip_level = 18;
} else if (inviter_credit > 200 ether){
vip_level = 15;
} else if (inviter_credit > 100 ether){
vip_level = 12;
} else if (inviter_credit > 50 ether){
vip_level = 10;
} else if (inviter_credit > 20 ether){
vip_level = 8;
} else if (inviter_credit > 10 ether){
vip_level = 6;
} else if (inviter_credit > 5 ether){
vip_level = 5;
} else if (inviter_credit > 2 ether){
vip_level = 4;
} else if (inviter_credit > 1 ether){
vip_level = 3;
} else if (inviter_credit > 0.5 ether){
vip_level = 2;
} else {
vip_level = 1;
}
return vip_level;
}
// view god's information
function get_god_id (address god_address) public view returns (uint god_id){
return gods[god_address].god_id;
}
function get_god_address(uint god_id) public view returns (address){
return gods_address[god_id];
}
function get_god (uint god_id) public view returns(uint, string, uint, uint, uint, uint, uint) {
address god_address = gods_address[god_id];
string memory god_name;
god_name = eth_gods_name.get_god_name(god_address);
if (bytes(god_name).length == 0){
god_name = "Unknown";
}
return (gods[god_address].god_id,
god_name,
gods[god_address].level,
gods[god_address].exp,
gods[god_address].invite_price,
gods[god_address].listed,
gods[god_address].blessing_player_id
);
}
function get_god_info (address god_address) public view returns (uint, bytes32, bool, uint, uint, uint, bytes32){
return (gods[god_address].block_number,
gods[god_address].gene,
gods[god_address].gene_created,
gods[god_address].pet_type,
gods[god_address].pet_level,
gods[god_address].bid_eth,
gods[god_address].pray_hash
);
}
function get_god_hosted_pray (uint god_id) public view returns (bool){
return gods[gods_address[god_id]].hosted_pray;
}
function get_my_info () public view returns(uint, uint, uint, uint, uint, uint, uint) { //private information
return (gods[msg.sender].god_id,
egses_balances[msg.sender], //egses
balances[msg.sender], //egst
get_vip_level(msg.sender),
gods[msg.sender].credit, // inviter_credit
gods[msg.sender].inviter_id,
gods[msg.sender].count_gods_invited
);
}
function get_listed_gods (uint page_number) public view returns (uint[]){
uint count_listed_gods = listed_gods.length;
require(count_listed_gods <= mul(page_number, 20));
uint[] memory tempArray = new uint[] (20);
if (page_number < 1) {
page_number = 1;
}
for (uint i = 0; i < 20; i++){
if(count_listed_gods > add(i, mul(20, sub(page_number, 1)))) {
tempArray[i] = listed_gods[sub(sub(sub(count_listed_gods, i), 1), mul(20, sub(page_number, 1)))];
} else {
break;
}
}
return tempArray;
}
// amulets
function upgrade_amulet (uint amulet_id) public returns(uint){
require(amulets[amulet_id].owner == msg.sender);
uint egst_cost = mul(add(amulets[amulet_id].level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 7);// reason 7, upgrade_amulet
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
amulets[amulet_id].level = add(amulets[amulet_id].level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
emit upgradeAmulet(msg.sender, amulet_id, amulets[amulet_id].level);
return amulets[amulet_id].level;
}
function create_amulet_order (uint amulet_id, uint price) public returns (uint) {
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block == 0
&& add(amulets[amulet_id].bound_start_block, bound_duration) < block.number
&& price > 0);
amulets[amulet_id].start_selling_block = block.number;
amulets[amulet_id].price = price;
gods[msg.sender].count_amulets_at_hand = sub(gods[msg.sender].count_amulets_at_hand, 1);
gods[msg.sender].count_amulets_selling = add(gods[msg.sender].count_amulets_selling, 1);
return gods[msg.sender].count_amulets_selling;
}
function buy_amulet (uint amulet_id) public payable returns (bool) {
uint price = amulets[amulet_id].price;
require(msg.value >= price && msg.value < add(price, max_extra_eth)
&& amulets[amulet_id].start_selling_block > 0
&& amulets[amulet_id].owner != msg.sender
&& price > 0);
address seller = amulets[amulet_id].owner;
amulets[amulet_id].owner = msg.sender;
amulets[amulet_id].bound_start_block = block.number;
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
update_amulets_count(msg.sender, amulet_id, true);
gods[seller].count_amulets_selling--;
update_amulets_count(seller, amulet_id, false);
egses_from_contract(seller, price, 6); // 6 sell amulet
return true;
}
function withdraw_amulet_order (uint amulet_id) public returns (uint){
// an amulet can only have one order_id, so withdraw amulet_id instead of withdraw order_id, since only amulet_id is shown in amulets_at_hand
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block > 0);
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
gods[msg.sender].count_amulets_selling--;
return gods[msg.sender].count_amulets_selling;
}
function update_amulets_count (address god_address, uint amulet_id, bool obtained) private returns (uint){
if (obtained == true){
if (amulet_id < gods[god_address].amulets_start_id) {
gods[god_address].amulets_start_id = amulet_id;
}
} else {
if (amulet_id == gods[god_address].amulets_start_id){
for (uint i = amulet_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && i > amulet_id){
gods[god_address].amulets_start_id = i;
break;
}
}
}
}
return gods[god_address].amulets_start_id;
}
function get_amulets_generated (uint god_id) public view returns (uint[]) {
address god_address = gods_address[god_id];
uint count_amulets_generated = gods[god_address].count_amulets_generated;
uint [] memory temp_list = new uint[](count_amulets_generated);
uint count_elements = 0;
for (uint i = gods[god_address].first_amulet_generated; i <= count_amulets; i++){
if (amulets[i].god_id == god_id){
temp_list [count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_generated){
break;
}
}
}
return temp_list;
}
function get_amulets_at_hand (address god_address) public view returns (uint[]) {
uint count_amulets_at_hand = gods[god_address].count_amulets_at_hand;
uint [] memory temp_list = new uint[] (count_amulets_at_hand);
uint count_elements = 0;
for (uint i = gods[god_address].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_at_hand){
break;
}
}
}
return temp_list;
}
function get_my_amulets_selling () public view returns (uint[]){
uint count_amulets_selling = gods[msg.sender].count_amulets_selling;
uint [] memory temp_list = new uint[] (count_amulets_selling);
uint count_elements = 0;
for (uint i = gods[msg.sender].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == msg.sender
&& amulets[i].start_selling_block > 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_selling){
break;
}
}
}
return temp_list;
}
// to calculate how many pages
function get_amulet_orders_overview () public view returns(uint){
uint count_amulets_selling = 0;
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
return count_amulets_selling; // to show page numbers when getting amulet_orders
}
function get_amulet_orders (uint page_number) public view returns (uint[]){
uint[] memory temp_list = new uint[] (20);
uint count_amulets_selling = 0;
uint count_list_elements = 0;
if ((page_number < 1)
|| count_amulets <= 20) {
page_number = 1; // chose a page out of range
}
uint start_amulets_count = mul(sub(page_number, 1), 20);
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
if (count_amulets_selling <= start_amulets_count) {
count_amulets_selling ++;
}
if (count_amulets_selling > start_amulets_count){
temp_list[count_list_elements] = i;
count_list_elements ++;
if (count_list_elements >= 20){
break;
}
}
}
}
return temp_list;
}
function get_amulet (uint amulet_id) public view returns(address, string, uint, uint, uint, uint, uint){
uint god_id = amulets[amulet_id].god_id;
// address god_address = gods_address[god_id];
string memory god_name = eth_gods_name.get_god_name(gods_address[god_id]);
uint god_level = gods[gods_address[god_id]].level;
uint amulet_level = amulets[amulet_id].level;
uint start_selling_block = amulets[amulet_id].start_selling_block;
uint price = amulets[amulet_id].price;
return(amulets[amulet_id].owner,
god_name,
god_id,
god_level,
amulet_level,
start_selling_block,
price
);
}
function get_amulet2 (uint amulet_id) public view returns(uint){
return amulets[amulet_id].bound_start_block;
}
// end of amulet
// start of pray
function admin_deposit (uint egst_amount) public payable returns (bool) {
require (msg.sender == admin);
if (msg.value > 0){
pray_egses = add(pray_egses, msg.value);
egses_from_contract(admin, msg.value, 4); // 4 admin_deposit to reward_pool
}
if (egst_amount > 0){
pray_egst = add(pray_egst, egst_amount);
egst_to_contract(admin, egst_amount, 4); // 4 admin_deposit to reward_pool
}
return true;
}
function initialize_pray () private returns (bool){
if (pray_start_block > 0) {
require (check_event_completed() == true
&& rewarded_pray_winners == true);
}
count_rounds = add(count_rounds, 1);
count_rounds_winner_logs[count_rounds] = 0;
pray_start_block = block.number;
rewarded_pray_winners = false;
for (uint i = 1; i <= 5; i++){
pk_positions[i] = max_winners[i]; // pk start from the last slot
count_listed_winners[i] = 0;
}
if (listed_gods.length > count_hosted_gods) {
// a new god's turn
count_hosted_gods = add(count_hosted_gods, 1);
pray_host_god = bidding_gods[count_hosted_gods];
gods[pray_host_god].hosted_pray = true;
pray_reward_top100 = true;
} else {
//choose highest bidder
(uint highest_bid, address highest_bidder) = compare_bid_eth();
gods[highest_bidder].bid_eth = 0;
pray_host_god = highest_bidder;
pray_egses = add(pray_egses, highest_bid);
pray_reward_top100 = false;
}
return true;
}
function bid_host () public payable returns (bool) {
require (msg.value > 0 && gods[msg.sender].listed > 0);
gods[msg.sender].bid_eth = add (gods[msg.sender].bid_eth, msg.value);
return true;
}
function withdraw_bid () public returns (bool) {
require(gods[msg.sender].bid_eth > 0);
gods[msg.sender].bid_eth = 0;
egses_from_contract(msg.sender, gods[msg.sender].bid_eth, 8); // 8 withdraw bid
return true;
}
// if browser web3 didn't get god's credit, use pray_create in the pray button to create god_id first
function pray_create (uint inviter_id) public returns (bool) {
// when create a new god, set credit as 1, so credit <= 0 means god_id not created yet
create_god(msg.sender, inviter_id);
pray();
}
// if browser web3 got god's credit, use pray in the pray button
function pray () public returns (bool){
require (add(gods[msg.sender].block_number, min_pray_interval) < block.number
&& tx.gasprice <= max_gas_price
&& check_event_completed() == false);
if (waiting_prayer_index <= count_waiting_prayers) {
address waiting_prayer = waiting_prayers[waiting_prayer_index];
uint god_block_number = gods[waiting_prayer].block_number;
bytes32 block_hash;
if ((add(god_block_number, 1)) < block.number) {// can only get previous block hash
if (add(god_block_number, block_hash_duration) < block.number) {// make sure this god has a valid block_number to generate block hash
gods[waiting_prayer].block_number = block.number; // refresh this god's expired block_id
// delete waiting_prayers[waiting_prayer_index];
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = waiting_prayer;
} else {// draw lottery and/or create gene for the waiting prayer
block_hash = keccak256(abi.encodePacked(blockhash(add(god_block_number, 1))));
if(gods[waiting_prayer].gene_created == false){
gods[waiting_prayer].gene = block_hash;
gods[waiting_prayer].gene_created = true;
}
gods[waiting_prayer].pray_hash = block_hash;
uint dice_result = eth_gods_dice.throw_dice (block_hash)[0];
if (dice_result >= 1 && dice_result <= 5){
set_winner(dice_result, waiting_prayer, block_hash, god_block_number);
}
}
waiting_prayer_index = add(waiting_prayer_index, 1);
}
}
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = msg.sender;
gods[msg.sender].block_number = block.number;
add_exp(msg.sender, 1);
add_exp(pray_host_god, 1);
return true;
}
function set_winner (uint prize, address waiting_prayer, bytes32 block_hash, uint god_block_number) private returns (uint){
count_rounds_winner_logs[count_rounds] = add(count_rounds_winner_logs[count_rounds], 1);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].god_block_number = god_block_number;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].block_hash = block_hash;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prayer = waiting_prayer;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prize = prize;
if (count_listed_winners[prize] >= max_winners[prize]){ // winner_list maxed, so the new prayer challenge previous winners
uint pk_position = pk_positions[prize];
address previous_winner = listed_winners[prize][pk_position];
bool pk_result = pk(waiting_prayer, previous_winner, block_hash);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].pk_result = pk_result;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].previous_winner = previous_winner;
if (pk_result == true) {
listed_winners[prize][pk_position] = waiting_prayer; // attacker defeat defender
}
if (prize > 1) { // no need to change pk_pos for champion
if (pk_positions[prize] > 1){
pk_positions[prize] = sub(pk_positions[prize], 1);
} else {
pk_positions[prize] = max_winners[prize];
}
}
} else {
count_listed_winners[prize] = add(count_listed_winners[prize], 1);
listed_winners[prize][count_listed_winners[prize]] = waiting_prayer;
}
return count_listed_winners[prize];
}
function reward_pray_winners () public returns (bool){
require (check_event_completed() == true);
uint this_reward_egses;
uint reward_pool_egses = div(pray_egses, 10);
pray_egses = sub(pray_egses, reward_pool_egses);
uint this_reward_egst;
uint reward_pool_egst = div(pray_egst, 10);
pray_egst = sub(pray_egst, reward_pool_egst); // reduce sum for less calculation
egst_from_contract(pray_host_god, mul(div(reward_pool_egst, 100), 60), 1); // 1 pray_reward for hosting event
for (uint i = 1; i<=5; i++){
this_reward_egses = 0;
this_reward_egst = 0;
if (i == 1) {
this_reward_egses = mul(div(reward_pool_egses, 100), 60);
} else if (i == 2){
this_reward_egses = mul(div(reward_pool_egses, 100), 20);
} else if (i == 3){
this_reward_egst = mul(div(reward_pool_egst, 100), 3);
} else if (i == 4){
this_reward_egst = div(reward_pool_egst, 100);
}
for (uint reward_i = 1; reward_i <= count_listed_winners[i]; reward_i++){
address rewarding_winner = listed_winners[i][reward_i];
if (this_reward_egses > 0 ) {
egses_from_contract(rewarding_winner, this_reward_egses, 1); // 1 pray_reward
} else if (this_reward_egst > 0) {
egst_from_contract(rewarding_winner, this_reward_egst, 1); // 1 pray_reward
}
add_exp(rewarding_winner, 6);
}
}
if(pray_reward_top100 == true) {
reward_top_gods();
}
// a small gift of exp & egst to the god who burned gas to send rewards to the community
egst_from_contract(msg.sender, mul(initializer_reward, 1 ether), 1); // 1 pray_reward
_totalSupply = add(_totalSupply, mul(initializer_reward, 1 ether));
add_exp(msg.sender, initializer_reward);
rewarded_pray_winners = true;
initialize_pray();
return true;
}
// more listed gods, more reward to the top gods, highest reward 600 egst
function reward_top_gods () private returns (bool){ // public when testing
uint count_listed_gods = listed_gods.length;
uint last_god_index;
if (count_listed_gods > 100) {
last_god_index = sub(count_listed_gods, 100);
} else {
last_god_index = 0;
}
uint reward_egst = 0;
uint base_reward = 6 ether;
if (count_rounds == 6){
base_reward = mul(base_reward, 6);
}
for (uint i = last_god_index; i < count_listed_gods; i++) {
reward_egst = mul(base_reward, sub(add(i, 1), last_god_index));
egst_from_contract(gods_address[listed_gods[i]], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
if (gods[gods_address[listed_gods[i]]].blessing_player_id > 0){
egst_from_contract(gods_address[gods[gods_address[listed_gods[i]]].blessing_player_id], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
}
}
return true;
}
function compare_bid_eth () private view returns (uint, address) {
uint highest_bid = 0;
address highest_bidder = v_god; // if no one bid, v god host this event
for (uint j = 1; j <= listed_gods.length; j++){
if (gods[bidding_gods[j]].bid_eth > highest_bid){
highest_bid = gods[bidding_gods[j]].bid_eth;
highest_bidder = bidding_gods[j];
}
}
return (highest_bid, highest_bidder);
}
function check_event_completed () public view returns (bool){
// check min and max pray_event duration
if (add(pray_start_block, max_pray_duration) > block.number){
if (add(pray_start_block, min_pray_duration) < block.number){
for (uint i = 1; i <= 5; i++){
if(count_listed_winners[i] < max_winners[i]){
return false;
}
}
return true;
} else {
return false;
}
} else {
return true;
}
}
function pk (address attacker, address defender, bytes32 block_hash) public view returns (bool pk_result){// make it public, view only, other contract may use it
(uint attacker_sum_god_levels, uint attacker_sum_amulet_levels) = get_sum_levels_pk(attacker);
(uint defender_sum_god_levels, uint defender_sum_amulet_levels) = get_sum_levels_pk(defender);
pk_result = eth_gods_dice.pk(block_hash, attacker_sum_god_levels, attacker_sum_amulet_levels, defender_sum_god_levels, defender_sum_amulet_levels);
return pk_result;
}
function get_sum_levels_pk (address god_address) public view returns (uint sum_gods_level, uint sum_amulets_level){
sum_gods_level = gods[god_address].level;
sum_amulets_level = gods[god_address].pet_level; // add pet level to the sum
uint amulet_god_id;
uint amulet_god_level;
for (uint i = 1; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
amulet_god_id = amulets[i].god_id;
amulet_god_level = gods[gods_address[amulet_god_id]].level;
sum_gods_level = add(sum_gods_level, amulet_god_level);
sum_amulets_level = add(sum_amulets_level, amulets[i].level);
}
}
return (sum_gods_level, sum_amulets_level);
}
//admin need this function
function get_listed_winners (uint prize) public view returns (address[]){
address [] memory temp_list = new address[] (count_listed_winners[prize]);
for (uint i = 0; i < count_listed_winners[prize]; i++){
temp_list[i] = listed_winners[prize][add(i,1)];
}
return temp_list;
}
function query_pray () public view returns (uint, uint, uint, address, address, uint, bool){
(uint highest_bid, address highest_bidder) = compare_bid_eth();
return (highest_bid,
pray_egses,
pray_egst,
pray_host_god,
highest_bidder,
count_rounds,
pray_reward_top100);
}
// end of pray
// start of egses
function egses_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
if (reason == 1) {
require (pray_egses > tokens);
pray_egses = sub(pray_egses, tokens);
}
egses_balances[to] = add(egses_balances[to], tokens);
create_change_log(1, reason, tokens, egses_balances[to], contract_address, to);
return true;
}
function egses_withdraw () public returns (uint tokens){
tokens = egses_balances[msg.sender];
require (tokens > 0 && contract_address.balance >= tokens && reEntrancyMutex == false);
reEntrancyMutex = true; // if met problem, it will use up gas from msg.sender and roll back to false
egses_balances[msg.sender] = 0;
msg.sender.transfer(tokens);
reEntrancyMutex = false;
emit withdraw_egses(msg.sender, tokens);
create_change_log(1, 5, tokens, 0, contract_address, msg.sender); // 5 withdraw egses
return tokens;
}
event withdraw_egses (address receiver, uint tokens);
// end of egses
// start of erc20 for egst
function totalSupply () public view returns (uint){
return _totalSupply;
}
function balanceOf (address tokenOwner) public view returns (uint){
return balances[tokenOwner]; // will return 0 if doesn't exist
}
function allowance (address tokenOwner, address spender) public view returns (uint) {
return allowed[tokenOwner][spender];
}
function transfer (address to, uint tokens) public returns (bool success){
require (balances[msg.sender] >= tokens);
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
create_change_log(2, 9, tokens, balances[to], msg.sender, to);
return true;
}
event Transfer (address indexed from, address indexed to, uint tokens);
function approve (address spender, uint tokens) public returns (bool success) {
// if allowed amount used and owner tries to reset allowed amount within a short time,
// the allowed account might be cheating the owner
require (balances[msg.sender] >= tokens);
if (tokens > 0){
require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number);
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
event Approval (address indexed tokenOwner, address indexed spender, uint tokens);
function transferFrom (address from, address to, uint tokens) public returns (bool success) {
require (balances[from] >= tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[from] = sub(balances[from], tokens);
balances[to] = add(balances[to], tokens);
gods[from].allowed_block = block.number;
emit Transfer(from, to, tokens);
create_change_log(2, 10, tokens, balances[to], from, to);
return true;
}
// end of erc20 for egst
// egst
function egst_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
balances[to] = add(balances[to], tokens);
create_change_log(2, reason, tokens, balances[to], contract_address, to);
return true;
}
function egst_to_contract (address from, uint tokens, uint reason) private returns (bool) { // public when testing
require (balances[from] >= tokens);
balances[from] = sub(balances[from], tokens);
emit spend_egst(from, tokens, reason);
create_change_log(2, reason, tokens, balances[from], from, contract_address);
return true;
}
event spend_egst (address from, uint tokens, uint reason);
function create_token_order (uint unit_price, uint egst_amount) public returns (uint) {
require(unit_price >= min_unit_price && unit_price <= max_unit_price
&& balances[msg.sender] >= egst_amount
&& egst_amount <= max_egst_amount
&& egst_amount >= min_egst_amount);
count_token_orders = add(count_token_orders, 1);
egst_to_contract(msg.sender, egst_amount, 3); // 3 create_token_order
token_orders[count_token_orders].start_selling_block = block.number;
token_orders[count_token_orders].seller = msg.sender;
token_orders[count_token_orders].unit_price = unit_price;
token_orders[count_token_orders].egst_amount = egst_amount;
gods[msg.sender].count_token_orders++;
update_first_active_token_order(msg.sender);
return gods[msg.sender].count_token_orders++;
}
function withdraw_token_order (uint order_id) public returns (bool) {
require (msg.sender == token_orders[order_id].seller
&& token_orders[order_id].egst_amount > 0);
uint egst_amount = token_orders[order_id].egst_amount;
token_orders[order_id].start_selling_block = 0;
token_orders[order_id].egst_amount = 0;
// balances[msg.sender] = add(balances[msg.sender], tokens);
egst_from_contract(msg.sender, egst_amount, 4); // 4 withdraw token_order
gods[msg.sender].count_token_orders = sub(gods[msg.sender].count_token_orders, 1);
update_first_active_token_order(msg.sender);
emit WithdrawTokenOrder(msg.sender, order_id);
return true;
}
event WithdrawTokenOrder (address seller, uint order_id);
function buy_token (uint order_id, uint egst_amount) public payable returns (uint) {
require(order_id >= first_active_token_order
&& order_id <= count_token_orders
&& egst_amount <= token_orders[order_id].egst_amount
&& token_orders[order_id].egst_amount > 0);
// unit_price 100 means 1 egst = 0.001 ether
uint eth_cost = div(mul(token_orders[order_id].unit_price, egst_amount), 100000);
require(msg.value >= eth_cost && msg.value < add(eth_cost, max_extra_eth) );
token_orders[order_id].egst_amount = sub(token_orders[order_id].egst_amount, egst_amount);
egst_from_contract(msg.sender, egst_amount, token_orders[order_id].unit_price); // uint price (> 10) will be recorded as reason in change log and translated by front end as buy token & unit_price
// balances[msg.sender] = add(balances[msg.sender], egst_amount);
address seller = token_orders[order_id].seller;
egses_from_contract(seller, eth_cost, 7); // 7 sell egst
if (token_orders[order_id].egst_amount <= 0){
token_orders[order_id].start_selling_block = 0;
gods[seller].count_token_orders = sub(gods[seller].count_token_orders, 1);
update_first_active_token_order(seller);
}
emit BuyToken(msg.sender, order_id, egst_amount);
return token_orders[order_id].egst_amount;
}
event BuyToken (address buyer, uint order_id, uint egst_amount);
function update_first_active_token_order (address god_address) private returns (uint, uint){ // public when testing
if (count_token_orders > 0
&& first_active_token_order == 0){
first_active_token_order = 1;
} else {
for (uint i = first_active_token_order; i <= count_token_orders; i++) {
if (add(token_orders[i].start_selling_block, order_duration) > block.number){
// find the first active order and compare with the currect index
if (i > first_active_token_order){
first_active_token_order = i;
}
break;
}
}
}
if (gods[god_address].count_token_orders > 0
&& gods[god_address].first_active_token_order == 0){
gods[god_address].first_active_token_order = 1; // may not be 1, but it will correct next time
} else {
for (uint j = gods[god_address].first_active_token_order; j < count_token_orders; j++){
if (token_orders[j].seller == god_address
&& token_orders[j].start_selling_block > 0){ // don't check duration, show it to selling, even if expired
// find the first active order and compare with the currect index
if(j > gods[god_address].first_active_token_order){
gods[god_address].first_active_token_order = j;
}
break;
}
}
}
return (first_active_token_order, gods[msg.sender].first_active_token_order);
}
function get_token_order (uint order_id) public view returns(uint, address, uint, uint){
require(order_id >= 1 && order_id <= count_token_orders);
return(token_orders[order_id].start_selling_block,
token_orders[order_id].seller,
token_orders[order_id].unit_price,
token_orders[order_id].egst_amount);
}
// return total orders and lowest price to browser, browser query each active order and show at most three orders of lowest price
function get_token_orders () public view returns(uint, uint, uint, uint, uint) {
uint lowest_price = max_unit_price;
for (uint i = first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].unit_price < lowest_price
&& token_orders[i].egst_amount > 0
&& add(token_orders[i].start_selling_block, order_duration) > block.number){
lowest_price = token_orders[i].unit_price;
}
}
return (count_token_orders, first_active_token_order, order_duration, max_unit_price, lowest_price);
}
function get_my_token_orders () public view returns(uint []) {
uint my_count_token_orders = gods[msg.sender].count_token_orders;
uint [] memory temp_list = new uint[] (my_count_token_orders);
uint count_list_elements = 0;
for (uint i = gods[msg.sender].first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].seller == msg.sender
&& token_orders[i].start_selling_block > 0){
temp_list[count_list_elements] = i;
count_list_elements++;
if (count_list_elements >= my_count_token_orders){
break;
}
}
}
return temp_list;
}
// end of egst
// logs
function get_winner_log (uint pray_round, uint log_id) public view returns (uint, bytes32, address, address, uint, bool){
require(log_id >= 1 && log_id <= count_rounds_winner_logs[pray_round]);
winner_log storage this_winner_log = winner_logs[pray_round][log_id];
return (this_winner_log.god_block_number,
this_winner_log.block_hash,
this_winner_log.prayer,
this_winner_log.previous_winner,
this_winner_log.prize,
this_winner_log.pk_result);
}
function get_count_rounds_winner_logs (uint pray_round) public view returns (uint){
return count_rounds_winner_logs[pray_round];
}
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token (> 10),
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward,
// 9 transfer, 10 transferFrom(owner & receiver)
function create_change_log (uint asset_type, uint reason, uint change_amount, uint after_amount, address _from, address _to) private returns (uint) {
count_rounds_change_logs[count_rounds] = add(count_rounds_change_logs[count_rounds], 1);
uint log_id = count_rounds_change_logs[count_rounds];
change_logs[count_rounds][log_id].block_number = block.number;
change_logs[count_rounds][log_id].asset_type = asset_type;
change_logs[count_rounds][log_id].reason = reason;
change_logs[count_rounds][log_id].change_amount = change_amount;
change_logs[count_rounds][log_id].after_amount = after_amount;
change_logs[count_rounds][log_id]._from = _from;
change_logs[count_rounds][log_id]._to = _to;
return log_id;
}
function get_change_log (uint pray_round, uint log_id) public view returns (uint, uint, uint, uint, uint, address, address){ // public
change_log storage this_log = change_logs[pray_round][log_id];
return (this_log.block_number,
this_log.asset_type,
this_log.reason, // reason > 10 is buy_token unit_price
this_log.change_amount,
this_log.after_amount, // god's after amount. transfer or transferFrom doesn't record log
this_log._from,
this_log._to);
}
function get_count_rounds_change_logs (uint pray_round) public view returns(uint){
return count_rounds_change_logs[pray_round];
}
// end of logs
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsDice {
// ethgods
EthGods private eth_gods;
address private ethgods_contract_address = address(0);// publish ethgods first, then use that address in constructor
function set_eth_gods_contract_address(address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
uint private block_hash_duration;
function update_admin () public returns (bool){
(,,address new_admin, uint new_block_hash_duration,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
block_hash_duration = new_block_hash_duration;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
}
function finalize () public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
function () public payable {
revert(); // if received eth for no reason, reject
}
// end of constructor and destructor
function tell_fortune_blockhash () public view returns (bytes32){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return block_hash;
}
function tell_fortune () public view returns (uint[]){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return throw_dice (block_hash);
}
function throw_dice (bytes32 block_hash) public pure returns (uint[]) {// 0 for prize, 1-6 for 6 numbers should be pure
uint[] memory dice_numbers = new uint[](7);
//uint [7] memory dice_numbers;
uint hash_number;
uint[] memory count_dice_numbers = new uint[](7);
//uint [7] memory count_dice_numbers; // how many times for each dice number
uint i; // for loop
for (i = 1; i <= 6; i++) {
hash_number = uint(block_hash[i]);
// hash_number=1;
if (hash_number >= 214) { // 214
dice_numbers[i] = 6;
} else if (hash_number >= 172) { // 172
dice_numbers[i] = 5;
} else if (hash_number >= 129) { // 129
dice_numbers[i] = 4;
} else if (hash_number >= 86) { // 86
dice_numbers[i] = 3;
} else if (hash_number >= 43) { // 43
dice_numbers[i] = 2;
} else {
dice_numbers[i] = 1;
}
count_dice_numbers[dice_numbers[i]] ++;
}
bool won_super_prize = false;
uint count_super_eth = 0;
for (i = 1; i <= 6; i++) {
if (count_dice_numbers[i] >= 5) {
dice_numbers[0] = 1; //champion_eth
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 4) {
dice_numbers[0] = 3; // super_egst
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 1) {
count_super_eth ++;
if (count_super_eth == 6) {
dice_numbers[0] = 2; // super_eth
won_super_prize = true;
}
}
}
if (won_super_prize == false) {
if (count_dice_numbers[6] >= 2){
dice_numbers[0] = 4; // primary_egst
} else if (count_dice_numbers[6] == 1){
dice_numbers[0] = 5; // lucky_star
}
}
return dice_numbers;
}
function pk (bytes32 block_hash, uint attacker_sum_god_levels, uint attacker_sum_amulet_levels, uint defender_sum_god_levels, uint defender_sum_amulet_levels) public pure returns (bool){
uint god_win_chance;
attacker_sum_god_levels = add(attacker_sum_god_levels, 10);
if (attacker_sum_god_levels < defender_sum_god_levels){
god_win_chance = 0;
} else {
god_win_chance = sub(attacker_sum_god_levels, defender_sum_god_levels);
if (god_win_chance > 20) {
god_win_chance = 100;
} else { // equal level, 50% chance to win
god_win_chance = mul(god_win_chance, 5);
}
}
uint amulet_win_chance;
attacker_sum_amulet_levels = add(attacker_sum_amulet_levels, 10);
if (attacker_sum_amulet_levels < defender_sum_amulet_levels){
amulet_win_chance = 0;
} else {
amulet_win_chance = sub(attacker_sum_amulet_levels, defender_sum_amulet_levels);
if (amulet_win_chance > 20) {
amulet_win_chance = 100;
} else { // equal level, 50% chance to win
amulet_win_chance = mul(amulet_win_chance, 5);
}
}
uint attacker_win_chance = div(add(god_win_chance, amulet_win_chance), 2);
if (attacker_win_chance >= div(mul(uint(block_hash[3]),2),5)){
return true;
} else {
return false;
}
}
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsName {
// EthGods
EthGods private eth_gods;
address private ethgods_contract_address;
function set_eth_gods_contract_address (address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
function update_admin () public returns (bool){
(,,address new_admin,,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private invalid_chars = "\\\"";
bytes private invalid_bytes = bytes(invalid_chars);
function set_invalid_chars (string new_invalid_chars) public returns (bool) {
require(msg.sender == admin);
invalid_chars = new_invalid_chars;
invalid_bytes = bytes(invalid_chars);
return true;
}
uint private valid_length = 16;
function set_valid_length (uint new_valid_length) public returns (bool) {
require(msg.sender == admin);
valid_length = new_valid_length;
return true;
}
struct god_name {
string god_name;
uint block_number;
uint block_duration;
}
mapping (address => god_name) private gods_name;
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
address v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
gods_name[v_god].god_name = "V";
}
function () public payable {
revert(); // if received eth for no reason, reject
}
function finalize() public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
// end of constructor and destructor
function set_god_name (string new_name) public returns (bool){
address god_address = msg.sender;
require (add(gods_name[god_address].block_number, gods_name[god_address].block_duration) < block.number );
bytes memory bs = bytes(new_name);
require (bs.length <= valid_length);
for (uint i = 0; i < bs.length; i++){
for (uint j = 0; j < invalid_bytes.length; j++) {
if (bs[i] == invalid_bytes[j]){
return false;
}
}
}
gods_name[god_address].god_name = new_name;
emit set_name(god_address, new_name);
return true;
}
event set_name (address indexed god_address, string new_name);
function get_god_name (address god_address) public view returns (string) {
return gods_name[god_address].god_name;
}
function block_god_name (address god_address, uint block_duration) public {
require (msg.sender == admin);
gods_name[god_address].god_name = "Unkown";
gods_name[god_address].block_number = block.number;
gods_name[god_address].block_duration = block_duration;
}
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
}
|
if allowed amount used and owner tries to reset allowed amount within a short time, the allowed account might be cheating the owner
|
function approve (address spender, uint tokens) public returns (bool success) {
require (balances[msg.sender] >= tokens);
if (tokens > 0){
require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number);
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 997,300
|
./full_match/5/0x77087fb998Dc569F8E3bC60acf27FA0d313664Cb/sources/project_/contracts/MintTZRKT.sol
|
set Billy Mint Time can only be called by the owner startTime mint start epoch time endTime mint end epoch time/
|
function setBillyMintTime(uint256 startTime, uint256 endTime) public onlyOwner {
require(startTime < endTime, "setBillyMintTime: startTime is greater than endTime");
_billyMintStartTime = startTime;
_billyMintEndTime = endTime;
}
| 1,935,728
|
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: contracts/BunnyStaking.sol
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
interface ERC1155 /* is ERC165 */ {
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_id` argument MUST be the token type being transferred.
The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);
/**
@dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
The `_from` argument MUST be the address of the holder whose balance is decreased.
The `_to` argument MUST be the address of the recipient whose balance is increased.
The `_ids` argument MUST be the list of tokens being transferred.
The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
*/
event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);
/**
@dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled).
*/
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
@dev MUST emit when the URI is updated for a token ID.
URIs are defined in RFC 3986.
The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
*/
event URI(string _value, uint256 indexed _id);
/**
@notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
MUST revert on any other error.
MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _id ID of the token type
@param _value Transfer amount
@param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
*/
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
/**
@notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
@dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
MUST revert if `_to` is the zero address.
MUST revert if length of `_ids` is not the same as length of `_values`.
MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
MUST revert on any other error.
MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
@param _from Source address
@param _to Target address
@param _ids IDs of each token type (order and length must match _values array)
@param _values Transfer amounts per token type (order and length must match _ids array)
@param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
*/
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;
/**
@notice Get the balance of an account's tokens.
@param _owner The address of the token holder
@param _id ID of the token
@return The _owner's balance of the token type requested
*/
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/**
@notice Get the balance of multiple account/token pairs
@param _owners The addresses of the token holders
@param _ids ID of the tokens
@return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
*/
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
/**
@notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
@dev MUST emit the ApprovalForAll event on success.
@param _operator Address to add to the set of authorized operators
@param _approved True if the operator is approved, false to revoke approval
*/
function setApprovalForAll(address _operator, bool _approved) external;
/**
@notice Queries the approval status of an operator for a given owner.
@param _owner The owner of the tokens
@param _operator Address of authorized operator
@return True if the operator is approved, false if not
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 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 SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 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
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 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),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 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(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: 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(IERC20 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, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/libs/Initializable.sol
pragma solidity ^0.8.0;
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// File: contracts/libs/EIP712Base.sol
pragma solidity ^0.8.0;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File: contracts/libs/ContentMixin.sol
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File: openzeppelin-solidity/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// 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 (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @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) {
return a + b;
}
/**
* @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 a - b;
}
/**
* @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) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting 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 a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting 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) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* 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) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/libs/NativeMetaTransaction.sol
pragma solidity ^0.8.0;
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File: openzeppelin-solidity/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-solidity/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-solidity/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-solidity/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-solidity/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-solidity/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-solidity/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-solidity/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-solidity/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);
}
interface FadeAwayBunnyNFT is IERC721 {
function bunnies(uint256 _id) external view returns (bytes32, uint64, uint32, uint32, uint16);
}
interface IPillToken is IERC20 {
function mint(address _user, uint256 _amount) external;
}
contract BunnyStakingContract is Ownable, ReentrancyGuard, IERC721Receiver {
using SafeMath for uint256;
using SafeERC20 for IPillToken;
using EnumerableSet for EnumerableSet.UintSet;
// Info of each user.
struct UserInfo {
uint256 amount;
uint256 harvestedReward;
mapping(uint256 => AppliedItem) item;
EnumerableSet.UintSet nftIds;
mapping(uint256 => uint256) lastRewardBlock;
}
struct AppliedItem {
uint256 endBlock;
uint256 itemId;
}
struct FadeAwayBunny {
bytes32 genes;
uint64 birthTime;
uint32 matronId;
uint32 sireId;
uint16 generation;
}
IPillToken public rewardToken;
FadeAwayBunnyNFT public nftAddress;
ERC1155 public itemAddress;
mapping(address => UserInfo) userInfo;
mapping(uint256 => uint16) public itemRate; // same with rewardRate, 10000 = 100%
uint256 public finalRewardBlock; // The block number when token rewarding has to end.
uint256 public rewardPerDay = 100 * 1e18; // 100 PILL per day
uint256 public itemEffectBlock = 50400; // 7 days with 12s each block
uint256 public blockPerDay = 7200; // 1 day with 12s each block
address burnAddress = 0x000000000000000000000000000000000000dEaD;
event Deposit(address indexed user, uint256 indexed nftId, uint256 indexed itemId);
event Withdraw(address indexed user, uint256 indexed nftId);
event Harvest(address indexed user, uint256 indexed nftId, uint256 amount);
event ApplyItem(address indexed user, uint256 indexed nftId, uint256 indexed itemId);
constructor(
IPillToken _rewardToken,
FadeAwayBunnyNFT _nftAddress,
uint256 _finalRewardBlock
) {
rewardToken = _rewardToken;
nftAddress = _nftAddress;
finalRewardBlock = _finalRewardBlock;
}
// Update item effect block by the owner
function setItemEffectBlock(uint256 _itemEffectBlock) public onlyOwner {
itemEffectBlock = _itemEffectBlock;
}
// Update reward rate by the owner
function setRewardPerDay(uint256 _rewardPerDay) public onlyOwner {
rewardPerDay = _rewardPerDay;
}
// Update final reward block by the owner
function setFinalRewardBlock(uint256 _finalRewardBlock) public onlyOwner {
finalRewardBlock = _finalRewardBlock;
}
function getUserInfo(address _user) external view returns (uint256, uint256) {
UserInfo storage user = userInfo[_user];
return (user.amount, user.harvestedReward);
}
function getApliedItemInfo(address _user, uint256 _tokenId ) external view returns (AppliedItem memory) {
UserInfo storage user = userInfo[_user];
return user.item[_tokenId];
}
//check deposited nft.
function depositsOf(address _user)
external
view
returns (uint256[] memory)
{
UserInfo storage user = userInfo[_user];
EnumerableSet.UintSet storage depositSet = user.nftIds;
uint256[] memory tokenIds = new uint256[] (depositSet.length());
for (uint256 i; i < depositSet.length(); i++) {
tokenIds[i] = depositSet.at(i);
}
return tokenIds;
}
function deposit(uint256 _nftId, uint256 _itemId) public {
UserInfo storage user = userInfo[msg.sender];
nftAddress.safeTransferFrom(address(msg.sender), address(this), _nftId);
user.amount = user.amount.add(1);
user.lastRewardBlock[_nftId] = block.number;
user.nftIds.add(_nftId);
if (_itemId != 0) {
applyItem(_nftId, _itemId);
}
}
function batchDeposit(uint256[] memory _nftIds) public nonReentrant {
uint256 i;
for (i = 0; i < _nftIds.length; i++) {
deposit(_nftIds[i], 0);
}
}
function viewNftRate(uint256 _nftId) public view returns (uint16) {
(bytes32 genes, , , , uint16 generation) = nftAddress.bunnies(_nftId);
if (generation == 0) {
return 10000;
}
bytes2[2] memory earnRate = [bytes2(0), 0];
assembly {
mstore(earnRate, genes)
mstore(add(earnRate, 2), genes)
}
uint16 earnRateInt = uint16(earnRate[1]);
if (earnRateInt < 180) {
return 10000;
} else if (earnRateInt < 231) {
return 15000;
} else {
return 20000;
}
}
function isUserStakedNft(address _user, uint256 _nftId) public view returns (bool) {
UserInfo storage user = userInfo[_user];
return user.nftIds.contains(_nftId);
}
function viewReward(address _user, uint256 _nftId) public view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint16 nftRate = viewNftRate(_nftId);
uint256 maxBlock;
if (block.number > finalRewardBlock) {
maxBlock = finalRewardBlock;
} else {
maxBlock = block.number;
}
if (user.lastRewardBlock[_nftId] >= maxBlock) {
return 0;
}
if (user.item[_nftId].itemId != 0 && user.lastRewardBlock[_nftId] <= user.item[_nftId].endBlock) {
if (maxBlock <= user.item[_nftId].endBlock) {
return rewardPerDay.mul(maxBlock - user.lastRewardBlock[_nftId]).mul(itemRate[user.item[_nftId].itemId]).mul(nftRate).div(1e8).div(blockPerDay);
} else {
uint256 itemPeriod = user.item[_nftId].endBlock - user.lastRewardBlock[_nftId];
uint256 normalPeriod = maxBlock - user.item[_nftId].endBlock;
uint256 tmpItemRate = itemRate[user.item[_nftId].itemId];
uint256 itemPeriodReward = rewardPerDay.mul(itemPeriod).mul(tmpItemRate).mul(nftRate).div(1e8).div(blockPerDay);
uint256 normalPeriodReward = rewardPerDay.mul(normalPeriod).mul(nftRate).div(10000).div(blockPerDay);
return itemPeriodReward + normalPeriodReward;
}
} else {
return rewardPerDay.mul(maxBlock - user.lastRewardBlock[_nftId]).mul(nftRate).div(10000).div(blockPerDay);
}
}
function harvest(uint256 _nftId) public {
require(isUserStakedNft(msg.sender, _nftId), "harvest:: this nft is not yours");
UserInfo storage user = userInfo[msg.sender];
uint256 reward = viewReward(msg.sender, _nftId);
if (reward == 0) {
return;
}
user.lastRewardBlock[_nftId] = block.number;
user.harvestedReward = user.harvestedReward + reward;
rewardToken.mint(msg.sender, reward);
emit Harvest(msg.sender, _nftId, reward);
}
function harvestAll() public nonReentrant {
UserInfo storage user = userInfo[msg.sender];
EnumerableSet.UintSet storage depositSet = user.nftIds;
for (uint256 i; i < depositSet.length(); i++) {
harvest(depositSet.at(i));
}
}
function batchHarvest(uint256[] memory _nftIds) public nonReentrant {
uint256 i;
for (i = 0; i < _nftIds.length; i++) {
harvest(_nftIds[i]);
}
}
function batchWithdraw(uint256[] memory _nftIds) public nonReentrant {
uint256 i;
for (i = 0; i < _nftIds.length; i++) {
withdraw(_nftIds[i]);
}
}
function withdraw(uint256 _nftId) public {
require(isUserStakedNft(msg.sender, _nftId), "withdraw:: this nft is not yours");
UserInfo storage user = userInfo[msg.sender];
harvest(_nftId);
user.amount = user.amount.sub(1);
nftAddress.safeTransferFrom(address(this), address(msg.sender), _nftId);
user.nftIds.remove(_nftId);
emit Withdraw(msg.sender, _nftId);
}
function applyItem(uint256 _nftId, uint256 _itemId) public nonReentrant {
require(isUserStakedNft(msg.sender, _nftId), "applyItem:: this nft is not yours!");
require(itemAddress.balanceOf(msg.sender, _itemId) > 0, "applyItem:: you dont own the item!");
UserInfo storage user = userInfo[msg.sender];
require(block.number >= user.item[_nftId].endBlock, "applyItem:: only 1 ecstasy can be used at a time!");
harvest(_nftId);
itemAddress.safeTransferFrom(address(msg.sender), burnAddress, _itemId, 1, "");
user.item[_nftId].endBlock = block.number + itemEffectBlock;
user.item[_nftId].itemId = _itemId;
emit ApplyItem(msg.sender, _nftId, _itemId);
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
}
|
Update final reward block by the owner
|
function setFinalRewardBlock(uint256 _finalRewardBlock) public onlyOwner {
finalRewardBlock = _finalRewardBlock;
}
| 2,556,911
|
pragma solidity ^0.4.23;
// Copyright 2018 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// MessageBus Library
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "../lib/MerklePatriciaProof.sol";
import "../lib/SafeMath.sol";
import "../lib/BytesLib.sol";
library MessageBus {
using SafeMath for uint256;
/* Enum */
/** Status of the message state machine */
enum MessageStatus {
Undeclared,
Declared,
Progressed,
DeclaredRevocation,
Revoked
}
/** Status of the message state machine */
enum MessageBoxType {
Outbox,
Inbox
}
/* Struct */
/** MessageBox stores the inbox and outbox mapping */
struct MessageBox {
/** Maps messageHash to the MessageStatus. */
mapping(bytes32 /* messageHash */ => MessageStatus) outbox;
/** Maps messageHash to the MessageStatus. */
mapping(bytes32 /* messageHash */ => MessageStatus) inbox;
}
/** Message */
struct Message {
/**
* intent hash, this can be staking intent hash, redemption intent
* hash, gateway linking hash
*/
bytes32 intentHash;
/** nonce of the sender */
uint256 nonce;
/** gas price that sender will pay for reward */
uint256 gasPrice;
/** gas limit that sender will pay */
uint256 gasLimit;
/** sender address */
address sender;
/** hash lock provided by the facilitator */
bytes32 hashLock;
/**
* the amount of the gas consumed, this is used for reward
* calculation
*/
uint256 gasConsumed;
}
/* constants */
/** Position of outbox in struct MessageBox */
uint8 constant OUTBOX_OFFSET = 0;
/** Position of inbox in struct MessageBox */
uint8 constant INBOX_OFFSET = 1;
/**
* @notice Declare a new message. This will update the outbox status to
* `Declared` for the given message hash
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _signature Signed data.
*
* @return messageHash_ Message hash
*/
function declareMessage(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes _signature
)
external
returns (bytes32 messageHash_)
{
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// Check the existing message status for the message hash in message
// outbox is `Undeclared`
require(
_messageBox.outbox[messageHash_] == MessageStatus.Undeclared,
"Message status must be Undeclared"
);
// Verify the signature
require(
verifySignature(messageHash_, _signature, _message.sender),
"Invalid signature"
);
// Update the message status to `Declared` in outbox for the given
// message hash
_messageBox.outbox[messageHash_] = MessageStatus.Declared;
}
/**
* @notice Confirm a new message that is declared in outbox on the source
* chain. Merkle proof will be performed to verify the declared
* status in source chains outbox. This will update the inbox
* status to `Declared` for the given message hash.
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _rlpEncodedParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset position of the messageBox.
* @param _storageRoot storage root for proof
*
* @return messageHash_ Message hash
*/
function confirmMessage(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes _rlpEncodedParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot
)
external
returns (bytes32 messageHash_)
{
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// Check the existing message status for the message hash in message
// inbox is `Undeclared`
require(
_messageBox.inbox[messageHash_] == MessageStatus.Undeclared,
"Message status must be Undeclared"
);
// get the storage path for proof
bytes memory path = bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(MessageStatus.Declared)),
path,
_rlpEncodedParentNodes,
_storageRoot),
"Merkle proof verification failed"
);
// Update the message box inbox status to `Declared`.
_messageBox.inbox[messageHash_] = MessageStatus.Declared;
}
/**
* @notice Update the status for the outbox for a given message hash to
* `Progressed`
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _unlockSecret unlock secret for the hash lock provided while
* declaration
*
* @return messageHash_ Message hash
*/
function progressOutbox(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes32 _unlockSecret
)
external
returns (bytes32 messageHash_)
{
// verify the unlock secret
require(
_message.hashLock == keccak256(abi.encode(_unlockSecret)),
"Invalid unlock secret"
);
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// Verify the current message status is `Declared`
require(
_messageBox.outbox[messageHash_] == MessageStatus.Declared,
"Message status must be Declared"
);
// Update the message status of outbox to `Progressed`
_messageBox.outbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the outbox for a given message hash to
* `Progressed`. Merkle proof is used to verify status of inbox in
* source chain. This is an alternative approach to hashlocks.
*
* @dev The messsage status for the message hash in the inbox should be
* either `Declared` or `Progresses`. Either of this status will be
* verified in the merkle proof
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _rlpEncodedParentNodes RLP encoded parent node data to prove in
* messageBox inbox.
* @param _messageBoxOffset position of the messageBox.
* @param _storageRoot storage root for proof
* @param _messageStatus Message status of message hash in the inbox of
* source chain
*
* @return messageHash_ Message hash
*/
function progressOutboxWithProof(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes _rlpEncodedParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
// the message status for the message hash in the inbox must be either
// `Declared` or `Progressed`
require(
_messageStatus == MessageStatus.Declared ||
_messageStatus == MessageStatus.Progressed,
"Message status must be Declared or Progressed"
);
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// The existing message status must be `Declared` or
// `DeclaredRevocation`.
require(
_messageBox.outbox[messageHash_] == MessageStatus.Declared ||
_messageBox.outbox[messageHash_] ==
MessageStatus.DeclaredRevocation,
"Message status must be Declared"
);
// Get the path
bytes memory path = bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
INBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
path,
_rlpEncodedParentNodes,
_storageRoot),
"Merkle proof verification failed"
);
// Update the status to `Progressed`
_messageBox.outbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the inbox for a given message hash to
* `Progressed`
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _unlockSecret unlock secret for the hash lock provided while
* declaration
*
* @return messageHash_ Message hash
*/
function progressInbox(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes32 _unlockSecret
)
external
returns (bytes32 messageHash_)
{
// verify the unlock secret
require(
_message.hashLock == keccak256(abi.encode(_unlockSecret)),
"Invalid unlock secret"
);
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// Verify the current message status is `Declared`
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message status must be Declared"
);
// Update the message status of outbox to `Progressed`
_messageBox.inbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Update the status for the inbox for a given message hash to
* `Progressed`. Merkle proof is used to verify status of outbox in
* source chain. This is an alternative approach to hashlocks.
*
* @dev The messsage status for the message hash in the outbox should be
* either `Declared` or `Progresses`. Either of this status will be
* verified in the merkle proof
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _rlpEncodedParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset position of the messageBox.
* @param _storageRoot storage root for proof
* @param _messageStatus Message status of message hash in the outbox of
* source chain
*
* @return messageHash_ Message hash
*/
function progressInboxWithProof(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes _rlpEncodedParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
// the message status for the message hash in the outbox must be either
// `Declared` or `Progressed`
require(
_messageStatus == MessageStatus.Declared ||
_messageStatus == MessageStatus.Progressed,
"Message status must be Declared or Progressed"
);
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// The existing message status must be `Declared`
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message status must be Declared"
);
// @dev the out box is at location 0 of the MessageBox struct, so it
// is same as _messageBoxOffset
bytes memory path = bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
path,
_rlpEncodedParentNodes,
_storageRoot),
"Merkle proof verification failed"
);
// Update the status to `Progressed`
_messageBox.inbox[messageHash_] = MessageStatus.Progressed;
}
/**
* @notice Declare a new revocation message. This will update the outbox
* status to `DeclaredRevocation` for the given message hash
*
* @dev In order to declare revocation the existing message status for the
* given message hash should be `Declared`.
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
*
* @return messageHash_ Message hash
*/
function declareRevocationMessage(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message
)
external
returns (bytes32 messageHash_)
{
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// outbox should be declared
require(
_messageBox.outbox[messageHash_] == MessageStatus.Declared,
"Message status must be Declared"
);
// change the status of outbox
_messageBox.outbox[messageHash_] = MessageStatus.DeclaredRevocation;
}
/**
* @notice Confirm a revocation message that is declared in the outbox of
* source chain. This will update the outbox status to
* `Revoked` for the given message hash.
*
* @dev In order to declare revocation the existing message status for the
* given message hash should be `Declared`.
*
* @param _messageBox Message Box
* @param _messageTypeHash Message type hash
* @param _message Message object
* @param _rlpEncodedParentNodes RLP encoded parent node data to prove in
* messageBox outbox.
* @param _messageBoxOffset position of the messageBox.
* @param _storageRoot storage root for proof
*
* @return messageHash_ Message hash
*/
function confirmRevocation(
MessageBox storage _messageBox,
bytes32 _messageTypeHash,
Message storage _message,
bytes _rlpEncodedParentNodes,
uint8 _messageBoxOffset,
bytes32 _storageRoot
)
external
returns (bytes32 messageHash_)
{
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// Check the existing message status for the message hash in message
// inbox is `Declared`
require(
_messageBox.inbox[messageHash_] == MessageStatus.Declared,
"Message status must be Declared"
);
// Get the path
bytes memory path = bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
OUTBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof
require(MerklePatriciaProof.verify(
keccak256(abi.encodePacked(MessageStatus.DeclaredRevocation)),
path,
_rlpEncodedParentNodes,
_storageRoot),
"Merkle proof verification failed"
);
// Update the message box inbox status to `Revoked`.
_messageBox.inbox[messageHash_] = MessageStatus.Revoked;
}
/**
* @notice Update the status for the outbox for a given message hash to
* `Revoked`. Merkle proof is used to verify status of inbox in
* source chain.
*
* @dev The messsage status in the inbox should be
* either `DeclaredRevocation` or `Revoked`. Either of this status
* will be verified in the merkle proof
*
* @param _messageBox Message Box
* @param _message Message object
* @param _messageTypeHash Message type hash
* @param _messageBoxOffset position of the messageBox.
* @param _rlpEncodedParentNodes RLP encoded parent node data to prove in
* messageBox inbox.
* @param _storageRoot storage root for proof
* @param _messageStatus Message status of message hash in the inbox of
* source chain
*
* @return messageHash_ Message hash
*/
function progressOutboxRevocation(
MessageBox storage _messageBox,
Message storage _message,
bytes32 _messageTypeHash,
uint8 _messageBoxOffset,
bytes _rlpEncodedParentNodes,
bytes32 _storageRoot,
MessageStatus _messageStatus
)
external
returns (bytes32 messageHash_)
{
// the message status for the message hash in the inbox must be either
// `DeclaredRevocation` or `Revoked`
require(
_messageStatus == MessageStatus.DeclaredRevocation ||
_messageStatus == MessageStatus.Revoked,
"Message status must be DeclaredRevocation or Revoked"
);
// Get the message hash
messageHash_ = messageDigest(
_messageTypeHash,
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit
);
// The existing message status must be `DeclaredRevocation`
require(
_messageBox.outbox[messageHash_] ==
MessageStatus.DeclaredRevocation,
"Message status must be DeclaredRevocation"
);
// @dev the out box is at location 1 of the MessageBox struct, so we
// add one to get the path
bytes memory path = bytes32ToBytes(
storageVariablePathForStruct(
_messageBoxOffset,
INBOX_OFFSET,
messageHash_
)
);
// Perform the merkle proof
require(
MerklePatriciaProof.verify(
keccak256(abi.encodePacked(_messageStatus)),
path,
_rlpEncodedParentNodes,
_storageRoot),
"Merkle proof verification failed"
);
// Update the status to `Revoked`
_messageBox.outbox[messageHash_] = MessageStatus.Revoked;
}
/**
* @notice Change inbox state to the next possible state
*
* @dev State will change only for Undeclared, Declared, DeclaredRevocation
* Undeclared -> Declared, Declared -> Progressed,
* DeclaredRevocation -> Revoked
*
* @param _messageBox Message box.
* @param _messageHash Message hash
*
* @return isChanged_ `true` if the state is changed
* @return nextState_ Next state to which its changed
*/
function changeInboxState(
MessageBox storage _messageBox,
bytes32 _messageHash
)
external
returns (
bool isChanged_,
MessageBus.MessageStatus nextState_
)
{
MessageStatus status = _messageBox.inbox[_messageHash];
if(status == MessageStatus.Undeclared) {
isChanged_ = true;
nextState_ = MessageStatus.Declared;
} else if(status == MessageStatus.Declared) {
isChanged_ = true;
nextState_ = MessageStatus.Progressed;
} else if(status == MessageStatus.DeclaredRevocation) {
isChanged_ = true;
nextState_ = MessageStatus.Revoked;
}
if(isChanged_){
// Update the message inbox status.
_messageBox.inbox[_messageHash] = nextState_;
}
}
/**
* @notice Change outbox state to the next possible state
*
* @dev State will change only for Undeclared, Declared, DeclaredRevocation
* Undeclared -> Declared, Declared -> Progressed,
* DeclaredRevocation -> Revoked
*
* @param _messageBox Message box.
* @param _messageHash Message hash
*
* @return isChanged_ `true` if the state is changed
* @return nextState_ Next state to which its changed
*/
function changeOutboxState(
MessageBox storage _messageBox,
bytes32 _messageHash
)
external
returns (
bool isChanged_,
MessageBus.MessageStatus nextState_
)
{
MessageStatus status = _messageBox.outbox[_messageHash];
if(status == MessageStatus.Undeclared) {
isChanged_ = true;
nextState_ = MessageStatus.Declared;
} else if(status == MessageStatus.Declared) {
isChanged_ = true;
nextState_ = MessageStatus.Progressed;
} else if(status == MessageStatus.DeclaredRevocation) {
isChanged_ = true;
nextState_ = MessageStatus.Revoked;
}
if(isChanged_){
// Update the message outbox status.
_messageBox.outbox[_messageHash] = nextState_;
}
}
/* public functions */
/**
* @notice Generate revocation message hash from the input params
*
* @param _messageHash Message hash
* @param _nonce Nonce
*
* @return Revocation message hash
*/
function revocationMessageDigest(
bytes32 _messageHash,
uint256 _nonce
)
public
pure
returns (bytes32 /* revocationMessageHash */)
{
return keccak256(
abi.encode(
_messageHash,
_nonce
)
);
}
/**
* @notice Generate message hash from the input params
*
* @param _messageTypeHash Message type hash
* @param _intentHash Intent hash
* @param _nonce Nonce
* @param _gasPrice Gas price
*
* @return Message hash
*/
function messageDigest(
bytes32 _messageTypeHash,
bytes32 _intentHash,
uint256 _nonce,
uint256 _gasPrice,
uint256 _gasLimit
)
public
pure
returns (bytes32 /* messageHash */)
{
return keccak256(
abi.encode(
_messageTypeHash,
_intentHash,
_nonce,
_gasPrice,
_gasLimit
)
);
}
/* private functions */
/**
* @notice Verify the signature is signed by the signer address.
*
* @param _message Message hash
* @param _signature Signature
* @param _signer Signer address
*
* @return `true` if the signature is signed by the signer
*/
function verifySignature(
bytes32 _message,
bytes _signature,
address _signer
)
private
pure
returns (bool /*success*/)
{
if (_signature.length != 65) {
return false;
}
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
_message = keccak256(abi.encodePacked(prefix, _message));
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also
// possible versions
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return false;
}
return (ecrecover(_message, v, r, s) == _signer);
}
/*
* @notice Get the storage path of the variable inside the struct
*
* @param _structPosition Position of struct variable
* @param _offset Offset of variable inside the struct
* @param _key Key of variable incase of mapping
*
* @return bytes32 Storage path of the variable
*/
function storageVariablePathForStruct(
uint8 _structPosition,
uint8 _offset,
bytes32 _key
)
private
pure
returns(bytes32 /* storage path */)
{
bytes memory indexBytes = BytesLib.leftPad(bytes32ToBytes(
bytes32(_structPosition)));
bytes memory keyBytes = BytesLib.leftPad(bytes32ToBytes(_key));
bytes memory path = BytesLib.concat(keyBytes, indexBytes);
bytes32 structPath = keccak256(abi.encodePacked(keccak256(
abi.encodePacked(path))));
if (_offset == 0) {
return structPath;
}
bytes32 storagePath;
uint8 offset = _offset;
assembly {
storagePath := add(structPath, offset)
}
return keccak256(abi.encodePacked(storagePath));
}
/**
* @notice Convert bytes32 to bytes
*
* @param _inBytes32 bytes32 value
*
* @return bytes value
*/
function bytes32ToBytes(bytes32 _inBytes32)
private
pure
returns (bytes)
{
bytes memory res = new bytes(32);
assembly {
mstore(add(32,res), _inBytes32)
}
return res;
}
}
|
Change outbox state to the next possible state State will change only for Undeclared, Declared, DeclaredRevocation Undeclared -> Declared, Declared -> Progressed, DeclaredRevocation -> Revoked _messageBox Message box. _messageHash Message hash return isChanged_ `true` if the state is changed return nextState_ Next state to which its changed/ Update the message outbox status.
|
function changeOutboxState(
MessageBox storage _messageBox,
bytes32 _messageHash
)
external
returns (
bool isChanged_,
MessageBus.MessageStatus nextState_
)
{
MessageStatus status = _messageBox.outbox[_messageHash];
if(status == MessageStatus.Undeclared) {
isChanged_ = true;
nextState_ = MessageStatus.Declared;
isChanged_ = true;
nextState_ = MessageStatus.Progressed;
isChanged_ = true;
nextState_ = MessageStatus.Revoked;
}
if(isChanged_){
_messageBox.outbox[_messageHash] = nextState_;
}
}
| 14,100,029
|
./full_match/5/0xE70761E6FA325a9Ec97Ba7Ad7A05ad9175047776/sources/project_/contracts/FarmsentERC20.sol
|
Removing account to Whitelisting _beneficiary address of the account./
|
function removeFromWhitelist(address _beneficiary) external onlyOwner {
_whitelist[_beneficiary] = false;
emit RemovedFromWhiteListed(_beneficiary);
}
| 1,921,802
|
./partial_match/3/0xB4467E8D621105312a914F1D42f10770C0Ffe3c8/sources/FlashToken.sol
|
Explicitly disallow authorizations for address(0) as ecrecover returns address(0) on malformed messages
|
function _validateSignedData(
address signer,
bytes32 encodeData,
uint8 v,
bytes32 r,
bytes32 s
) internal view {
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", getDomainSeparator(), encodeData));
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == signer, "FlashToken:: INVALID_SIGNATURE");
}
| 5,140,354
|
/*
Implements EIP918 draft token standard: https://github.com/0xbitcoin/ERC541-Spec/blob/master/contracts/EIP541.sol
.*/
pragma solidity ^0.4.18;
import "./EIP20Interface.sol";
import "./AbstractERC918.sol";
import "./SafeMath.sol";
import "./ExtendedMath.sol";
import "./Owned.sol";
/**
* _0xBitcoinBase Implementation used for creating ERC918, ERC20 mineable tokens using the same difficulty
* adjustment, reward and hashing features of 0xBitcoin
*
* This complex contract implements a minimal set of behaviors (hash, reward, epoch, and difficulty adjustment)
* and state required to build a Proof of Work driven mineable token. Refactoring of 0xBitcoin base code to be
* used for implementing 0xbitcoin based mineable tokens
*
* https://github.com/ethereum/EIPs/pull/918
* https://github.com/0xbitcoin/0xbitcoin-token/blob/master/contracts/_0xBitcoinToken.sol
*/
contract _0xBitcoinBase is AbstractERC918, EIP20Interface {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint256 public totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount;//number of 'blocks' mined
uint public baseMiningReward;
uint public blocksPerReadjustment;
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**234;
uint public rewardEra;
uint public maxSupplyForEra;
uint public MAX_REWARD_ERA = 39;
uint public MINING_RATE_FACTOR = 60; //mint the token 60 times less often than ether
//difficulty adjustment parameters- be careful modifying these
uint public MAX_ADJUSTMENT_PERCENT = 100;
uint public TARGET_DIVISOR = 2000;
uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2);
mapping(bytes32 => bytes32) solutionForChallenge;
mapping(address => mapping(address => uint)) allowed;
// balances of
mapping(address => uint) balances;
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function _0xBitcoinBase(
string tokenSymbol,
string tokenName,
uint256 tokenSupply,
uint8 tokenDecimals,
uint initialReward,
uint blocksPerDifficultyAdjustment
) public {
symbol = tokenSymbol;
name = tokenName;
decimals = tokenDecimals;
totalSupply = tokenSupply * 10**uint(decimals);
baseMiningReward = initialReward;
blocksPerReadjustment = blocksPerDifficultyAdjustment;
// -- do not change lines below --
tokensMinted = 0;
rewardEra = 0;
maxSupplyForEra = totalSupply.div(2);
difficulty = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_newEpoch(0);
}
function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest) {
digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > difficulty) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
}
//21m coins total
//reward begins at 50 and is cut in half every reward era (as tokens are mined)
function _reward() internal returns (uint) {
//once we get half way thru the coins, only get 25 per block
//every reward era, the reward amount halves.
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
return reward_amount;
}
function _newEpoch(uint256 nonce) internal returns (uint) {
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//40 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA)
{
rewardEra = rewardEra + 1;
}
//set the next minted supply at which the era will change
// total supply is 2100000000000000 because of 8 decimal places
maxSupplyForEra = totalSupply - totalSupply.div( 2**(rewardEra + 1));
epochCount = epochCount.add(1);
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
//DO NOT manually edit this method unless you know EXACTLY what you are doing
function _adjustDifficulty() internal returns (uint) {
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % blocksPerReadjustment != 0){
return difficulty;
}
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 360 ethereum blocks per hour
//we want miners to spend 10 minutes to mine each 'block', about 60 ethereum blocks = one 0xbitcoin epoch
uint epochsMined = blocksPerReadjustment;
uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR;
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); //by up to 50 %
}else{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); //always between 0 and 1000
//make it easier
difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(difficulty < _MINIMUM_TARGET) //very difficult
{
difficulty = _MINIMUM_TARGET;
}
if(difficulty > _MAXIMUM_TARGET) //very easy
{
difficulty = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(difficulty);
}
function getMiningTarget() public constant returns (uint) {
return difficulty;
}
//21m coins total
//reward begins at 50 and is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint) {
//once we get half way thru the coins, only get 25 per block
//every reward era, the reward amount halves.
return (baseMiningReward * 10**uint(decimals) ).div( 2**rewardEra ) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
|
if max supply for the era will be exceeded next reward round then enter the new era before that happens40 is the final reward era, almost all tokens mintedonce the final era is reached, more tokens will not be given out because the assert function
|
function _newEpoch(uint256 nonce) internal returns (uint) {
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA)
{
rewardEra = rewardEra + 1;
}
epochCount = epochCount.add(1);
}
| 951,753
|
./partial_match/1/0x1111111254EEB25477B68fb85Ed929f73A960582/sources/AggregationRouterV5.sol
|
(bool success, bytes memory data) = signer.staticcall(abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, abi.encodePacked(r, vs))); return success && data.length >= 4 && abi.decode(data, (bytes4)) == IERC1271.isValidSignature.selector;
|
function isValidSignature(address signer, bytes32 hash, bytes32 r, bytes32 vs) internal view returns(bool success) {
bytes4 selector = IERC1271.isValidSignature.selector;
let ptr := mload(0x40)
mstore(ptr, selector)
mstore(add(ptr, 0x04), hash)
mstore(add(ptr, 0x24), 0x40)
mstore(add(ptr, 0x44), 64)
mstore(add(ptr, 0x64), r)
mstore(add(ptr, 0x84), vs)
if staticcall(gas(), signer, ptr, 0xa4, 0, 0x20) {
success := and(eq(selector, mload(0)), eq(returndatasize(), 0x20))
}
}
| 9,171,886
|
./full_match/1/0xDda46bF18eeb3E06E2F12975A3A184e40581A72f/sources/_prb/math/src/ud60x18/Casting.sol
|
Alias for the `wrap` function.
|
function ud(uint256 x) pure returns (UD60x18 result) {
result = wrap(x);
}
| 3,094,350
|
pragma solidity ^0.4.11;
/// @title Voting with delegation.
contract Ballot {
// This declares a new complex type which will
// be used for variables later.
// It will represent a single voter.
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
uint votedParty; // index of the voted proposal
uint votedCandidate;
}
// This is a type for a single proposal.
struct Party {
bytes32 partyName; // short name (up to 32 bytes)
uint partyVoteCount; // number of accumulated votes
}
struct Candidate {
bytes32 candidateName;
uint candidateVoteCount;
}
address public chairperson;
uint electionEndTime = 0;
bool electionHasStarted = false;
uint blockNo;
// This declares a state variable that
// stores a `Voter` struct for each possible address.
mapping(address => Voter) public voters;
// A dynamically-sized array of structs.
Party[] public parties;
Candidate[] public candidates;
/// Create a new ballot to choose one of `proposalNames`.
function Ballot(bytes32[] partyNames, bytes32[] candidateNames) {
chairperson = msg.sender;
voters[chairperson].weight = 1;
// For each of the provided proposal names,
// create a new proposal object and add it
// to the end of the array.
for (uint i = 0; i < partyNames.length; i++) {
// `Proposal({...})` creates a temporary
// Proposal object and `proposals.push(...)`
// appends it to the end of `proposals`.
parties.push(Party({
partyName: partyNames[i],
partyVoteCount: 0
}));
}
for (uint j = 0; j < candidateNames.length; j++) {
candidates.push(Candidate({
candidateName: candidateNames[j],
candidateVoteCount: 0
}));
}
}
// Function to start an election by setting end time in epoch-seconds
function startElection(uint duration) {
require(msg.sender == chairperson);
electionEndTime = block.timestamp + duration;
electionHasStarted = true;
}
// This function returns the total votes a candidate has received so far
function totalVotesForParty(uint party) returns (uint numberOfVotes) {
//require(electionHasStarted);
//require(now > electionEndTime);
numberOfVotes = parties[party].partyVoteCount;
}
// This function returns the total votes a candidate has received so far
function totalVotesForCandidate(uint candidate) returns (uint numberOfVotes) {
//require(electionHasStarted);
//require(now > electionEndTime);
numberOfVotes = candidates[candidate].candidateVoteCount;
}
// Give `voter` the right to vote on this ballot.
// Hardcode addresses before election
function giveRightToVote(address voter) {
require((msg.sender == chairperson) && !voters[voter].voted && (voters[voter].weight == 0));
voters[voter].weight = 1;
}
/// Give your vote (including votes delegated to you)
/// to proposal `proposals[proposal].name`.
function vote(uint party, uint candidate) {
// Check if election is still active
//require(electionHasStarted);
//require(now < electionEndTime);
Voter storage sender = voters[msg.sender];
//require(!sender.voted); INCLUDE AFTER AUTHORIZING VOTERS
if (voters[msg.sender].voted) {
// Deduct the old vote
parties[sender.votedParty].partyVoteCount -= sender.weight;
candidates[sender.votedCandidate].candidateVoteCount -= sender.weight;
// Add the new vote
voters[msg.sender].votedParty = party;
voters[msg.sender].votedCandidate = candidate;
parties[party].partyVoteCount += sender.weight;
candidates[candidate].candidateVoteCount += sender.weight;
} else {
sender.weight = 1;
sender.voted = true;
sender.votedParty = party;
sender.votedCandidate = candidate;
// If `proposal` is out of the range of the array,
// this will throw automatically and revert all
// changes.
parties[party].partyVoteCount += sender.weight;
candidates[candidate].candidateVoteCount += sender.weight;
}
}
// Return the vote -- should only be called by voter
function getVotersPartyVote() constant // constant == read-only
returns (bytes32 partyTitle)
{
// require(msg.sender = voteraddress);
uint votedPartyVote = voters[msg.sender].votedParty;
partyTitle = parties[votedPartyVote].partyName;
}
function getVotersCandidateVote() constant // constant == read-only
returns (bytes32 candidateTitle)
{
Voter storage sender = voters[msg.sender];
// require(msg.sender = voteraddress);
uint votedCandidateVote = voters[msg.sender].votedCandidate;
candidateTitle = candidates[votedCandidateVote].candidateName;
}
// Function removes vote to be called when they casted it live instead
// NOT TESTED!
//function removeVotersVote(address voter) {
// Voter storage sender = voters[voter];
//proposals[sender.vote].voteCount -= 1;
//delete voters[voter];
// }
}
|
This function returns the total votes a candidate has received so farrequire(electionHasStarted);require(now > electionEndTime);
|
function totalVotesForParty(uint party) returns (uint numberOfVotes) {
numberOfVotes = parties[party].partyVoteCount;
}
| 13,141,608
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.13;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./interfaces/IOwnable.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IERC20Metadata.sol";
import "./interfaces/IOHM.sol";
import "./interfaces/IsOHM.sol";
import "./interfaces/IBondingCalculator.sol";
import "./interfaces/ITreasury.sol";
import "./types/OlympusAccessControlled.sol";
contract OlympusTreasury is OlympusAccessControlled, ITreasury {
/* ========== DEPENDENCIES ========== */
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== EVENTS ========== */
event Deposit(address indexed token, uint256 amount, uint256 value);
event Withdrawal(address indexed token, uint256 amount, uint256 value);
event CreateDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event RepayDebt(
address indexed debtor,
address indexed token,
uint256 amount,
uint256 value
);
event Managed(address indexed token, uint256 amount);
event ReservesAudited(uint256 indexed totalReserves);
event Minted(
address indexed caller,
address indexed recipient,
uint256 amount
);
event PermissionQueued(STATUS indexed status, address queued);
event Permissioned(address addr, STATUS indexed status, bool result);
/* ========== DATA STRUCTURES ========== */
enum STATUS {
RESERVEDEPOSITOR,
RESERVESPENDER,
RESERVETOKEN,
RESERVEMANAGER,
LIQUIDITYDEPOSITOR,
LIQUIDITYTOKEN,
LIQUIDITYMANAGER,
RESERVEDEBTOR,
REWARDMANAGER,
SOHM,
OHMDEBTOR
}
struct Queue {
STATUS managing;
address toPermit;
address calculator;
uint256 timelockEnd;
bool nullify;
bool executed;
}
/* ========== STATE VARIABLES ========== */
IOHM public immutable OHM;
IsOHM public sOHM;
mapping(STATUS => address[]) public registry;
mapping(STATUS => mapping(address => bool)) public permissions;
mapping(address => address) public bondCalculator;
mapping(address => uint256) public debtLimit;
uint256 public totalReserves;
uint256 public totalDebt;
uint256 public ohmDebt;
Queue[] public permissionQueue;
uint256 public immutable blocksNeededForQueue;
bool public timelockEnabled;
bool public initialized;
uint256 public onChainGovernanceTimelock;
string internal notAccepted = "Treasury: not accepted";
string internal notApproved = "Treasury: not approved";
string internal invalidToken = "Treasury: invalid token";
string internal insufficientReserves = "Treasury: insufficient reserves";
/* ========== CONSTRUCTOR ========== */
constructor(
address _ohm,
uint256 _timelock,
address _authority
) OlympusAccessControlled(IOlympusAuthority(_authority)) {
require(_ohm != address(0), "Zero address: OHM");
OHM = IOHM(_ohm);
timelockEnabled = false;
initialized = false;
blocksNeededForQueue = _timelock;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice allow approved address to deposit an asset for OHM
* @param _amount uint256
* @param _token address
* @param _profit uint256
* @return send_ uint256
*/
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external override returns (uint256 send_) {
if (permissions[STATUS.RESERVETOKEN][_token]) {
require(permissions[STATUS.RESERVEDEPOSITOR][msg.sender], notApproved);
} else if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
require(permissions[STATUS.LIQUIDITYDEPOSITOR][msg.sender], notApproved);
} else {
revert(invalidToken);
}
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 value = tokenValue(_token, _amount);
// mint OHM needed and store amount of rewards for distribution
send_ = value.sub(_profit);
OHM.mint(msg.sender, send_);
totalReserves = totalReserves.add(value);
emit Deposit(_token, _amount, value);
}
/**
* @notice allow approved address to burn OHM for reserves
* @param _amount uint256
* @param _token address
*/
function withdraw(uint256 _amount, address _token) external override {
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted); // Only reserves can be used for redemptions
require(permissions[STATUS.RESERVESPENDER][msg.sender], notApproved);
uint256 value = tokenValue(_token, _amount);
OHM.burnFrom(msg.sender, value);
totalReserves = totalReserves.sub(value);
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Withdrawal(_token, _amount, value);
}
/**
* @notice allow approved address to withdraw assets
* @param _token address
* @param _amount uint256
*/
function manage(address _token, uint256 _amount) external override {
if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
require(permissions[STATUS.LIQUIDITYMANAGER][msg.sender], notApproved);
} else {
require(permissions[STATUS.RESERVEMANAGER][msg.sender], notApproved);
}
if (
permissions[STATUS.RESERVETOKEN][_token] ||
permissions[STATUS.LIQUIDITYTOKEN][_token]
) {
uint256 value = tokenValue(_token, _amount);
require(value <= excessReserves(), insufficientReserves);
totalReserves = totalReserves.sub(value);
}
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Managed(_token, _amount);
}
/**
* @notice mint new OHM using excess reserves
* @param _recipient address
* @param _amount uint256
*/
function mint(address _recipient, uint256 _amount) external override {
require(permissions[STATUS.REWARDMANAGER][msg.sender], notApproved);
require(_amount <= excessReserves(), insufficientReserves);
OHM.mint(_recipient, _amount);
emit Minted(msg.sender, _recipient, _amount);
}
/**
* DEBT: The debt functions allow approved addresses to borrow treasury assets
* or OHM from the treasury, using sOHM as collateral. This might allow an
* sOHM holder to provide OHM liquidity without taking on the opportunity cost
* of unstaking, or alter their backing without imposing risk onto the treasury.
* Many of these use cases are yet to be defined, but they appear promising.
* However, we urge the community to think critically and move slowly upon
* proposals to acquire these permissions.
*/
/**
* @notice allow approved address to borrow reserves
* @param _amount uint256
* @param _token address
*/
function incurDebt(uint256 _amount, address _token) external override {
uint256 value;
if (_token == address(OHM)) {
require(permissions[STATUS.OHMDEBTOR][msg.sender], notApproved);
value = _amount;
} else {
require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved);
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted);
value = tokenValue(_token, _amount);
}
require(value != 0, invalidToken);
sOHM.changeDebt(value, msg.sender, true);
require(
sOHM.debtBalances(msg.sender) <= debtLimit[msg.sender],
"Treasury: exceeds limit"
);
totalDebt = totalDebt.add(value);
if (_token == address(OHM)) {
OHM.mint(msg.sender, value);
ohmDebt = ohmDebt.add(value);
} else {
totalReserves = totalReserves.sub(value);
IERC20(_token).safeTransfer(msg.sender, _amount);
}
emit CreateDebt(msg.sender, _token, _amount, value);
}
/**
* @notice allow approved address to repay borrowed reserves with reserves
* @param _amount uint256
* @param _token address
*/
function repayDebtWithReserve(uint256 _amount, address _token)
external
override
{
require(permissions[STATUS.RESERVEDEBTOR][msg.sender], notApproved);
require(permissions[STATUS.RESERVETOKEN][_token], notAccepted);
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 value = tokenValue(_token, _amount);
sOHM.changeDebt(value, msg.sender, false);
totalDebt = totalDebt.sub(value);
totalReserves = totalReserves.add(value);
emit RepayDebt(msg.sender, _token, _amount, value);
}
/**
* @notice allow approved address to repay borrowed reserves with OHM
* @param _amount uint256
*/
function repayDebtWithOHM(uint256 _amount) external {
require(
permissions[STATUS.RESERVEDEBTOR][msg.sender] ||
permissions[STATUS.OHMDEBTOR][msg.sender],
notApproved
);
OHM.burnFrom(msg.sender, _amount);
sOHM.changeDebt(_amount, msg.sender, false);
totalDebt = totalDebt.sub(_amount);
ohmDebt = ohmDebt.sub(_amount);
emit RepayDebt(msg.sender, address(OHM), _amount, _amount);
}
/* ========== MANAGERIAL FUNCTIONS ========== */
/**
* @notice takes inventory of all tracked assets
* @notice always consolidate to recognized reserves before audit
*/
function auditReserves() external onlyGovernor {
uint256 reserves;
address[] memory reserveToken = registry[STATUS.RESERVETOKEN];
for (uint256 i = 0; i < reserveToken.length; i++) {
if (permissions[STATUS.RESERVETOKEN][reserveToken[i]]) {
reserves = reserves.add(
tokenValue(
reserveToken[i],
IERC20(reserveToken[i]).balanceOf(address(this))
)
);
}
}
address[] memory liquidityToken = registry[STATUS.LIQUIDITYTOKEN];
for (uint256 i = 0; i < liquidityToken.length; i++) {
if (permissions[STATUS.LIQUIDITYTOKEN][liquidityToken[i]]) {
reserves = reserves.add(
tokenValue(
liquidityToken[i],
IERC20(liquidityToken[i]).balanceOf(address(this))
)
);
}
}
totalReserves = reserves;
emit ReservesAudited(reserves);
}
/**
* @notice set max debt for address
* @param _address address
* @param _limit uint256
*/
function setDebtLimit(address _address, uint256 _limit)
external
onlyGovernor
{
debtLimit[_address] = _limit;
}
/**
* @notice enable permission from queue
* @param _status STATUS
* @param _address address
* @param _calculator address
*/
function enable(
STATUS _status,
address _address,
address _calculator
) external onlyGovernor {
require(timelockEnabled == false, "Use queueTimelock");
if (_status == STATUS.SOHM) {
sOHM = IsOHM(_address);
} else {
permissions[_status][_address] = true;
if (_status == STATUS.LIQUIDITYTOKEN) {
bondCalculator[_address] = _calculator;
}
(bool registered, ) = indexInRegistry(_address, _status);
if (!registered) {
registry[_status].push(_address);
if (
_status == STATUS.LIQUIDITYTOKEN || _status == STATUS.RESERVETOKEN
) {
(bool reg, uint256 index) = indexInRegistry(_address, _status);
if (reg) {
delete registry[_status][index];
}
}
}
}
emit Permissioned(_address, _status, true);
}
/**
* @notice disable permission from address
* @param _status STATUS
* @param _toDisable address
*/
function disable(STATUS _status, address _toDisable) external {
require(
msg.sender == authority.governor() || msg.sender == authority.guardian(),
"Only governor or guardian"
);
permissions[_status][_toDisable] = false;
emit Permissioned(_toDisable, _status, false);
}
/**
* @notice check if registry contains address
* @return (bool, uint256)
*/
function indexInRegistry(address _address, STATUS _status)
public
view
returns (bool, uint256)
{
address[] memory entries = registry[_status];
for (uint256 i = 0; i < entries.length; i++) {
if (_address == entries[i]) {
return (true, i);
}
}
return (false, 0);
}
/* ========== TIMELOCKED FUNCTIONS ========== */
// functions are used prior to enabling on-chain governance
/**
* @notice queue address to receive permission
* @param _status STATUS
* @param _address address
* @param _calculator address
*/
function queueTimelock(
STATUS _status,
address _address,
address _calculator
) external onlyGovernor {
require(_address != address(0));
require(timelockEnabled == true, "Timelock is disabled, use enable");
uint256 timelock = block.number.add(blocksNeededForQueue);
if (
_status == STATUS.RESERVEMANAGER || _status == STATUS.LIQUIDITYMANAGER
) {
timelock = block.number.add(blocksNeededForQueue.mul(2));
}
permissionQueue.push(
Queue({
managing: _status,
toPermit: _address,
calculator: _calculator,
timelockEnd: timelock,
nullify: false,
executed: false
})
);
emit PermissionQueued(_status, _address);
}
/**
* @notice enable queued permission
* @param _index uint256
*/
function execute(uint256 _index) external {
require(timelockEnabled == true, "Timelock is disabled, use enable");
Queue memory info = permissionQueue[_index];
require(!info.nullify, "Action has been nullified");
require(!info.executed, "Action has already been executed");
require(block.number >= info.timelockEnd, "Timelock not complete");
if (info.managing == STATUS.SOHM) {
// 9
sOHM = IsOHM(info.toPermit);
} else {
permissions[info.managing][info.toPermit] = true;
if (info.managing == STATUS.LIQUIDITYTOKEN) {
bondCalculator[info.toPermit] = info.calculator;
}
(bool registered, ) = indexInRegistry(info.toPermit, info.managing);
if (!registered) {
registry[info.managing].push(info.toPermit);
if (info.managing == STATUS.LIQUIDITYTOKEN) {
(bool reg, uint256 index) = indexInRegistry(
info.toPermit,
STATUS.RESERVETOKEN
);
if (reg) {
delete registry[STATUS.RESERVETOKEN][index];
}
} else if (info.managing == STATUS.RESERVETOKEN) {
(bool reg, uint256 index) = indexInRegistry(
info.toPermit,
STATUS.LIQUIDITYTOKEN
);
if (reg) {
delete registry[STATUS.LIQUIDITYTOKEN][index];
}
}
}
}
permissionQueue[_index].executed = true;
emit Permissioned(info.toPermit, info.managing, true);
}
/**
* @notice cancel timelocked action
* @param _index uint256
*/
function nullify(uint256 _index) external onlyGovernor {
permissionQueue[_index].nullify = true;
}
/**
* @notice disables timelocked functions
*/
function disableTimelock() external onlyGovernor {
require(timelockEnabled == true, "timelock already disabled");
if (
onChainGovernanceTimelock != 0 &&
onChainGovernanceTimelock <= block.number
) {
timelockEnabled = false;
} else {
onChainGovernanceTimelock = block.number.add(blocksNeededForQueue.mul(7)); // 7-day timelock
}
}
/**
* @notice enables timelocks after initilization
*/
function initialize() external onlyGovernor {
require(initialized == false, "Already initialized");
timelockEnabled = true;
initialized = true;
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice returns excess reserves not backing tokens
* @return uint
*/
function excessReserves() public view override returns (uint256) {
return totalReserves.sub(OHM.totalSupply().sub(totalDebt));
}
/**
* @notice returns OHM valuation of asset
* @param _token address
* @param _amount uint256
* @return value_ uint256
*/
function tokenValue(address _token, uint256 _amount)
public
view
override
returns (uint256 value_)
{
value_ = _amount.mul(10**IERC20Metadata(address(OHM)).decimals()).div(
10**IERC20Metadata(_token).decimals()
);
if (permissions[STATUS.LIQUIDITYTOKEN][_token]) {
value_ = IBondingCalculator(bondCalculator[_token]).valuation(
_token,
_amount
);
}
}
/**
* @notice returns supply metric that cannot be manipulated by debt
* @dev use this any time you need to query supply
* @return uint256
*/
function baseSupply() external view override returns (uint256) {
return OHM.totalSupply() - ohmDebt;
}
}
|
queue address to receive permission _status STATUS _address address _calculator address/
|
function queueTimelock(
STATUS _status,
address _address,
address _calculator
) external onlyGovernor {
require(_address != address(0));
require(timelockEnabled == true, "Timelock is disabled, use enable");
uint256 timelock = block.number.add(blocksNeededForQueue);
if (
_status == STATUS.RESERVEMANAGER || _status == STATUS.LIQUIDITYMANAGER
) {
timelock = block.number.add(blocksNeededForQueue.mul(2));
}
permissionQueue.push(
Queue({
managing: _status,
toPermit: _address,
calculator: _calculator,
timelockEnd: timelock,
nullify: false,
executed: false
})
);
emit PermissionQueued(_status, _address);
}
| 14,115,757
|
pragma solidity ^0.5.13;
import './interfaces/SyscoinSuperblocksI.sol';
import "./SyscoinErrorCodes.sol";
import "./SyscoinTransactionProcessor.sol";
import "@openzeppelin/upgrades/contracts/Initializable.sol";
// @dev - Manages superblocks
//
// Management of superblocks and status transitions
contract SyscoinSuperblocks is Initializable, SyscoinSuperblocksI, SyscoinErrorCodes {
uint constant ERR_PARSE_TX_SYS = 10170;
enum Network { MAINNET, TESTNET, REGTEST }
uint32 constant SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN = 0x7407;
// Mapping superblock id => superblock data
mapping (bytes32 => SuperblockInfo) private superblocks;
bytes32 private bestSuperblock;
SyscoinTransactionProcessor public syscoinERC20Manager;
event NewSuperblock(bytes32 superblockHash, address who);
event ApprovedSuperblock(bytes32 superblockHash, address who);
event ChallengeSuperblock(bytes32 superblockHash, address who);
event SemiApprovedSuperblock(bytes32 superblockHash, address who);
event InvalidSuperblock(bytes32 superblockHash, address who);
event ErrorSuperblock(bytes32 superblockHash, uint err);
event VerifyTransaction(bytes32 txHash, uint returnCode);
event RelayTransaction(bytes32 txHash, uint returnCode);
// SyscoinClaimManager
address public trustedClaimManager;
modifier onlyClaimManager() {
require(msg.sender == trustedClaimManager);
_;
}
// @param _syscoinERC20Manager - address of the SyscoinERC20Manager contract to be associated with
// @param _claimManager - address of the ClaimManager contract to be associated with
function init(address _syscoinERC20Manager, address _claimManager) public initializer {
require(address(syscoinERC20Manager) == address(0) && _syscoinERC20Manager != address(0));
syscoinERC20Manager = SyscoinTransactionProcessor(_syscoinERC20Manager);
require(address(trustedClaimManager) == address(0) && _claimManager != address(0));
trustedClaimManager = _claimManager;
}
// Convert a variable integer into something useful and return it and
// the index to after it.
function parseVarInt(bytes memory txBytes, uint pos) private pure returns (uint, uint) {
// the first byte tells us how big the integer is
uint8 ibit = uint8(txBytes[pos]);
pos += 1; // skip ibit
if (ibit < 0xfd) {
return (ibit, pos);
} else if (ibit == 0xfd) {
return (getBytesLE(txBytes, pos, 16), pos + 2);
} else if (ibit == 0xfe) {
return (getBytesLE(txBytes, pos, 32), pos + 4);
} else if (ibit == 0xff) {
return (getBytesLE(txBytes, pos, 64), pos + 8);
}
}
// convert little endian bytes to uint
function getBytesLE(bytes memory data, uint pos, uint bits) private pure returns (uint256 result) {
for (uint256 i = 0; i < bits / 8; i++) {
result += uint256(uint8(data[pos + i])) * 2 ** (i * 8);
}
}
// @dev - Parses a syscoin tx
//
// @param txBytes - tx byte array
// Outputs
// @return output_value - amount sent to the lock address in satoshis
// @return destinationAddress - ethereum destination address
function parseTransaction(bytes memory txBytes) private pure
returns (uint, uint, address, uint32, uint8, address)
{
uint output_value;
uint32 assetGUID;
address destinationAddress;
uint32 version;
address erc20Address;
uint8 precision;
uint pos = 0;
version = bytesToUint32Flipped(txBytes, pos);
if(version != SYSCOIN_TX_VERSION_ASSET_ALLOCATION_BURN){
return (ERR_PARSE_TX_SYS, output_value, destinationAddress, assetGUID, precision, erc20Address);
}
pos = skipInputs(txBytes, 4);
(output_value, destinationAddress, assetGUID, precision, erc20Address) = scanBurns(txBytes, pos);
return (0, output_value, destinationAddress, assetGUID, precision, erc20Address);
}
function skipInputs(bytes memory txBytes, uint pos) private pure
returns (uint)
{
uint n_inputs;
uint script_len;
(n_inputs, pos) = parseVarInt(txBytes, pos);
// if dummy 0x00 is present this is a witness transaction
if(n_inputs == 0x00){
(n_inputs, pos) = parseVarInt(txBytes, pos); // flag
require(n_inputs != 0x00);
// after dummy/flag the real var int comes for txins
(n_inputs, pos) = parseVarInt(txBytes, pos);
}
require(n_inputs < 100);
for (uint i = 0; i < n_inputs; i++) {
pos += 36; // skip outpoint
(script_len, pos) = parseVarInt(txBytes, pos);
pos += script_len + 4; // skip sig_script, seq
}
return pos;
}
// scan the burn outputs and return the value and script data of first burned output.
function scanBurns(bytes memory txBytes, uint pos) private pure
returns (uint, address, uint32, uint8, address)
{
uint script_len;
uint output_value;
uint32 assetGUID = 0;
address destinationAddress;
address erc20Address;
uint8 precision;
uint n_outputs;
(n_outputs, pos) = parseVarInt(txBytes, pos);
require(n_outputs < 10);
for (uint i = 0; i < n_outputs; i++) {
pos += 8;
// varint
(script_len, pos) = parseVarInt(txBytes, pos);
if(!isOpReturn(txBytes, pos)){
// output script
pos += script_len;
output_value = 0;
continue;
}
// skip opreturn marker
pos += 1;
(output_value, destinationAddress, assetGUID, precision, erc20Address) = scanAssetDetails(txBytes, pos);
// only one opreturn data allowed per transaction
break;
}
return (output_value, destinationAddress, assetGUID, precision, erc20Address);
}
// Returns true if the tx output is an OP_RETURN output
function isOpReturn(bytes memory txBytes, uint pos) private pure
returns (bool) {
// scriptPub format is
// 0x6a OP_RETURN
return
txBytes[pos] == byte(0x6a);
}
// Returns asset data parsed from the op_return data output from syscoin asset burn transaction
function scanAssetDetails(bytes memory txBytes, uint pos) private pure
returns (uint, address, uint32, uint8, address) {
uint32 assetGUID;
address destinationAddress;
address erc20Address;
uint output_value;
uint8 precision;
uint8 op;
// vchAsset
(op, pos) = getOpcode(txBytes, pos);
// guid length should be 4 bytes
require(op == 0x04);
assetGUID = bytesToUint32(txBytes, pos);
pos += op;
// amount
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x08);
output_value = bytesToUint64(txBytes, pos);
pos += op;
// destination address
(op, pos) = getOpcode(txBytes, pos);
// ethereum contracts are 20 bytes (without the 0x)
require(op == 0x14);
destinationAddress = readEthereumAddress(txBytes, pos);
pos += op;
// precision
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x01);
precision = uint8(txBytes[pos]);
pos += op;
// erc20Address
(op, pos) = getOpcode(txBytes, pos);
require(op == 0x14);
erc20Address = readEthereumAddress(txBytes, pos);
return (output_value, destinationAddress, assetGUID, precision, erc20Address);
}
// Read the ethereum address embedded in the tx output
function readEthereumAddress(bytes memory txBytes, uint pos) private pure
returns (address) {
uint256 data;
assembly {
data := mload(add(add(txBytes, 20), pos))
}
return address(uint160(data));
}
// Read next opcode from script
function getOpcode(bytes memory txBytes, uint pos) private pure
returns (uint8, uint)
{
require(pos < txBytes.length);
return (uint8(txBytes[pos]), pos + 1);
}
// @dev - Converts a bytes of size 4 to uint32,
// e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304
function bytesToUint32Flipped(bytes memory input, uint pos) private pure returns (uint32 result) {
assembly {
let data := mload(add(add(input, 0x20), pos))
let flip := mload(0x40)
mstore8(add(flip, 0), byte(3, data))
mstore8(add(flip, 1), byte(2, data))
mstore8(add(flip, 2), byte(1, data))
mstore8(add(flip, 3), byte(0, data))
result := shr(mul(8, 28), mload(flip))
}
}
// @dev - Bitcoin-way of hashing
// @param _dataBytes - raw data to be hashed
// @return - result of applying SHA-256 twice to raw data and then flipping the bytes
function dblShaFlip(bytes memory _dataBytes) private pure returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256(abi.encodePacked(_dataBytes))))));
}
function sha256mem(bytes memory _rawBytes, uint offset, uint len) private view returns (bytes32 result) {
assembly {
// Call sha256 precompiled contract (located in address 0x02) to copy data.
// Assign to ptr the next available memory position (stored in memory position 0x40).
let ptr := mload(0x40)
if iszero(staticcall(gas, 0x02, add(add(_rawBytes, 0x20), offset), len, ptr, 0x20)) {
revert(0, 0)
}
result := mload(ptr)
}
}
// @dev - Bitcoin-way of hashing
// @param _dataBytes - raw data to be hashed
// @return - result of applying SHA-256 twice to raw data and then flipping the bytes
function dblShaFlipMem(bytes memory _rawBytes, uint offset, uint len) private view returns (uint) {
return flip32Bytes(uint(sha256(abi.encodePacked(sha256mem(_rawBytes, offset, len)))));
}
function bytesToUint64(bytes memory input, uint pos) private pure returns (uint64 result) {
result = uint64(uint8(input[pos+7])) + uint64(uint8(input[pos + 6]))*(2**8) + uint64(uint8(input[pos + 5]))*(2**16) + uint64(uint8(input[pos + 4]))*(2**24) + uint64(uint8(input[pos + 3]))*(2**32) + uint64(uint8(input[pos + 2]))*(2**40) + uint64(uint8(input[pos + 1]))*(2**48) + uint64(uint8(input[pos]))*(2**56);
}
function bytesToUint32(bytes memory input, uint pos) private pure returns (uint32 result) {
result = uint32(uint8(input[pos+3])) + uint32(uint8(input[pos + 2]))*(2**8) + uint32(uint8(input[pos + 1]))*(2**16) + uint32(uint8(input[pos]))*(2**24);
}
// @dev - convert an unsigned integer from little-endian to big-endian representation
//
// @param _input - little-endian value
// @return - input value in big-endian format
function flip32Bytes(uint _input) private pure returns (uint result) {
assembly {
let pos := mload(0x40)
mstore8(add(pos, 0), byte(31, _input))
mstore8(add(pos, 1), byte(30, _input))
mstore8(add(pos, 2), byte(29, _input))
mstore8(add(pos, 3), byte(28, _input))
mstore8(add(pos, 4), byte(27, _input))
mstore8(add(pos, 5), byte(26, _input))
mstore8(add(pos, 6), byte(25, _input))
mstore8(add(pos, 7), byte(24, _input))
mstore8(add(pos, 8), byte(23, _input))
mstore8(add(pos, 9), byte(22, _input))
mstore8(add(pos, 10), byte(21, _input))
mstore8(add(pos, 11), byte(20, _input))
mstore8(add(pos, 12), byte(19, _input))
mstore8(add(pos, 13), byte(18, _input))
mstore8(add(pos, 14), byte(17, _input))
mstore8(add(pos, 15), byte(16, _input))
mstore8(add(pos, 16), byte(15, _input))
mstore8(add(pos, 17), byte(14, _input))
mstore8(add(pos, 18), byte(13, _input))
mstore8(add(pos, 19), byte(12, _input))
mstore8(add(pos, 20), byte(11, _input))
mstore8(add(pos, 21), byte(10, _input))
mstore8(add(pos, 22), byte(9, _input))
mstore8(add(pos, 23), byte(8, _input))
mstore8(add(pos, 24), byte(7, _input))
mstore8(add(pos, 25), byte(6, _input))
mstore8(add(pos, 26), byte(5, _input))
mstore8(add(pos, 27), byte(4, _input))
mstore8(add(pos, 28), byte(3, _input))
mstore8(add(pos, 29), byte(2, _input))
mstore8(add(pos, 30), byte(1, _input))
mstore8(add(pos, 31), byte(0, _input))
result := mload(pos)
}
}
// @dev - For a valid proof, returns the root of the Merkle tree.
//
// @param _txHash - transaction hash
// @param _txIndex - transaction's index within the block it's assumed to be in
// @param _siblings - transaction's Merkle siblings
// @return - Merkle tree root of the block the transaction belongs to if the proof is valid,
// garbage if it's invalid
function computeMerkle(uint _txHash, uint _txIndex, uint[] memory _siblings) private pure returns (uint) {
uint length = _siblings.length;
uint i;
for (i = 0; i < length; i++) {
_siblings[i] = flip32Bytes(_siblings[i]);
}
i = 0;
uint resultHash = flip32Bytes(_txHash);
while (i < length) {
uint proofHex = _siblings[i];
uint left;
uint right;
if (_txIndex % 2 == 1) { // 0 means _siblings is on the right; 1 means left
left = proofHex;
right = resultHash;
} else {
left = resultHash;
right = proofHex;
}
resultHash = uint(sha256(abi.encodePacked(sha256(abi.encodePacked(left, right)))));
_txIndex /= 2;
i += 1;
}
return flip32Bytes(resultHash);
}
// @dev - extract Merkle root field from a raw Syscoin block header
//
// @param _blockHeader - Syscoin block header bytes
// @param pos - where to start reading root from
// @return - block's Merkle root in big endian format
function getHeaderMerkleRoot(bytes memory _blockHeader) public pure returns (uint) {
uint merkle;
assembly {
merkle := mload(add(add(_blockHeader, 32), 0x24))
}
return flip32Bytes(merkle);
}
// @dev - Initializes superblocks contract
//
// Initializes the superblock contract. It can only be called once.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @param _blockHeight Block height of last block in superblock
// @return Error code and superblockHash
function initialize(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId
) external returns (uint, bytes32) {
require(bestSuperblock == 0);
require(_parentId == 0);
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _timestamp, _mtpTimestamp, _lastHash, _lastBits, _parentId);
SuperblockInfo storage superblock = superblocks[superblockHash];
require(superblock.status == Status.Uninitialized);
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.timestamp = _timestamp;
superblock.mtpTimestamp = _mtpTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.submitter = msg.sender;
superblock.height = 1;
superblock.lastBits = _lastBits;
superblock.status = Status.Approved;
emit NewSuperblock(superblockHash, msg.sender);
bestSuperblock = superblockHash;
emit ApprovedSuperblock(superblockHash, msg.sender);
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Proposes a new superblock
//
// To be accepted, a new superblock needs to have its parent
// either approved or semi-approved.
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @return Error code and superblockHash
function propose(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address submitter
) external returns (uint, bytes32) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(0, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return (ERR_SUPERBLOCK_NOT_CLAIMMANAGER, 0);
}
SuperblockInfo storage parent = superblocks[_parentId];
if (parent.status != Status.SemiApproved && parent.status != Status.Approved) {
emit ErrorSuperblock(_parentId, ERR_SUPERBLOCK_BAD_PARENT + uint(parent.status));
return (ERR_SUPERBLOCK_BAD_PARENT + uint(parent.status), 0);
}
if (parent.height < getChainHeight()) {
emit ErrorSuperblock(_parentId, ERR_SUPERBLOCK_BAD_BLOCKHEIGHT);
return (ERR_SUPERBLOCK_BAD_BLOCKHEIGHT, 0);
}
bytes32 superblockHash = calcSuperblockHash(_blocksMerkleRoot, _timestamp, _mtpTimestamp, _lastHash, _lastBits, _parentId);
SuperblockInfo storage superblock = superblocks[superblockHash];
if (superblock.status == Status.Uninitialized) {
superblock.blocksMerkleRoot = _blocksMerkleRoot;
superblock.timestamp = _timestamp;
superblock.mtpTimestamp = _mtpTimestamp;
superblock.lastHash = _lastHash;
superblock.parentId = _parentId;
superblock.height = parent.height + 1;
superblock.lastBits = _lastBits;
}
superblock.status = Status.New;
superblock.submitter = submitter;
emit NewSuperblock(superblockHash, submitter);
return (ERR_SUPERBLOCK_OK, superblockHash);
}
// @dev - Confirm a proposed superblock
//
// An unchallenged superblock can be confirmed after a timeout.
// A challenged superblock is confirmed if it has enough descendants
// in the main chain.
//
// @param _superblockHash Id of the superblock to confirm
// @param _validator Address requesting superblock confirmation
// @return Error code and superblockHash
function confirm(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
if (superblock.height <= getChainHeight()) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_BLOCKHEIGHT);
return ERR_SUPERBLOCK_BAD_BLOCKHEIGHT;
}
SuperblockInfo storage parent = superblocks[superblock.parentId];
if (parent.status != Status.Approved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_PARENT);
return ERR_SUPERBLOCK_BAD_PARENT;
}
superblock.status = Status.Approved;
bestSuperblock = _superblockHash;
emit ApprovedSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - Challenge a proposed superblock
//
// A new superblock can be challenged to start a battle
// to verify the correctness of the data submitted.
//
// @param _superblockHash Id of the superblock to challenge
// @param _challenger Address requesting a challenge
// @return Error code and superblockHash
function challenge(bytes32 _superblockHash, address _challenger) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.New && superblock.status != Status.InBattle) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
if(superblock.submitter == _challenger){
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_OWN_CHALLENGE);
return ERR_SUPERBLOCK_OWN_CHALLENGE;
}
superblock.status = Status.InBattle;
emit ChallengeSuperblock(_superblockHash, _challenger);
return ERR_SUPERBLOCK_OK;
}
// @dev - Semi-approve a challenged superblock
//
// A challenged superblock can be marked as semi-approved
// if it satisfies all the queries or when all challengers have
// stopped participating.
//
// @param _superblockHash Id of the superblock to semi-approve
// @param _validator Address requesting semi approval
// @return Error code and superblockHash
function semiApprove(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.New) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
superblock.status = Status.SemiApproved;
emit SemiApprovedSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - Invalidates a superblock
//
// A superblock with incorrect data can be invalidated immediately.
// Superblocks that are not in the main chain can be invalidated
// if not enough superblocks follow them, i.e. they don't have
// enough descendants.
//
// @param _superblockHash Id of the superblock to invalidate
// @param _validator Address requesting superblock invalidation
// @return Error code and superblockHash
function invalidate(bytes32 _superblockHash, address _validator) external returns (uint) {
if (msg.sender != trustedClaimManager) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_NOT_CLAIMMANAGER);
return ERR_SUPERBLOCK_NOT_CLAIMMANAGER;
}
SuperblockInfo storage superblock = superblocks[_superblockHash];
if (superblock.status != Status.InBattle && superblock.status != Status.SemiApproved) {
emit ErrorSuperblock(_superblockHash, ERR_SUPERBLOCK_BAD_STATUS);
return ERR_SUPERBLOCK_BAD_STATUS;
}
superblock.status = Status.Invalid;
emit InvalidSuperblock(_superblockHash, _validator);
return ERR_SUPERBLOCK_OK;
}
// @dev - relays transaction `_txBytes` to ERC20Manager's processTransaction() method.
// Also logs the value of processTransaction.
// Note: callers cannot be 100% certain when an ERR_RELAY_VERIFY occurs because
// it may also have been returned by processTransaction(). Callers should be
// aware of the contract that they are relaying transactions to and
// understand what that contract's processTransaction method returns.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _txSiblings - transaction's Merkle siblings
// @param _syscoinBlockHeader - block header containing transaction
// @param _syscoinBlockIndex - block's index withing superblock
// @param _syscoinBlockSiblings - block's merkle siblings
// @param _superblockHash - superblock containing block header
function relayTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _txSiblings,
bytes memory _syscoinBlockHeader,
uint _syscoinBlockIndex,
uint[] memory _syscoinBlockSiblings,
bytes32 _superblockHash
) public returns (uint) {
// Check if Syscoin block belongs to given superblock
if (bytes32(computeMerkle(dblShaFlip(_syscoinBlockHeader), _syscoinBlockIndex, _syscoinBlockSiblings))
!= superblocks[_superblockHash].blocksMerkleRoot) {
// Syscoin block is not in superblock
emit RelayTransaction(bytes32(0), ERR_SUPERBLOCK);
return ERR_SUPERBLOCK;
}
uint txHash = verifyTx(_txBytes, _txIndex, _txSiblings, _syscoinBlockHeader, _superblockHash);
if (txHash != 0) {
uint value;
address destinationAddress;
uint ret;
uint32 assetGUID;
address erc20ContractAddress;
uint8 precision;
(ret, value, destinationAddress, assetGUID, precision, erc20ContractAddress) = parseTransaction(_txBytes);
if(ret != 0){
emit RelayTransaction(bytes32(txHash), ret);
return ret;
}
syscoinERC20Manager.processTransaction(txHash, value, destinationAddress, superblocks[_superblockHash].submitter, erc20ContractAddress, assetGUID, precision);
return value;
}
emit RelayTransaction(bytes32(0), ERR_RELAY_VERIFY);
return(ERR_RELAY_VERIFY);
}
// @dev - Checks whether the transaction given by `_txBytes` is in the block identified by `_txBlockHeaderBytes`.
// First it guards against a Merkle tree collision attack by raising an error if the transaction is exactly 64 bytes long,
// then it calls helperVerifyHash to do the actual check.
//
// @param _txBytes - transaction bytes
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _txBlockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - SHA-256 hash of _txBytes if the transaction is in the block, 0 otherwise
function verifyTx(
bytes memory _txBytes,
uint _txIndex,
uint[] memory _siblings,
bytes memory _txBlockHeaderBytes,
bytes32 _txsuperblockHash
) private returns (uint) {
uint txHash = dblShaFlip(_txBytes);
if (_txBytes.length == 64) { // todo: is check 32 also needed?
emit VerifyTransaction(bytes32(txHash), ERR_TX_64BYTE);
return 0;
}
if (helperVerifyHash(txHash, _txIndex, _siblings, _txBlockHeaderBytes, _txsuperblockHash) == 1) {
return txHash;
} else {
// log is done via helperVerifyHash
return 0;
}
}
// @dev - Checks whether the transaction identified by `_txHash` is in the block identified by `_blockHeaderBytes`
// and whether the block is in the Syscoin main chain. Transaction check is done via Merkle proof.
// Note: no verification is performed to prevent txHash from just being an
// internal hash in the Merkle tree. Thus this helper method should NOT be used
// directly and is intended to be private.
//
// @param _txHash - transaction hash
// @param _txIndex - transaction's index within the block
// @param _siblings - transaction's Merkle siblings
// @param _blockHeaderBytes - block header containing transaction
// @param _txsuperblockHash - superblock containing block header
// @return - 1 if the transaction is in the block and the block is in the main chain,
// 20020 (ERR_CONFIRMATIONS) if the block is not in the main chain,
// 20050 (ERR_MERKLE_ROOT) if the block is in the main chain but the Merkle proof fails.
function helperVerifyHash(
uint256 _txHash,
uint _txIndex,
uint[] memory _siblings,
bytes memory _blockHeaderBytes,
bytes32 _txsuperblockHash
) private returns (uint) {
//TODO: Verify superblock is in superblock's main chain
if (!isApproved(_txsuperblockHash)) {
emit VerifyTransaction(bytes32(_txHash), ERR_CHAIN);
return (ERR_CHAIN);
}
// Verify tx Merkle root
uint merkle = getHeaderMerkleRoot(_blockHeaderBytes);
if (computeMerkle(_txHash, _txIndex, _siblings) != merkle) {
emit VerifyTransaction(bytes32(_txHash), ERR_MERKLE_ROOT);
return (ERR_MERKLE_ROOT);
}
return (1);
}
// @dev - Calculate superblock hash from superblock data
//
// @param _blocksMerkleRoot Root of the merkle tree of blocks contained in a superblock
// @param _timestamp Timestamp of the last block in the superblock
// @param _mtpTimestamp Median Timestamp of the last block in the superblock
// @param _lastHash Hash of the last block in the superblock
// @param _lastBits Difficulty bits of the last block in the superblock bits
// @param _parentId Id of the parent superblock
// @return Superblock id
function calcSuperblockHash(
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId
) public pure returns (bytes32) {
return keccak256(abi.encodePacked(
_blocksMerkleRoot,
_timestamp,
_mtpTimestamp,
_lastHash,
_lastBits,
_parentId
));
}
// @dev - Returns the confirmed superblock with the most accumulated work
//
// @return Best superblock hash
function getBestSuperblock() external view returns (bytes32) {
return bestSuperblock;
}
// @dev - Returns the superblock data for the supplied superblock hash
//
function getSuperblock(bytes32 superblockHash) external view returns (
bytes32 _blocksMerkleRoot,
uint _timestamp,
uint _mtpTimestamp,
bytes32 _lastHash,
uint32 _lastBits,
bytes32 _parentId,
address _submitter,
Status _status,
uint32 _height
) {
SuperblockInfo storage superblock = superblocks[superblockHash];
return (
superblock.blocksMerkleRoot,
superblock.timestamp,
superblock.mtpTimestamp,
superblock.lastHash,
superblock.lastBits,
superblock.parentId,
superblock.submitter,
superblock.status,
superblock.height
);
}
// @dev - Returns superblock height
function getSuperblockHeight(bytes32 superblockHash) public view returns (uint32) {
return superblocks[superblockHash].height;
}
// @dev - Return superblock timestamp
function getSuperblockTimestamp(bytes32 _superblockHash) external view returns (uint) {
return superblocks[_superblockHash].timestamp;
}
// @dev - Return superblock median timestamp
function getSuperblockMedianTimestamp(bytes32 _superblockHash) external view returns (uint) {
return superblocks[_superblockHash].mtpTimestamp;
}
// @dev - Return superblock parent
function getSuperblockParentId(bytes32 _superblockHash) external view returns (bytes32) {
return superblocks[_superblockHash].parentId;
}
// @dev - Return superblock status
function getSuperblockStatus(bytes32 _superblockHash) public view returns (Status) {
return superblocks[_superblockHash].status;
}
function isApproved(bytes32 _superblockHash) private view returns (bool) {
return (getSuperblockStatus(_superblockHash) == Status.Approved);
}
function getChainHeight() public view returns (uint) {
return superblocks[bestSuperblock].height;
}
// @dev - return superblock hash at a given height in superblock main chain
//
// @param _height - superblock height
// @return - hash corresponding to block of height _height
function getSuperblockAt(uint _height) external view returns (bytes32) {
bytes32 superblockHash = bestSuperblock;
while (getSuperblockHeight(superblockHash) > _height) {
superblockHash = superblocks[superblockHash].parentId;
}
return superblockHash;
}
}
|
if dummy 0x00 is present this is a witness transaction after dummy/flag the real var int comes for txins
|
function skipInputs(bytes memory txBytes, uint pos) private pure
returns (uint)
{
uint n_inputs;
uint script_len;
(n_inputs, pos) = parseVarInt(txBytes, pos);
if(n_inputs == 0x00){
require(n_inputs != 0x00);
(n_inputs, pos) = parseVarInt(txBytes, pos);
}
require(n_inputs < 100);
for (uint i = 0; i < n_inputs; i++) {
(script_len, pos) = parseVarInt(txBytes, pos);
}
return pos;
}
| 12,794,829
|
./full_match/1/0xff368E106EA8782FaB6B2D4AD69739a60C66400E/sources/contracts/Stabilizer/Stabilizer.sol
|
Configure intial settings _minEquityRatio The minimum equity ratio can be negative. _spreadFee The fee that the protocol will get for providing the loan when the stabilizer takes debt _loanLimit How much debt a Stabilizer can take in SWEEP. _liquidatorDiscount A percentage that will be discounted in favor to the liquidator when the stabilizer is liquidated _callDelay Time in seconds after AutoCall until the Stabilizer gets defaulted if the debt is not paid in that period _autoInvestMinRatio Minimum equity ratio that should be kept to allow the execution of an auto invest _autoInvestMinAmount Minimum amount to be invested to allow the execution of an auto invest _autoInvestEnabled Represents if an auto invest execution is allowed or not _url A URL link to a Web page that describes the borrower and the asset Sets the initial configuration of the Stabilizer. This configuration will be analyzed by the protocol and if accepted, used to include the Stabilizer in the minter's whitelist of Sweep. The minimum equity ratio can not be less than 1%/
|
function configure(
int256 _minEquityRatio,
uint256 _spreadFee,
uint256 _loanLimit,
uint256 _liquidatorDiscount,
uint256 _callDelay,
int256 _autoInvestMinRatio,
uint256 _autoInvestMinAmount,
bool _autoInvestEnabled,
string calldata _url
) external onlyBorrower onlySettingsEnabled {
minEquityRatio = _minEquityRatio;
spreadFee = _spreadFee;
loanLimit = _loanLimit;
liquidatorDiscount = _liquidatorDiscount;
callDelay = _callDelay;
autoInvestMinRatio = _autoInvestMinRatio;
autoInvestMinAmount = _autoInvestMinAmount;
autoInvestEnabled = _autoInvestEnabled;
link = _url;
emit ConfigurationChanged(
_minEquityRatio,
_spreadFee,
_loanLimit,
_liquidatorDiscount,
_callDelay,
_autoInvestMinRatio,
_autoInvestMinAmount,
_autoInvestEnabled,
_url
);
}
| 3,205,017
|
./partial_match/1/0xc6cb9722D4633dC4DaAff4680f2B72CEFe110Cf9/sources/BTC.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20(unicode"Buy This Coin", unicode"BTC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 20;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 50;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 2,620,209
|
./full_match/80001/0xf494169441E0Ef3708EFA9d2E4c01BaB184a98ea/sources/StakeManager.sol
|
@inheritdoc IStakeManager/
|
function unstake(
address validator,
Token.Type token,
uint256 amount
) external {
revert ObsoletedMethod();
}
| 857,871
|
./full_match/1/0x83797D8608aA53dFcC77D350081383dF021ee5Bc/sources/contracts/NToken.sol
|
See {IERC721Metadata-symbol}./
|
function symbol() public view virtual override returns (string memory) {
return __symbol;
}
| 17,008,055
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./LeafToken.sol";
import "./LeafNft.sol";
contract LeafDapp is Ownable {
/// @dev value to go to the next level
uint constant NEW_LEVEL_VALUE = 10000;
uint constant OWNER_LEAFS = 1000000*(10 ** 18);
uint constant MIN_NB_STEPS = 1000;
uint constant MAX_LEVEL = 3;
/// @dev the NFT price
uint cost = 0.01 ether;
/// @dev max supply for 1st level NFTs
uint maxSupplyNft = 10000;
/// @dev max supply for token LEAF
uint maxSupplyLeaf = 150000000 * (10**18);
/// @dev to pause the dapp
bool paused = false;
/// @dev if can do test without time restriction
bool test = true;
/// @dev the token ERC20 LEAF
LeafToken leaf;
/// @dev the token ERC721 LNFT
LeafNft nft;
/// @param oldNbStep yesterday's step count
/// @param nbDaySuccess number of days success (+10000 steps)
/// @param level level of player 0, 1, 2 or 3
/// @param totalNbStep total number of steps
/// @param lastUpdateDate last update when player had more than 10000 steps
/// @param uriIpfs list of ipfs URIs
struct Player {
uint32 oldNbStep;
uint32 nbDaySuccess;
uint32 level;
uint totalNbStep;
uint lastUpdateDate;
string[] uriIpfs;
}
/// @dev return player from his address
mapping (address => Player) players;
/// @dev returns player validity from his address
mapping(address => bool) whitelisted;
/// @dev when new NFT was buyed
event NftBuyed(address _address, string uriIpfs);
/// @dev when LEAF was transfered
event LeafTransfer(address _address, uint amountLeaf);
/// @param _leaf the ERC20 LEAF token contract address
/// @param _nft the ERC721 LNFT token contract address
constructor(address _leaf, address _nft) {
leaf = LeafToken(_leaf);
nft = LeafNft(_nft);
}
modifier onlyPlayer() {
require (isPlayer(msg.sender), "LeafDapp : caller is not a player");
_;
}
modifier onlyOwnerOrPlayer() {
require (owner() == msg.sender ||
isPlayer(msg.sender), "LeafDapp : caller is not a player");
_;
}
/// @dev mint million LEAF for owner
function mintLeaf() external onlyOwner {
leaf.mint(maxSupplyLeaf);
leaf.transfer(msg.sender, OWNER_LEAFS);
}
/// @dev to play you have to buy the first NFT
function buyNft() payable external {
require(! isPlayer(msg.sender), "LeafDapp : this address already has an nft");
require(! whitelisted[msg.sender], "LeafDapp : this address already has an nft");
require(!paused, "LeafDapp : is paused");
uint amountTobuy = msg.value;
uint supply = nftSupply();
require(amountTobuy == cost, "LeafDApp : must be aqual to 0.01ETH");
require(supply < maxSupplyNft, "LeafDApp : the LNFT reserve is empty");
string memory newNft = nft.firstMint(msg.sender);
players[msg.sender].uriIpfs.push(newNft);
whitelisted[msg.sender] = true;
emit NftBuyed(msg.sender, newNft);
}
/// @dev update player data related to the number of steps
/// @param _nbStep number of steps per day
function stepToLeaf(uint32 _nbStep) external onlyPlayer {
require(block.timestamp - players[msg.sender].lastUpdateDate >= 1 days,
"LeafDApp : a day has not passed yet");
require(!paused, "LeafDapp : is paused");
uint amountLeaf = _nbStep / 10;
if(_nbStep >= MIN_NB_STEPS) {
players[msg.sender].lastUpdateDate = block.timestamp;
players[msg.sender].nbDaySuccess++;
players[msg.sender].oldNbStep = _nbStep;
players[msg.sender].totalNbStep += _nbStep;
if(players[msg.sender].level < MAX_LEVEL) {
setNewLevel(msg.sender);
} else {
leaf.transfer(msg.sender, amountLeaf);
}
} else {
players[msg.sender].nbDaySuccess = 0;
}
emit LeafTransfer(msg.sender, amountLeaf);
}
function stepToLeafWithoutTimestamp(uint32 _nbStep) external onlyPlayer {
require(test);
// require(block.timestamp - players[msg.sender].lastUpdateDate >= 1 days,
// "LeafDApp : a day has not passed yet");
require(!paused, "LeafDapp : is paused");
require(isPlayer(msg.sender), "LeafDApp : not a player");
uint amountLeaf = _nbStep / 10;
if(_nbStep >= MIN_NB_STEPS) {
players[msg.sender].lastUpdateDate = block.timestamp;
players[msg.sender].nbDaySuccess++;
players[msg.sender].oldNbStep = _nbStep;
players[msg.sender].totalNbStep += _nbStep;
if(players[msg.sender].level < MAX_LEVEL) {
setNewLevel(msg.sender);
} else {
leaf.transfer(msg.sender, amountLeaf);
}
} else {
players[msg.sender].nbDaySuccess = 0;
}
emit LeafTransfer(msg.sender, amountLeaf);
}
//////////////////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////
/// @dev the player levels up and receives a new NFT
/// @param _player address of player
function setNewLevel(address _player) internal {
require(isPlayer(_player));
players[_player].level++;
uint newLevel = players[_player].level * NEW_LEVEL_VALUE;
string memory newNft = nft.nextMint(_player, newLevel);
players[_player].uriIpfs.push(newNft);
}
/// @return supply for one level
function nftSupply() internal view returns(uint) {
return nft.getSupply();
}
/// @dev show if player or not
function isPlayer(address _player) internal view returns(bool) {
require(_player != address(0), "LeafDapp : must not be equal to address 0");
return whitelisted[_player];
}
//////////////////////////////////////////////////////////////////////////
// EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////
/// @dev withdraw for only owner
/// @param _amount the desired amount
function withdraw(uint _amount) external onlyOwner {
payable(msg.sender).transfer(_amount);
}
/// @return player
function getPlayer() external view onlyOwnerOrPlayer returns(Player memory){
return players[msg.sender];
}
/// @dev set pause/start the dapp
function setPause(bool _state) external onlyOwner {
paused = _state;
}
/// @dev get pause/start the dapp
function getPause() external view onlyOwner returns(bool) {
return paused;
}
/// @dev set on/off test mode
function setTest(bool _state) external onlyOwner {
test = _state;
}
/// @dev get on/off test mode
function getTest() external view onlyOwner returns(bool) {
return test;
}
/// @dev change the cost
function setCost(uint _newCost) external onlyOwner {
cost = _newCost;
}
/// @dev add to whitelist
/// @param _player the address of player
function whitelistPlayer(address _player) external onlyOwner {
require(_player != address(0), "LeafDapp : must not be equal to address 0");
whitelisted[_player] = true;
}
/// @dev remove frome whitelist
/// @param _player the address of player
function removeWhitelistPlayer(address _player) external onlyOwner {
require(_player != address(0), "LeafDapp : must not be equal to address 0");
whitelisted[_player] = false;
}
/// @return balance of _player in LEAF
/// @param _player address of player
function balancePlayer(address _player) external view onlyOwner returns(uint) {
return leaf.balanceOf(_player);
}
/// @return balance of appellant in LEAF
function balance() external view onlyPlayer returns(uint) {
return leaf.balanceOf(address(msg.sender));
}
/// @return supply of NFTs
function balanceNft() external view onlyOwnerOrPlayer returns (uint) {
return nftSupply();
}
/// @return contract balance in LEAF
function balanceDappLeaf() external view onlyOwnerOrPlayer returns(uint) {
return leaf.balanceOf(address(this));
}
/// @return contract balance in ETH
function balanceDappEth() external view onlyOwner returns(uint) {
return address(this).balance;
}
/// @return leaf
function getLeaf() external view onlyOwner returns(LeafToken) {
return leaf;
}
/// @return nft
function getNft() external view onlyOwner returns(LeafNft) {
return nft;
}
}
|
require(block.timestamp - players[msg.sender].lastUpdateDate >= 1 days, "LeafDApp : a day has not passed yet");
|
function stepToLeafWithoutTimestamp(uint32 _nbStep) external onlyPlayer {
require(test);
require(!paused, "LeafDapp : is paused");
require(isPlayer(msg.sender), "LeafDApp : not a player");
uint amountLeaf = _nbStep / 10;
if(_nbStep >= MIN_NB_STEPS) {
players[msg.sender].lastUpdateDate = block.timestamp;
players[msg.sender].nbDaySuccess++;
players[msg.sender].oldNbStep = _nbStep;
players[msg.sender].totalNbStep += _nbStep;
if(players[msg.sender].level < MAX_LEVEL) {
setNewLevel(msg.sender);
leaf.transfer(msg.sender, amountLeaf);
}
players[msg.sender].nbDaySuccess = 0;
}
emit LeafTransfer(msg.sender, amountLeaf);
}
| 929,710
|
/**
*Submitted for verification at Etherscan.io on 2020-10-07
*/
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
interface IMerkleTreeTokensVerification {
function verify(
address _leaf,
bytes32 [] calldata proof,
uint256 [] calldata positions
)
external
view
returns (bool);
}
interface ITokensTypeStorage {
function isRegistred(address _address) external view returns(bool);
function getType(address _address) external view returns(bytes32);
function isPermittedAddress(address _address) external view returns(bool);
function owner() external view returns(address);
function addNewTokenType(address _token, string calldata _type) external;
function setTokenTypeAsOwner(address _token, string calldata _type) external;
}
// Contains view methods for exchange
// We have separated the methods for the fund and for the exchange because they contain different methods.
interface PoolPortalViewInterface {
function getDataForBuyingPool(IERC20 _poolToken, uint _type, uint256 _amount)
external
view
returns(
address[] memory connectorsAddress,
uint256[] memory connectorsAmount
);
function getBacorConverterAddressByRelay(address relay)
external
view
returns(address converter);
function getBancorConnectorsAmountByRelayAmount
(
uint256 _amount,
IERC20 _relay
)
external view returns(uint256 bancorAmount, uint256 connectorAmount);
function getBancorConnectorsByRelay(address relay)
external
view
returns(address[] memory connectorsAddress);
function getBancorRatio(address _from, address _to, uint256 _amount)
external
view
returns(uint256);
function getUniswapConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
external
view
returns(uint256 ethAmount, uint256 ercAmount);
function getUniswapV2ConnectorsAmountByPoolAmount(
uint256 _amount,
address _exchange
)
external
view
returns(
uint256 tokenAmountOne,
uint256 tokenAmountTwo,
address tokenAddressOne,
address tokenAddressTwo
);
function getBalancerConnectorsAmountByPoolAmount(
uint256 _amount,
address _pool
)
external
view
returns(
address[] memory tokens,
uint256[] memory tokensAmount
);
function getUniswapTokenAmountByETH(address _token, uint256 _amount)
external
view
returns(uint256);
function getTokenByUniswapExchange(address _exchange)
external
view
returns(address);
}
interface DefiPortalInterface {
function callPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
payable
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
function callNonPayableProtocol(
address[] memory tokensToSend,
uint256[] memory amountsToSend,
bytes calldata _additionalData,
bytes32[] calldata _additionalArgs
)
external
returns(
string memory eventType,
address[] memory tokensToReceive,
uint256[] memory amountsToReceive
);
function getValue(
address _from,
address _to,
uint256 _amount
)
external
view
returns(uint256);
}
interface ExchangePortalInterface {
function trade(
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
payable
returns (uint256);
function getValue(address _from, address _to, uint256 _amount) external view returns (uint256);
function getTotalValue(
address[] calldata _fromAddresses,
uint256[] calldata _amounts,
address _to
)
external
view
returns (uint256);
}
interface IOneSplitAudit {
function swap(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 disableFlags
) external payable;
function getExpectedReturn(
IERC20 fromToken,
IERC20 toToken,
uint256 amount,
uint256 parts,
uint256 featureFlags // See contants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
/*
Bancor Network interface
*/
interface BancorNetworkInterface {
function getReturnByPath(
IERC20[] calldata _path,
uint256 _amount)
external
view
returns (uint256, uint256);
function convert(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn
) external payable returns (uint256);
function claimAndConvert(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn
) external returns (uint256);
function convertFor(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn,
address _for
) external payable returns (uint256);
function claimAndConvertFor(
IERC20[] calldata _path,
uint256 _amount,
uint256 _minReturn,
address _for
) external returns (uint256);
function conversionPath(
IERC20 _sourceToken,
IERC20 _targetToken
) external view returns (address[] memory);
}
interface IGetBancorData {
function getBancorContractAddresByName(string calldata _name) external view returns (address result);
function getBancorRatioForAssets(IERC20 _from, IERC20 _to, uint256 _amount) external view returns(uint256 result);
function getBancorPathForAssets(IERC20 _from, IERC20 _to) external view returns(address[] memory);
}
/*
* This contract do swap for ERC20 via 1inch
Also this contract allow get ratio between crypto curency assets
Also get ratio for Bancor and Uniswap pools
*/
/*
* @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 virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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 virtual 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 virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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) {
// Solidity only automatically asserts when dividing by 0
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;
}
}
contract ExchangePortal is ExchangePortalInterface, Ownable {
using SafeMath for uint256;
uint public version = 5;
// Contract for handle tokens types
ITokensTypeStorage public tokensTypes;
// Contract for merkle tree white list verification
IMerkleTreeTokensVerification public merkleTreeWhiteList;
// 1INCH
IOneSplitAudit public oneInch;
// 1 inch protocol for calldata
address public oneInchETH;
// BANCOR
IGetBancorData public bancorData;
// CoTrader portals
PoolPortalViewInterface public poolPortal;
DefiPortalInterface public defiPortal;
// 1 inch flags
// By default support Bancor + Uniswap + Uniswap v2
uint256 oneInchFlags = 570425349;
// Enum
// NOTE: You can add a new type at the end, but DO NOT CHANGE this order,
// because order has dependency in other contracts like ConvertPortal
enum ExchangeType { Paraswap, Bancor, OneInch, OneInchETH }
// This contract recognizes ETH by this address
IERC20 constant private ETH_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// Trade event
event Trade(
address trader,
address src,
uint256 srcAmount,
address dest,
uint256 destReceived,
uint8 exchangeType
);
// black list for non trade able tokens
mapping (address => bool) disabledTokens;
// Modifier to check that trading this token is not disabled
modifier tokenEnabled(IERC20 _token) {
require(!disabledTokens[address(_token)]);
_;
}
/**
* @dev contructor
*
* @param _defiPortal address of defiPortal contract
* @param _bancorData address of GetBancorData helper
* @param _poolPortal address of pool portal
* @param _oneInch address of 1inch OneSplitAudit contract
* @param _oneInchETH address of oneInch ETH contract
* @param _tokensTypes address of the ITokensTypeStorage
* @param _merkleTreeWhiteList address of the IMerkleTreeWhiteList
*/
constructor(
address _defiPortal,
address _bancorData,
address _poolPortal,
address _oneInch,
address _oneInchETH,
address _tokensTypes,
address _merkleTreeWhiteList
)
public
{
defiPortal = DefiPortalInterface(_defiPortal);
bancorData = IGetBancorData(_bancorData);
poolPortal = PoolPortalViewInterface(_poolPortal);
oneInch = IOneSplitAudit(_oneInch);
oneInchETH = _oneInchETH;
tokensTypes = ITokensTypeStorage(_tokensTypes);
merkleTreeWhiteList = IMerkleTreeTokensVerification(_merkleTreeWhiteList);
}
// EXCHANGE Functions
/**
* @dev Facilitates a trade for a SmartFund
*
* @param _source ERC20 token to convert from
* @param _sourceAmount Amount to convert from (in _source token)
* @param _destination ERC20 token to convert to
* @param _type The type of exchange to trade with
* @param _proof Merkle tree proof (if not used just set [])
* @param _positions Merkle tree positions (if not used just set [])
* @param _additionalData For additional data (if not used just set 0x0)
* @param _verifyDestanation For additional check if token in list or not
*
* @return receivedAmount The amount of _destination received from the trade
*/
function trade( //injected LOCKED ETHER
IERC20 _source,
uint256 _sourceAmount,
IERC20 _destination,
uint256 _type,
bytes32[] calldata _proof,
uint256[] calldata _positions,
bytes calldata _additionalData,
bool _verifyDestanation
)
external
override
payable
tokenEnabled(_destination)
returns (uint256 receivedAmount)
{
// throw if destanation token not in white list
if(_verifyDestanation)
_verifyToken(address(_destination), _proof, _positions);
require(_source != _destination, "source can not be destination");
// check ETH payable case
if (_source == ETH_TOKEN_ADDRESS) {
require(msg.value == _sourceAmount);
} else {
require(msg.value == 0);
}
// SHOULD TRADE PARASWAP HERE
if (_type == uint(ExchangeType.Paraswap)) {
revert("PARASWAP not supported");
}
// SHOULD TRADE BANCOR HERE
else if (_type == uint(ExchangeType.Bancor)){
receivedAmount = _tradeViaBancorNewtork(
address(_source),
address(_destination),
_sourceAmount
);
}
// SHOULD TRADE 1INCH HERE
else if (_type == uint(ExchangeType.OneInch)){
receivedAmount = _tradeViaOneInch(
address(_source),
address(_destination),
_sourceAmount,
_additionalData
);
}
// SHOULD TRADE 1INCH ETH HERE
else if (_type == uint(ExchangeType.OneInchETH)){
receivedAmount = _tradeViaOneInchETH(
address(_source),
address(_destination),
_sourceAmount,
_additionalData
);
}
else {
// unknown exchange type
revert();
}
// Additional check
require(receivedAmount > 0, "received amount can not be zerro");
// Send destination
if (_destination == ETH_TOKEN_ADDRESS) {
(msg.sender).transfer(0);
} else {
// transfer tokens received to sender
_destination.transfer(msg.sender, receivedAmount);
}
// Send remains
_sendRemains(_source, msg.sender);
// Trigger event
emit Trade(
msg.sender,
address(_source),
_sourceAmount,
address(_destination),
receivedAmount,
uint8(_type)
);
}
// Facilitates for send source remains
function _sendRemains(IERC20 _source, address _receiver) private {
// After the trade, any _source that exchangePortal holds will be sent back to msg.sender
uint256 endAmount = (_source == ETH_TOKEN_ADDRESS)
? address(this).balance
: _source.balanceOf(address(this));
// Check if we hold a positive amount of _source
if (endAmount > 0) {
if (_source == ETH_TOKEN_ADDRESS) {
payable(_receiver).transfer(0);
} else {
_source.transfer(_receiver, endAmount);
}
}
}
// Facilitates for verify destanation token input (check if token in merkle list or not)
// revert transaction if token not in list
function _verifyToken(
address _destination,
bytes32 [] memory proof,
uint256 [] memory positions)
private
view
{
bool status = merkleTreeWhiteList.verify(_destination, proof, positions);
if(!status)
revert("Dest not in white list");
}
// Facilitates trade with 1inch
function _tradeViaOneInch(
address sourceToken,
address destinationToken,
uint256 sourceAmount,
bytes memory _additionalData
)
private
returns(uint256 destinationReceived)
{
(uint256 flags,
uint256[] memory _distribution) = abi.decode(_additionalData, (uint256, uint256[]));
if(IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
oneInch.swap.value(sourceAmount)(
IERC20(sourceToken),
IERC20(destinationToken),
sourceAmount,
1,
_distribution,
flags
);
} else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(oneInch));
oneInch.swap(
IERC20(sourceToken),
IERC20(destinationToken),
sourceAmount,
1,
_distribution,
flags
);
}
destinationReceived = tokenBalance(IERC20(destinationToken));
tokensTypes.addNewTokenType(destinationToken, "CRYPTOCURRENCY");
}
// Facilitates trade with 1inch ETH
// this protocol require calldata from 1inch api
function _tradeViaOneInchETH(
address sourceToken,
address destinationToken,
uint256 sourceAmount,
bytes memory _additionalData
)
private
returns(uint256 destinationReceived)
{
bool success;
// from ETH
if(IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
(success, ) = oneInchETH.call.value(sourceAmount)(
_additionalData
);
}
// from ERC20
else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(oneInchETH));
(success, ) = oneInchETH.call(
_additionalData
);
}
// check trade status
require(success, "Fail 1inch call");
// get received amount
destinationReceived = tokenBalance(IERC20(destinationToken));
// set token type
tokensTypes.addNewTokenType(destinationToken, "CRYPTOCURRENCY");
}
// Facilitates trade with Bancor
function _tradeViaBancorNewtork(
address sourceToken,
address destinationToken,
uint256 sourceAmount
)
private
returns(uint256 returnAmount)
{
// get latest bancor contracts
BancorNetworkInterface bancorNetwork = BancorNetworkInterface(
bancorData.getBancorContractAddresByName("BancorNetwork")
);
// Get Bancor tokens path
address[] memory path = bancorData.getBancorPathForAssets(IERC20(sourceToken), IERC20(destinationToken));
// Convert addresses to ERC20
IERC20[] memory pathInERC20 = new IERC20[](path.length);
for(uint i=0; i<path.length; i++){
pathInERC20[i] = IERC20(path[i]);
}
// trade
if (IERC20(sourceToken) == ETH_TOKEN_ADDRESS) {
returnAmount = bancorNetwork.convert.value(sourceAmount)(pathInERC20, sourceAmount, 1);
}
else {
_transferFromSenderAndApproveTo(IERC20(sourceToken), sourceAmount, address(bancorNetwork));
returnAmount = bancorNetwork.claimAndConvert(pathInERC20, sourceAmount, 1);
}
tokensTypes.addNewTokenType(destinationToken, "BANCOR_ASSET");
}
/**
* @dev Transfers tokens to this contract and approves them to another address
*
* @param _source Token to transfer and approve
* @param _sourceAmount The amount to transfer and approve (in _source token)
* @param _to Address to approve to
*/
function _transferFromSenderAndApproveTo(IERC20 _source, uint256 _sourceAmount, address _to) private {
require(_source.transferFrom(msg.sender, address(this), _sourceAmount));
// reset previos approve because some tokens require allowance 0
_source.approve(_to, 0);
// approve
_source.approve(_to, _sourceAmount);
}
// VIEW Functions
function tokenBalance(IERC20 _token) private view returns (uint256) {
if (_token == ETH_TOKEN_ADDRESS)
return address(this).balance;
return _token.balanceOf(address(this));
}
/**
* @dev Gets the ratio by amount of token _from in token _to by totekn type
*
* @param _from Address of token we're converting from
* @param _to Address of token we're getting the value in
* @param _amount The amount of _from
*
* @return best price from 1inch for ERC20, or ratio for Uniswap and Bancor pools
*/
function getValue(address _from, address _to, uint256 _amount)
public
override
view
returns (uint256)
{
if(_amount > 0){
// get asset type
bytes32 assetType = tokensTypes.getType(_from);
// get value by asset type
if(assetType == bytes32("CRYPTOCURRENCY")){
return getValueViaDEXsAgregators(_from, _to, _amount);
}
else if (assetType == bytes32("BANCOR_ASSET")){
return getValueViaBancor(_from, _to, _amount);
}
else if (assetType == bytes32("UNISWAP_POOL")){
return getValueForUniswapPools(_from, _to, _amount);
}
else if (assetType == bytes32("UNISWAP_POOL_V2")){
return getValueForUniswapV2Pools(_from, _to, _amount);
}
else if (assetType == bytes32("BALANCER_POOL")){
return getValueForBalancerPool(_from, _to, _amount);
}
else{
// Unmarked type, try find value
return findValue(_from, _to, _amount);
}
}
else{
return 0;
}
}
/**
* @dev find the ratio by amount of token _from in token _to trying all available methods
*
* @param _from Address of token we're converting from
* @param _to Address of token we're getting the value in
* @param _amount The amount of _from
*
* @return best price from 1inch for ERC20, or ratio for Uniswap and Bancor pools
*/
function findValue(address _from, address _to, uint256 _amount) private view returns (uint256) {
if(_amount > 0){
// Check at first value from defi portal, maybe there are new defi protocols
// If defiValue return 0 continue check from another sources
uint256 defiValue = defiPortal.getValue(_from, _to, _amount);
if(defiValue > 0)
return defiValue;
// If 1inch return 0, check from Bancor network for ensure this is not a Bancor pool
uint256 oneInchResult = getValueViaDEXsAgregators(_from, _to, _amount);
if(oneInchResult > 0)
return oneInchResult;
// If Bancor return 0, check from Balancer network for ensure this is not Balancer asset
uint256 bancorResult = getValueViaBancor(_from, _to, _amount);
if(bancorResult > 0)
return bancorResult;
// If Balancer return 0, check from Uniswap pools for ensure this is not Uniswap pool
uint256 balancerResult = getValueForBalancerPool(_from, _to, _amount);
if(balancerResult > 0)
return balancerResult;
// If Uniswap return 0, check from Uniswap version 2 pools for ensure this is not Uniswap V2 pool
uint256 uniswapResult = getValueForUniswapPools(_from, _to, _amount);
if(uniswapResult > 0)
return uniswapResult;
// Uniswap V2 pools return 0 if these is not a Uniswap V2 pool
return getValueForUniswapV2Pools(_from, _to, _amount);
}
else{
return 0;
}
}
// helper for get value via 1inch
// in this interface can be added more DEXs aggregators
function getValueViaDEXsAgregators(
address _from,
address _to,
uint256 _amount
)
public view returns (uint256){
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get value via 1inch
if(_amount > 0){
// try get value from 1inch aggregator
return getValueViaOneInch(_from, _to, _amount);
}
else{
return 0;
}
}
// helper for get ratio between assets in 1inch aggregator
function getValueViaOneInch(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get rate
try oneInch.getExpectedReturn(
IERC20(_from),
IERC20(_to),
_amount,
10,
oneInchFlags)
returns(uint256 returnAmount, uint256[] memory distribution)
{
value = returnAmount;
}
catch{
value = 0;
}
}
// helper for get ratio between assets in Bancor network
function getValueViaBancor(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// if direction the same, just return amount
if(_from == _to)
return _amount;
// try get rate
if(_amount > 0){
try poolPortal.getBancorRatio(_from, _to, _amount) returns(uint256 result){
value = result;
}catch{
value = 0;
}
}else{
return 0;
}
}
// helper for get value via Balancer
function getValueForBalancerPool(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256 value)
{
// get value for each pool share
try poolPortal.getBalancerConnectorsAmountByPoolAmount(_amount, _from)
returns(
address[] memory tokens,
uint256[] memory tokensAmount
)
{
// convert and sum value via DEX aggregator
for(uint i = 0; i < tokens.length; i++){
value += getValueViaDEXsAgregators(tokens[i], _to, tokensAmount[i]);
}
}
catch{
value = 0;
}
}
// helper for get ratio between pools in Uniswap network
// _from - should be uniswap pool address
function getValueForUniswapPools(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256)
{
// get connectors amount
try poolPortal.getUniswapConnectorsAmountByPoolAmount(
_amount,
_from
) returns (uint256 ethAmount, uint256 ercAmount)
{
// get ERC amount in ETH
address token = poolPortal.getTokenByUniswapExchange(_from);
uint256 ercAmountInETH = getValueViaDEXsAgregators(token, address(ETH_TOKEN_ADDRESS), ercAmount);
// sum ETH with ERC amount in ETH
uint256 totalETH = ethAmount.add(ercAmountInETH);
// if _to == ETH no need additional convert, just return ETH amount
if(_to == address(ETH_TOKEN_ADDRESS)){
return totalETH;
}
// convert ETH into _to asset via 1inch
else{
return getValueViaDEXsAgregators(address(ETH_TOKEN_ADDRESS), _to, totalETH);
}
}catch{
return 0;
}
}
// helper for get ratio between pools in Uniswap network version 2
// _from - should be uniswap pool address
function getValueForUniswapV2Pools(
address _from,
address _to,
uint256 _amount
)
public
view
returns (uint256)
{
// get connectors amount by pool share
try poolPortal.getUniswapV2ConnectorsAmountByPoolAmount(
_amount,
_from
) returns (
uint256 tokenAmountOne,
uint256 tokenAmountTwo,
address tokenAddressOne,
address tokenAddressTwo
)
{
// convert connectors amount via DEX aggregator
uint256 amountOne = getValueViaDEXsAgregators(tokenAddressOne, _to, tokenAmountOne);
uint256 amountTwo = getValueViaDEXsAgregators(tokenAddressTwo, _to, tokenAmountTwo);
// return value
return amountOne + amountTwo;
}catch{
return 0;
}
}
/**
* @dev Gets the total value of array of tokens and amounts
*
* @param _fromAddresses Addresses of all the tokens we're converting from
* @param _amounts The amounts of all the tokens
* @param _to The token who's value we're converting to
*
* @return The total value of _fromAddresses and _amounts in terms of _to
*/
function getTotalValue(
address[] calldata _fromAddresses,
uint256[] calldata _amounts,
address _to)
external
override
view
returns (uint256)
{
uint256 sum = 0;
for (uint256 i = 0; i < _fromAddresses.length; i++) {
sum = sum.add(getValue(_fromAddresses[i], _to, _amounts[i]));
}
return sum;
}
// SETTERS Functions
/**
* @dev Allows the owner to disable/enable the buying of a token
*
* @param _token Token address whos trading permission is to be set
* @param _enabled New token permission
*/
function setToken(address _token, bool _enabled) external onlyOwner {
disabledTokens[_token] = _enabled;
}
// owner can change oneInch
function setNewOneInch(address _oneInch) external onlyOwner {
oneInch = IOneSplitAudit(_oneInch);
}
// owner can change oneInch
function setNewOneInchETH(address _oneInchETH) external onlyOwner {
oneInchETH = _oneInchETH;
}
// owner can set new pool portal
function setNewPoolPortal(address _poolPortal) external onlyOwner {
poolPortal = PoolPortalViewInterface(_poolPortal);
}
// owner can set new defi portal
function setNewDefiPortal(address _defiPortal) external onlyOwner {
defiPortal = DefiPortalInterface(_defiPortal);
}
// owner of portal can update 1 incg DEXs sources
function setOneInchFlags(uint256 _oneInchFlags) external onlyOwner {
oneInchFlags = _oneInchFlags;
}
// owner of portal can change getBancorData helper, for case if Bancor do some major updates
function setNewGetBancorData(address _bancorData) external onlyOwner {
bancorData = IGetBancorData(_bancorData);
}
// fallback payable function to receive ether from other contract addresses
fallback() external payable {} //injected LOCKED ETHER
}
|
owner can set new pool portal
|
function setNewPoolPortal(address _poolPortal) external onlyOwner {
poolPortal = PoolPortalViewInterface(_poolPortal);
}
| 887,758
|
./partial_match/1/0x54231C588b698dc9B91303C95c85F050DA35189B/sources/contracts/rewards/GaugeVoteRewards.sol
|
Process gauge rewards for the given epoch for mainnet _gauge Array of gauges _epoch The epoch/ This is not a current chain gauge and should be processed by processSidechainGaugeRewards instead this also covers cases where a src chain has not been set for invalid gauges Fund the extra reward distro for the next 2 epochs
|
function processGaugeRewards(uint256 _epoch, address[] calldata _gauge) external onlyDistributor {
require(_epoch <= _getCurrentEpoch(), "!epoch");
for (uint256 i = 0; i < _gauge.length; i++) {
address gauge = _gauge[i];
require(!isNoDepositGauge[gauge], "noDepositGauge");
require(getDstChainId[gauge] == lzChainId, "dstChainId!=lzChainId");
uint256 amountToSend = _calculateAmountToSend(_epoch, gauge);
Pid memory pid = getPoolId[gauge];
require(pid.isSet, "!poolId");
stashRewardDistro.fundPool(uint256(pid.value), address(aura), amountToSend, 2);
}
emit ProcessGaugeRewards(_gauge, _epoch);
}
| 9,191,389
|
./full_match/43113/0x2AB906aFb17d945E120414f47c2f99DD40d04a89/sources/LendingPool_flat.sol
|
Flash loan record how much user will have to pay back e.g. borrow 100, debt = 100.1 send borrower the tokens hand over control to borrwer repay the debt Distribute fee to token holders proportionally
|
function flashLoan(address flashLoanAddress, uint256 amount) external returns(bool){
EVRTFlashLoan flashLoanContract;
flashLoanContract = EVRTFlashLoan(flashLoanAddress);
uint256 debt = amount.mul(ONE.add(flashLoanFee)).div(ONE);
require(poolToken.transfer(msg.sender, amount), "borrow failed");
require(flashLoanContract.executeFlashLoan(poolToken, amount, debt), "flashLoan failed");
require(poolToken.transferFrom(msg.sender, address(this), debt), "repayment failed");
uint256 fee = debt.sub(amount);
uint256 available = (fee * magnitude) + scaledRemaider;
totalDividendPoints = totalDividendPoints.add(
(available).div(poolTokenBalance())
);
unclaimedDividends = unclaimedDividends.add(available);
scaledRemaider = available.mod(poolTokenBalance());
return true;
}
| 7,114,279
|
pragma solidity ^0.4.24;
/**
* @title - Crypto Skully
* ________ ___ __ ___ ___ ___ ___ ___ ___
* |\ ____\ |\ \|\ \ |\ \|\ \ |\ \ |\ \ |\ \ / /|
* \ \ \___|_ \ \ \/ /|_ \ \ \\\ \ \ \ \ \ \ \ \ \ \/ / /
* \ \_____ \ \ \ ___ \ \ \ \\\ \ \ \ \ \ \ \ \ \ / /
* \|____|\ \ \ \ \\ \ \ \ \ \\\ \ \ \ \____ \ \ \____ \/ / /
* ____\_\ \ \ \__\\ \__\ \ \_______\ \ \_______\ \ \_______\ __/ / /
* |\_________\ \|__| \|__| \|_______| \|_______| \|_______||\___/ /
* \|_________| \|___|/
*
* ---
*
* POWERED BY
* ____ _ _ _ _____ _ _
* / ___|_ __ _ _ _ __ | |_ ___ | \ | |___ /| | |
* | | | '__| | | | '_ \| __/ _ \ | \| | |_ \| | |
* | |___| | | |_| | |_) | || (_) | | |\ |___) |_|_|
* \____|_| \__, | .__/ \__\___/ |_| \_|____/(_|_)
* |___/|_|
*
* Game at https://skullylife.co/
**/
import "./auction/SkullAuction.sol";
contract SkullCore is SkullAuction {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
event Mint(address _to, uint256 attack, uint256 defend, uint256 rank, uint256 _tokenId);
event UpdateSkill(uint256 _id, uint256 _attack, uint256 _defend, uint256 _rank);
constructor () public {
// Starts paused.
paused = true;
rootAddress = msg.sender;
adminAddress = msg.sender;
// start with the mythical skull 0
_createSkull(0, 0, 0, 0, msg.sender);
}
function setNewAddress(address _v2Address) external onlyAdministrator whenPaused {
// See README.md for upgrade plan
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @notice Returns all the relevant information about a specific skull.
/// @param _id The ID of the skull of interest.
function getSkull(uint256 _id) external view returns (
uint256 birthTime,
uint256 attack,
uint256 defend,
uint256 rank,
uint256 genes
) {
uint256 skullId = _allTokensIndex[_id];
Skull storage skull = skulls[skullId];
birthTime = uint256(skull.birthTime);
attack = uint256(skull.attack);
defend = uint256(skull.defend);
rank = uint256(skull.rank);
genes = skull.genes;
}
function updateSkill(uint256 _id, uint256 _newAttack, uint256 _newDefend, uint256 _newRank) public whenNotPaused onlyUpdateAddress returns (bool){
uint256 skullId = _allTokensIndex[_id];
if (_newAttack > 0) {
skulls[skullId].attack = uint16(_newAttack);
}
if (_newDefend > 0) {
skulls[skullId].defend = uint16(_newDefend);
}
if (_newRank >= 0) {
skulls[skullId].rank = uint16(_newRank);
}
emit UpdateSkill(skullId, _newAttack, _newDefend, _newRank);
}
function unpause() public onlyAdministrator whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.setUnPaused();
}
function withdrawBalance() external onlyAdministrator {
rootAddress.transfer(address(this).balance);
}
function mint(address _to, uint256 _attack, uint256 _defend, uint256 _rank, uint256 _genes, string _tokenURI, uint256 tokenId) public whenNotPaused onlyAdministrator {
Skull memory _sklObj = Skull({
birthTime: uint64(now),
attack: uint16(_attack),
defend: uint16(_defend),
rank: uint16(_rank),
genes: _genes
});
// The new Skull is pushed onto the array and minted
// note that solidity uses 0 as a default value when an item is not found in a mapping
if (_allTokensIndex[tokenId] == 0) {
_mint(_to, tokenId);
_setTokenURI(tokenId, _tokenURI);
_allTokensIndex[tokenId] = skulls.length;
skulls.push(_sklObj);
emit Mint(_to, _attack, _defend, _rank, tokenId);
}
}
function mintMany(address _to, uint256 startId, uint256 endId) public whenNotPaused onlyAdministrator onlyOwner {
require(startId <= endId);
require(endId - startId < 10000);
for (uint256 tokenId = startId; tokenId <= endId; tokenId ++) {
uint16 attack = uint16(randomAttack(tokenId));
uint16 defend = uint16(randomDefend(tokenId + attack));
string memory tokenURI = strConcat("https://api.skullylife.co/skullies/", uint2str(tokenId));
Skull memory _sklObj = Skull({
birthTime: uint64(now),
attack: uint16(attack),
defend: uint16(defend),
rank: uint16(0),
genes: 0
});
// The new Skull is pushed onto the array and minted
// note that solidity uses 0 as a default value when an item is not found in a mapping
if (_allTokensIndex[tokenId] == 0) {
_mint(_to, tokenId);
_setTokenURI(tokenId, tokenURI);
_allTokensIndex[tokenId] = skulls.length;
skulls.push(_sklObj);
emit Mint(_to, attack, defend, 0, tokenId);
}
}
}
/// @dev setTokenURI(): Set an existing token URI.
/// @param _tokenId The token id.
/// @param _tokenURI The tokenURI string. Typically this will be a link to a json file on IPFS.
function setTokenURI(uint256 _tokenId, string _tokenURI) public whenNotPaused onlyAdministrator {
_setTokenURI(_tokenId, _tokenURI);
}
/// @dev getLatestId(): Returns the newest skull Id in the skull array.
/// @return the latest skull id.
function getLatestId() view public returns (uint256 tokenId)
{
if (skulls.length == 0) {
tokenId = 0;
} else {
tokenId = skulls.length - 1;
}
}
function randomAttack(uint256 index) private view returns (uint8) {
return uint8(30 + uint256(keccak256(block.timestamp, block.difficulty, index)) % 60); // random 30-90
}
function randomDefend(uint256 index) private view returns (uint8) {
return uint8(30 + uint256(keccak256(block.timestamp, block.difficulty, index)) % 30); // random 30-60
}
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
|
getLatestId(): Returns the newest skull Id in the skull array. return the latest skull id.
|
function getLatestId() view public returns (uint256 tokenId)
{
if (skulls.length == 0) {
tokenId = 0;
tokenId = skulls.length - 1;
}
}
| 5,391,709
|
pragma solidity ^0.4.16;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
mapping(address => bool) internal owners;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owners[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owners[msg.sender] == true);
_;
}
function addOwner(address newAllowed) onlyOwner public {
owners[newAllowed] = true;
}
function removeOwner(address toRemove) onlyOwner public {
owners[toRemove] = false;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BigToken is ERC20, Ownable {
using SafeMath for uint256;
string public name = "Big Token";
string public symbol = "BIG";
uint256 public decimals = 18;
uint256 public mintPerBlock = 333333333333333;
struct BigTransaction {
uint blockNumber;
uint256 amount;
}
uint public commissionPercent = 10;
uint256 public totalTransactions = 0;
bool public enabledMint = true;
uint256 public totalMembers;
mapping(address => mapping (address => uint256)) internal allowed;
mapping(uint256 => BigTransaction) public transactions;
mapping(address => uint256) public balances;
mapping(address => uint) public lastMint;
mapping(address => bool) invested;
mapping(address => bool) public confirmed;
mapping(address => bool) public members;
event Mint(address indexed to, uint256 amount);
event Commission(uint256 amount);
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 currentBalance = balances[msg.sender];
uint256 balanceToMint = getBalanceToMint(msg.sender);
uint256 commission = _value * commissionPercent / 100;
require((_value + commission) <= (currentBalance + balanceToMint));
if(balanceToMint > 0){
currentBalance = currentBalance.add(balanceToMint);
Mint(msg.sender, balanceToMint);
lastMint[msg.sender] = block.number;
totalSupply = totalSupply.add(balanceToMint);
}
if(block.number == transactions[totalTransactions - 1].blockNumber) {
transactions[totalTransactions - 1].amount = transactions[totalTransactions - 1].amount + (commission / totalMembers);
} else {
uint transactionID = totalTransactions++;
transactions[transactionID] = BigTransaction(block.number, commission / totalMembers);
}
balances[msg.sender] = currentBalance.sub(_value + commission);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
uint256 currentBalance = balances[_from];
uint256 balanceToMint = getBalanceToMint(_from);
uint256 commission = _value * commissionPercent / 100;
require((_value + commission) <= (currentBalance + balanceToMint));
if(balanceToMint > 0){
currentBalance = currentBalance.add(balanceToMint);
Mint(_from, balanceToMint);
lastMint[_from] = block.number;
totalSupply = totalSupply.add(balanceToMint);
}
if(block.number == transactions[totalTransactions - 1].blockNumber) {
transactions[totalTransactions - 1].amount = transactions[totalTransactions - 1].amount + (commission / totalMembers);
} else {
uint transactionID = totalTransactions++;
transactions[transactionID] = BigTransaction(block.number, commission / totalMembers);
}
balances[_from] = currentBalance.sub(_value + commission);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
if(lastMint[_owner] != 0){
return balances[_owner] + getBalanceToMint(_owner);
} else {
return balances[_owner];
}
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* 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
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function refreshBalance(address _address) public returns (uint256){
if(!members[_address]) return;
uint256 balanceToMint = getBalanceToMint(_address);
totalSupply = totalSupply.add(balanceToMint);
balances[_address] = balances[_address] + balanceToMint;
lastMint[_address] = block.number;
}
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
function getBalanceToMint(address _address) public constant returns (uint256){
if(!enabledMint) return 0;
if(!members[_address]) return 0;
if(lastMint[_address] == 0) return 0;
uint256 balanceToMint = (block.number - lastMint[_address]) * mintPerBlock;
for(uint i = totalTransactions - 1; i >= 0; i--){
if(block.number == transactions[i].blockNumber) continue;
if(transactions[i].blockNumber < lastMint[_address]) return balanceToMint;
if(transactions[i].amount > mintPerBlock) {
balanceToMint = balanceToMint.add(transactions[i].amount - mintPerBlock);
}
}
return balanceToMint;
}
function stopMint() public onlyOwner{
enabledMint = false;
}
function startMint() public onlyOwner{
enabledMint = true;
}
function confirm(address _address) onlyOwner public {
confirmed[_address] = true;
if(!members[_address] && invested[_address]){
members[_address] = true;
totalMembers = totalMembers.add(1);
setLastMint(_address, block.number);
}
}
function unconfirm(address _address) onlyOwner public {
confirmed[_address] = false;
if(members[_address]){
members[_address] = false;
totalMembers = totalMembers.sub(1);
}
}
function setLastMint(address _address, uint _block) onlyOwner public{
lastMint[_address] = _block;
}
function setCommission(uint _commission) onlyOwner public{
commissionPercent = _commission;
}
function setMintPerBlock(uint256 _mintPerBlock) onlyOwner public{
mintPerBlock = _mintPerBlock;
}
function setInvested(address _address) onlyOwner public{
invested[_address] = true;
if(confirmed[_address] && !members[_address]){
members[_address] = true;
totalMembers = totalMembers.add(1);
refreshBalance(_address);
}
}
function isMember(address _address) public constant returns(bool){
return members[_address];
}
}
contract Crowdsale is Ownable{
using SafeMath for uint;
BigToken public token;
uint public collected;
address public benefeciar;
function Crowdsale(address _token, address _benefeciar){
token = BigToken(_token);
benefeciar = _benefeciar;
owners[msg.sender] = true;
}
function () payable {
require(msg.value >= 0.01 ether);
uint256 amount = msg.value / 0.01 ether * 1 ether;
if(msg.value >= 100 ether && msg.value < 500 ether) amount = amount * 11 / 10;
if(msg.value >= 500 ether && msg.value < 1000 ether) amount = amount * 12 / 10;
if(msg.value >= 1000 ether && msg.value < 5000 ether) amount = amount * 13 / 10;
if(msg.value >= 5000 ether && msg.value < 10000 ether) amount = amount * 14 / 10;
if(msg.value >= 10000 ether) amount = amount * 15 / 10;
collected = collected.add(msg.value);
token.mint(msg.sender, amount);
token.setInvested(msg.sender);
}
function confirmAddress(address _address) public onlyOwner{
token.confirm(_address);
}
function unconfirmAddress(address _address) public onlyOwner{
token.unconfirm(_address);
}
function setBenefeciar(address _benefeciar) public onlyOwner{
benefeciar = _benefeciar;
}
function withdraw() public onlyOwner{
benefeciar.transfer(this.balance);
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 currentBalance = balances[msg.sender];
uint256 balanceToMint = getBalanceToMint(msg.sender);
uint256 commission = _value * commissionPercent / 100;
require((_value + commission) <= (currentBalance + balanceToMint));
if(balanceToMint > 0){
currentBalance = currentBalance.add(balanceToMint);
Mint(msg.sender, balanceToMint);
lastMint[msg.sender] = block.number;
totalSupply = totalSupply.add(balanceToMint);
}
if(block.number == transactions[totalTransactions - 1].blockNumber) {
transactions[totalTransactions - 1].amount = transactions[totalTransactions - 1].amount + (commission / totalMembers);
uint transactionID = totalTransactions++;
transactions[transactionID] = BigTransaction(block.number, commission / totalMembers);
}
balances[msg.sender] = currentBalance.sub(_value + commission);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 12,700,550
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
contract Memberships is ERC721, ERC721Enumerable, Pausable, Ownable {
using Counters for Conters.Counter;
using Strings for uint256;
// TODO local where you storage data
string _baseTokenURI = "ipfs://your-CID/";
// TODO choice the price of membershisp
uint256 private _price = 0.1 ether;
// TODO for team
uint256 public constant RESERVED_FOUNDING_MEMBERS = 10;
uint256 public constant FOUNDING_MEMBERS_SUPPLY = 100;
Counters.Counter private _tokenIdCounter;
Counters.Counter private _subscriptionCounter;
// store price and duration of membership
struct SubscripitonPlan {
uint256 price;
uint256 duration;
}
// available plans
mapping (uint256 => SubscripitonPlan) subscripitonPlans;
// store the time of an address membership
mapping (address => uint256) subscriptionExpiration;
event Mint(address indexed _minterMember, uint256tokenId);
event Subscription(address _subscrMember, SubscripitonPlan Plan, uint256 timestamp, uint256 expireAt, uint subscriptionCounter);
constructor() ERC721("Your Memberships", "SYMBOL") {
//you can set here how many subcription plans you want
subscripitonPlans[0] = SubscripitonPlan(0.15 ether, 30 days);
subscripitonPlans[1] = SubscripitonPlan(0.4 ether, 90 days);
subscripitonPlans[2] = SubscripitonPlan(1 ether, 365 days);
for(uint i = 0; i < RESERVED_FOUNDING_MEMBERS; i++){
_safeMint(msg.sender);
}
}
// owner can edit and add a subscription plan
function updateSubscriptionPlan(uint256 index, SubscriptionPlan memory plan) public onlyOnwer {
subscripitonPlans[index] = plan;
}
function _getSubscriptionPlan(uint256 index) private view returns(SubscripitonPlan memory) {
SubscripitonPlan memory plan = subscripitonPlans[index];
require(plan.duration > 0, "Subscription plan does not exist");
return plan;
}
function getSubscriptionPlan(uint256 index) external view returns(SubscriptionPlan memory) {
return _getSubscriptionPlan(index);
}
function subscribe(address _to, uint256 planIndex)whenNotPaused public payable {
SubscriptionPlan memory plan = _getSubscriptionPlan(planIndex);
require(plan.price == msg.value, "wrong amount sent");
require(plan.duration > 0, "Subscription plan does not exist");
// current time
uint256 startingDate = block.timestamp;
// check if _to address already has a sub active
if(_hasActiveSubscription(_to)) {
startingDate = subscriptionExpiration[_to];
}
// set the expiry date
uint256 expiresAt = startingDate + plan.duration;
// save the expiry date of the _to on the map
subscriptionExpiration[_to] = expiresAt;
_subscriptionCounter.increment();
emit Subscription(_to, plan, block.timestamp, expiresAt, _subscriptionCounter.current());
}
// will return true if the address was active
// will return 0 if the address never had a subscription
function _hasActiveSubscription(address _address) private view returns(bool) {
return subscriptionExpiration[_address] > block.timestamp;
}
function hasActiveSubscription(address _address) external view returns(bool) {
return _hasActiveSubscription(_address);
}
function mint(address _to) whenNotPaused public payable {
require(msg.value >= _price, "Insuficient funds");
require(_tokenIdCounter.current() < FOUNDING_MEMBERS_SUPPLY, "Can't mint over supply limit");
require(BalanceOf(_to) == 0, "Can't mint more than one membership");
_tokenIdCounter.increment();
_safeMint(_to, _tokenIdCounter.current());
emit Mint(_to, _tokenIdCounter.current());
}
function getBalance() external view returns (uint256) {
return _price;
}
function setPrice(uint256 price) public OnlyOwner {
_price = price;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function _baseURI() internal override view returns(string memory) {
return _baseTokenURI;
}
function pause() public onlyOwner whenNotPaused {
_pause();
}
function unpause() public onlyOwner whenPaused {
_unpause();
}
function _safeMint(address to) public onlyOwner {
_tokenIdCounter.increment();
_safeMint(to, _tokenIdCounter.current());
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function hasFoundingMemberToken (address wallet) public view returns(bool){
return balanceOf(wallet) > 0;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns(bool) {
return super.supportsInterface(interfaceId);
}
}
|
will return true if the address was active will return 0 if the address never had a subscription
|
function _hasActiveSubscription(address _address) private view returns(bool) {
return subscriptionExpiration[_address] > block.timestamp;
}
| 12,544,475
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../../lib/ConsumerBase.sol";
contract MockBadConsumerInfiniteGas is ConsumerBase {
using SafeMath for uint256;
uint256 public price;
bytes32 public requestId;
constructor(address _router, address _xfund)
ConsumerBase(_router, _xfund) { }
function getData(address _dataProvider, uint256 _fee, bytes32 _data) external {
_requestData(_dataProvider, _fee, _data);
}
function receiveData(
uint256 _price,
bytes32 _requestId
)
internal override {
while(true){}
// will never get here, but stops compiler warnings
price = _price;
requestId = _requestId;
}
}
|
will never get here, but stops compiler warnings
|
function receiveData(
uint256 _price,
bytes32 _requestId
)
internal override {
price = _price;
requestId = _requestId;
}
| 14,097,069
|
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* @dev This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract BuyLimits {
event LogLimitsChanged(uint _minBuy, uint _maxBuy);
// Variables holding the min and max payment in wei
uint public minBuy; // min buy in wei
uint public maxBuy; // max buy in wei, 0 means no maximum
/*
** Modifier, reverting if not within limits.
*/
modifier isWithinLimits(uint _amount) {
require(withinLimits(_amount));
_;
}
/*
** @dev Constructor, define variable:
*/
function BuyLimits(uint _min, uint _max) public {
_setLimits(_min, _max);
}
/*
** @dev Check TXs value is within limits:
*/
function withinLimits(uint _value) public view returns(bool) {
if (maxBuy != 0) {
return (_value >= minBuy && _value <= maxBuy);
}
return (_value >= minBuy);
}
/*
** @dev set limits logic:
** @param _min set the minimum buy in wei
** @param _max set the maximum buy in wei, 0 indeicates no maximum
*/
function _setLimits(uint _min, uint _max) internal {
if (_max != 0) {
require (_min <= _max); // Sanity Check
}
minBuy = _min;
maxBuy = _max;
emit LogLimitsChanged(_min, _max);
}
}
/**
* @title DAOstackPresale
* @dev A contract to allow only whitelisted followers to participate in presale.
*/
contract DAOstackPreSale is Pausable,BuyLimits,Whitelist {
event LogFundsReceived(address indexed _sender, uint _amount);
address public wallet;
/**
* @dev Constructor.
* @param _wallet Address where the funds are transfered to
* @param _minBuy Address where the funds are transfered to
* @param _maxBuy Address where the funds are transfered to
*/
function DAOstackPreSale(address _wallet, uint _minBuy, uint _maxBuy)
public
BuyLimits(_minBuy, _maxBuy)
{
// Set wallet:
require(_wallet != address(0));
wallet = _wallet;
}
/**
* @dev Fallback, funds coming in are transfered to wallet
*/
function () payable whenNotPaused onlyWhitelisted isWithinLimits(msg.value) external {
wallet.transfer(msg.value);
emit LogFundsReceived(msg.sender, msg.value);
}
/*
** @dev Drain function, in case of failure. Contract should not hold eth anyhow.
*/
function drain() external {
wallet.transfer((address(this)).balance);
}
}
|
Fallback, funds coming in are transfered to wallet/
|
function () payable whenNotPaused onlyWhitelisted isWithinLimits(msg.value) external {
wallet.transfer(msg.value);
emit LogFundsReceived(msg.sender, msg.value);
}
| 2,180,614
|
pragma solidity ^0.4.15;
// File: contracts/interfaces/IEditions.sol
contract IEditions {
function createEdition(uint _tokenId) external;
function pendingEditionsOf(address _of) public constant returns (
uint[] tokens,
uint[] startedAt,
uint[] completedAt,
uint8[] currentCounts,
uint8[] limitCounts
);
function counter(uint _tokenId) public
constant returns (uint8 current, uint8 limit);
function signature() external constant returns (uint _signature);
}
// File: contracts/interfaces/IStorage.sol
contract IStorage {
function isOwner(address _address) public constant returns (bool);
function isAllowed(address _address) external constant returns (bool);
function developer() public constant returns (address);
function setDeveloper(address _address) public;
function addAdmin(address _address) public;
function isAdmin(address _address) public constant returns (bool);
function removeAdmin(address _address) public;
function contracts(uint _signature) public returns (address _address);
function exists(uint _tokenId) external constant returns (bool);
function paintingsCount() public constant returns (uint);
function increaseOwnershipTokenCount(address _address) public;
function decreaseOwnershipTokenCount(address _address) public;
function setOwnership(uint _tokenId, address _address) public;
function getPainting(uint _tokenId)
external constant returns (address, uint, uint, uint, uint8, uint8);
function createPainting(
address _owner,
uint _tokenId,
uint _parentId,
uint8 _generation,
uint8 _speed,
uint _artistId,
uint _releasedAt) public;
function approve(uint _tokenId, address _claimant) external;
function isApprovedFor(uint _tokenId, address _claimant)
external constant returns (bool);
function createEditionMeta(uint _tokenId) public;
function getPaintingOwner(uint _tokenId)
external constant returns (address);
function getPaintingGeneration(uint _tokenId)
public constant returns (uint8);
function getPaintingSpeed(uint _tokenId)
external constant returns (uint8);
function getPaintingArtistId(uint _tokenId)
public constant returns (uint artistId);
function getOwnershipTokenCount(address _address)
external constant returns (uint);
function isReady(uint _tokenId) public constant returns (bool);
function getPaintingIdAtIndex(uint _index) public constant returns (uint);
function lastEditionOf(uint _index) public constant returns (uint);
function getPaintingOriginal(uint _tokenId)
external constant returns (uint);
function canBeBidden(uint _tokenId) public constant returns (bool _can);
function addAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration,
address _seller) public;
function addReleaseAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _startedAt,
uint _duration) public;
function initAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _startedAt,
uint _duration,
address _seller,
bool _byTeam) public;
function _isOnAuction(uint _tokenId) internal constant returns (bool);
function isOnAuction(uint _tokenId) external constant returns (bool);
function removeAuction(uint _tokenId) public;
function getAuction(uint256 _tokenId)
external constant returns (
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt);
function getAuctionSeller(uint256 _tokenId)
public constant returns (address);
function getAuctionEnd(uint _tokenId)
public constant returns (uint);
function canBeCanceled(uint _tokenId) external constant returns (bool);
function getAuctionsCount() public constant returns (uint);
function getTokensOnAuction() public constant returns (uint[]);
function getTokenIdAtIndex(uint _index) public constant returns (uint);
function getAuctionStartedAt(uint256 _tokenId) public constant returns (uint);
function getOffsetIndex() public constant returns (uint);
function nextOffsetIndex() public returns (uint);
function canCreateEdition(uint _tokenId, uint8 _generation)
public constant returns (bool);
function isValidGeneration(uint8 _generation)
public constant returns (bool);
function increaseGenerationCount(uint _tokenId, uint8 _generation) public;
function getEditionsCount(uint _tokenId) external constant returns (uint8[3]);
function setLastEditionOf(uint _tokenId, uint _editionId) public;
function setEditionLimits(uint _tokenId, uint8 _gen1, uint8 _gen2, uint8 _gen3) public;
function getEditionLimits(uint _tokenId) external constant returns (uint8[3]);
function hasEditionInProgress(uint _tokenId) external constant returns (bool);
function hasEmptyEditionSlots(uint _tokenId) external constant returns (bool);
function setPaintingName(uint _tokenId, string _name) public;
function setPaintingArtist(uint _tokenId, string _name) public;
function purgeInformation(uint _tokenId) public;
function resetEditionLimits(uint _tokenId) public;
function resetPainting(uint _tokenId) public;
function decreaseSpeed(uint _tokenId) public;
function isCanceled(uint _tokenId) public constant returns (bool _is);
function totalPaintingsCount() public constant returns (uint _total);
function isSecondary(uint _tokenId) public constant returns (bool _is);
function secondarySaleCut() public constant returns (uint8 _cut);
function sealForChanges(uint _tokenId) public;
function canBeChanged(uint _tokenId) public constant returns (bool _can);
function getPaintingName(uint _tokenId) public constant returns (string);
function getPaintingArtist(uint _tokenId) public constant returns (string);
function signature() external constant returns (bytes4);
}
// File: contracts/libs/Ownable.sol
/**
* @title Ownable
* @dev Manages ownership of the contracts
*/
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function isOwner(address _address) public constant returns (bool) {
return _address == owner;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
// File: contracts/libs/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function _pause() internal whenNotPaused {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function _unpause() internal whenPaused {
paused = false;
Unpause();
}
}
// File: contracts/libs/BitpaintingBase.sol
contract BitpaintingBase is Pausable {
/*** EVENTS ***/
event Create(uint _tokenId,
address _owner,
uint _parentId,
uint8 _generation,
uint _createdAt,
uint _completedAt);
event Transfer(address from, address to, uint256 tokenId);
IStorage public bitpaintingStorage;
modifier canPauseUnpause() {
require(msg.sender == owner || msg.sender == bitpaintingStorage.developer());
_;
}
function setBitpaintingStorage(address _address) public onlyOwner {
require(_address != address(0));
bitpaintingStorage = IStorage(_address);
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public canPauseUnpause whenNotPaused {
super._pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() external canPauseUnpause whenPaused {
super._unpause();
}
function canUserReleaseArtwork(address _address)
public constant returns (bool _can) {
return (bitpaintingStorage.isOwner(_address)
|| bitpaintingStorage.isAdmin(_address)
|| bitpaintingStorage.isAllowed(_address));
}
function canUserCancelArtwork(address _address)
public constant returns (bool _can) {
return (bitpaintingStorage.isOwner(_address)
|| bitpaintingStorage.isAdmin(_address));
}
modifier canReleaseArtwork() {
require(canUserReleaseArtwork(msg.sender));
_;
}
modifier canCancelArtwork() {
require(canUserCancelArtwork(msg.sender));
_;
}
/// @dev Assigns ownership of a specific Painting to an address.
function _transfer(address _from, address _to, uint256 _tokenId)
internal {
bitpaintingStorage.setOwnership(_tokenId, _to);
Transfer(_from, _to, _tokenId);
}
function _createOriginalPainting(uint _tokenId, uint _artistId, uint _releasedAt) internal {
address _owner = owner;
uint _parentId = 0;
uint8 _generation = 0;
uint8 _speed = 10;
_createPainting(_owner, _tokenId, _parentId, _generation, _speed, _artistId, _releasedAt);
}
function _createPainting(
address _owner,
uint _tokenId,
uint _parentId,
uint8 _generation,
uint8 _speed,
uint _artistId,
uint _releasedAt
)
internal
{
require(_tokenId == uint256(uint32(_tokenId)));
require(_parentId == uint256(uint32(_parentId)));
require(_generation == uint256(uint8(_generation)));
bitpaintingStorage.createPainting(
_owner, _tokenId, _parentId, _generation, _speed, _artistId, _releasedAt);
uint _createdAt;
uint _completedAt;
(,,_createdAt, _completedAt,,) = bitpaintingStorage.getPainting(_tokenId);
// emit the create event
Create(
_tokenId,
_owner,
_parentId,
_generation,
_createdAt,
_completedAt
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, _tokenId);
}
}
// File: contracts/libs/ERC721.sol
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public constant returns (uint256 total);
function balanceOf(address _owner) public constant returns (uint256 balance);
function ownerOf(uint256 _tokenId) external constant returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external constant returns (bool);
}
// File: contracts/libs/ERC721Metadata.sol
/// @title The external contract that is responsible for generating metadata for the kitties,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public constant returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
// File: contracts/libs/PaintingOwnership.sol
contract PaintingOwnership is BitpaintingBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "BitPaintings";
string public constant symbol = "BP";
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external constant returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyOwner {
erc721Metadata = ERC721Metadata(_contractAddress);
}
function _owns(address _claimant, uint256 _tokenId) internal constant returns (bool) {
return bitpaintingStorage.getPaintingOwner(_tokenId) == _claimant;
}
function balanceOf(address _owner) public constant returns (uint256 count) {
return bitpaintingStorage.getOwnershipTokenCount(_owner);
}
function _approve(uint256 _tokenId, address _approved) internal {
bitpaintingStorage.approve(_tokenId, _approved);
}
function _approvedFor(address _claimant, uint256 _tokenId)
internal constant returns (bool) {
return bitpaintingStorage.isApprovedFor(_tokenId, _claimant);
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external whenNotPaused {
_transferFrom(_from, _to, _tokenId);
}
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public constant returns (uint) {
return bitpaintingStorage.paintingsCount();
}
function ownerOf(uint256 _tokenId)
external constant returns (address) {
return _ownerOf(_tokenId);
}
function _ownerOf(uint256 _tokenId)
internal constant returns (address) {
return bitpaintingStorage.getPaintingOwner(_tokenId);
}
function tokensOfOwner(address _owner)
external constant returns(uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
}
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCats = totalSupply();
uint256 resultIndex = 0;
uint256 paintingId;
for (paintingId = 1; paintingId <= totalCats; paintingId++) {
if (bitpaintingStorage.getPaintingOwner(paintingId) == _owner) {
result[resultIndex] = paintingId;
resultIndex++;
}
}
return result;
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private constant {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private constant returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Kitty whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external constant returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
function withdraw() external onlyOwner {
owner.transfer(this.balance);
}
}
// File: contracts/BitpaintingEditions.sol
contract BitpaintingEditions is PaintingOwnership, IEditions {
event EditionCreated(
address creator,
uint parentId,
uint editionId,
uint8 parentSpeed);
function createEdition(uint _tokenId) external whenNotPaused {
address creator = msg.sender;
require(creator == _ownerOf(_tokenId));
require(bitpaintingStorage.isReady(_tokenId));
require(!bitpaintingStorage.hasEditionInProgress(_tokenId));
require(bitpaintingStorage.hasEmptyEditionSlots(_tokenId));
require(!bitpaintingStorage.isOnAuction(_tokenId));
bitpaintingStorage.createEditionMeta(_tokenId);
uint editionId = bitpaintingStorage.getOffsetIndex();
uint8 _generation =
bitpaintingStorage.getPaintingGeneration(_tokenId) + 1;
uint8 _speed = 10;
uint _artistId = bitpaintingStorage.getPaintingArtistId(_tokenId);
_createPainting(creator, editionId, _tokenId, _generation, _speed, _artistId, now + 1);
bitpaintingStorage.decreaseSpeed(_tokenId);
uint8 speed = bitpaintingStorage.getPaintingSpeed(_tokenId);
EditionCreated(creator, _tokenId, editionId, speed);
}
function pendingEditionsOf(address _of) public constant returns (
uint[] tokens,
uint[] startedAt,
uint[] completedAt,
uint8[] currentCounts,
uint8[] limitCounts
) {
uint tokenCount = totalSupply();
uint length = balanceOf(_of);
uint pointer;
tokens = new uint[](length);
startedAt = new uint[](length);
completedAt = new uint[](length);
currentCounts = new uint8[](length);
limitCounts = new uint8[](length);
for(uint index = 0; index < tokenCount; index++) {
uint tokenId = bitpaintingStorage.getPaintingIdAtIndex(index);
if (tokenId == 0) {
continue;
}
if (_ownerOf(tokenId) != _of) {
continue;
}
if (bitpaintingStorage.isReady(tokenId)) {
continue;
}
uint _startedAt;
uint _completedAt;
(,,_startedAt, _completedAt,,) = bitpaintingStorage.getPainting(tokenId);
uint8 _current;
uint8 _limit;
(_current, _limit) = counter(tokenId);
tokens[pointer] = tokenId;
startedAt[pointer] = _startedAt;
completedAt[pointer] = _completedAt;
currentCounts[pointer] = _current;
limitCounts[pointer] = _limit;
pointer++;
}
}
function counter(uint _tokenId) public
constant returns (uint8 current, uint8 limit) {
uint8 gen = bitpaintingStorage.getPaintingGeneration(_tokenId);
if (gen == 0) {
current = 1;
limit = 1;
} else {
uint original = bitpaintingStorage.getPaintingOriginal(_tokenId);
uint8[3] memory counts = bitpaintingStorage.getEditionsCount(original);
uint8[3] memory limits = bitpaintingStorage.getEditionLimits(original);
current = counts[gen - 1];
limit = limits[gen - 1];
}
}
function signature() external constant returns (uint _signature) {
return uint(keccak256("editions"));
}
}
|
Assigns ownership of a specific Painting to an address.
|
function _transfer(address _from, address _to, uint256 _tokenId)
internal {
bitpaintingStorage.setOwnership(_tokenId, _to);
Transfer(_from, _to, _tokenId);
}
| 13,000,016
|
pragma solidity ^0.6.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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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);
}
}
}
}
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 virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
/**
* @dev Implementation of the {IERC20} 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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-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 ERC20 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 {IERC20-approve}.
*/
contract XDEX is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @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, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-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 virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* 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 virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: 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 {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 {IERC20-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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @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 virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: 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) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].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 virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: 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 virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, 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:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount) internal virtual { }
}
|
See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}; 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 virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
| 5,431
|
./partial_match/56/0x9d34F2C6D072388afA2cAbEc1BfBe99666fb85e2/sources/StratHomora.sol
|
Return reward multiplier over the given _from to _to block. View function to see pending ALPACAs on frontend. Deposit LP tokens to MasterChef for ALPACA allocation. Withdraw LP tokens from MasterChef. Withdraw LP tokens from MasterChef. Stake ALPACA tokens to MasterChef Withdraw ALPACA tokens from STAKING. Withdraw without caring about rewards. EMERGENCY ONLY.
|
interface IAlpacaToken {
function lockOf(address _address) external;
function unlock() external;
}
| 11,290,352
|
// Verified using https://dapp.tools
// hevm: flattened sources of src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol
pragma solidity =0.6.7 >=0.6.0 <0.8.0 >=0.6.7 <0.7.0;
////// src/interfaces/CoinJoinLike.sol
/* pragma solidity 0.6.7; */
abstract contract CoinJoinLike {
function systemCoin() virtual public view returns (address);
function safeEngine() virtual public view returns (address);
function join(address, uint256) virtual external;
}
////// src/interfaces/CollateralJoinLike.sol
/* pragma solidity ^0.6.7; */
abstract contract CollateralJoinLike {
function safeEngine() virtual public view returns (address);
function collateralType() virtual public view returns (bytes32);
function collateral() virtual public view returns (address);
function decimals() virtual public view returns (uint256);
function contractEnabled() virtual public view returns (uint256);
function join(address, uint256) virtual external;
}
////// src/interfaces/ERC20Like.sol
/* pragma solidity ^0.6.7; */
abstract contract ERC20Like {
function approve(address guy, uint wad) virtual public returns (bool);
function transfer(address dst, uint wad) virtual public returns (bool);
function balanceOf(address) virtual external view returns (uint256);
function transferFrom(address src, address dst, uint wad)
virtual
public
returns (bool);
}
////// src/interfaces/GebSafeManagerLike.sol
/* pragma solidity ^0.6.7; */
abstract contract GebSafeManagerLike {
function safes(uint256) virtual public view returns (address);
function ownsSAFE(uint256) virtual public view returns (address);
function safeCan(address,uint256,address) virtual public view returns (uint256);
}
////// src/interfaces/LiquidationEngineLike.sol
/* pragma solidity ^0.6.7; */
abstract contract LiquidationEngineLike_3 {
function safeSaviours(address) virtual public view returns (uint256);
}
////// src/interfaces/OracleRelayerLike.sol
/* pragma solidity ^0.6.7; */
abstract contract OracleRelayerLike_2 {
function collateralTypes(bytes32) virtual public view returns (address, uint256, uint256);
function liquidationCRatio(bytes32) virtual public view returns (uint256);
function redemptionPrice() virtual public returns (uint256);
}
////// src/interfaces/PriceFeedLike.sol
/* pragma solidity ^0.6.7; */
abstract contract PriceFeedLike {
function priceSource() virtual public view returns (address);
function read() virtual public view returns (uint256);
function getResultWithValidity() virtual external view returns (uint256,bool);
}
////// src/interfaces/SAFEEngineLike.sol
/* pragma solidity ^0.6.7; */
abstract contract SAFEEngineLike_8 {
function approveSAFEModification(address) virtual external;
function safeRights(address,address) virtual public view returns (uint256);
function collateralTypes(bytes32) virtual public view returns (
uint256 debtAmount, // [wad]
uint256 accumulatedRate, // [ray]
uint256 safetyPrice, // [ray]
uint256 debtCeiling, // [rad]
uint256 debtFloor, // [rad]
uint256 liquidationPrice // [ray]
);
function safes(bytes32,address) virtual public view returns (
uint256 lockedCollateral, // [wad]
uint256 generatedDebt // [wad]
);
function modifySAFECollateralization(
bytes32 collateralType,
address safe,
address collateralSource,
address debtDestination,
int256 deltaCollateral, // [wad]
int256 deltaDebt // [wad]
) virtual external;
}
////// src/interfaces/SAFESaviourRegistryLike.sol
/* pragma solidity ^0.6.7; */
abstract contract SAFESaviourRegistryLike {
function markSave(bytes32 collateralType, address safeHandler) virtual external;
}
////// src/interfaces/TaxCollectorLike.sol
/* pragma solidity 0.6.7; */
abstract contract TaxCollectorLike {
function taxSingle(bytes32) public virtual returns (uint256);
}
////// src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.0; */
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
////// src/interfaces/SafeSaviourLike.sol
// Copyright (C) 2020 Reflexer Labs, INC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity ^0.6.7; */
/* import "./CollateralJoinLike.sol"; */
/* import "./CoinJoinLike.sol"; */
/* import "./OracleRelayerLike.sol"; */
/* import "./SAFEEngineLike.sol"; */
/* import "./LiquidationEngineLike.sol"; */
/* import "./PriceFeedLike.sol"; */
/* import "./ERC20Like.sol"; */
/* import "./GebSafeManagerLike.sol"; */
/* import "./TaxCollectorLike.sol"; */
/* import "./SAFESaviourRegistryLike.sol"; */
/* import "../utils/ReentrancyGuard.sol"; */
abstract contract SafeSaviourLike is ReentrancyGuard {
// Checks whether a saviour contract has been approved by governance in the LiquidationEngine
modifier liquidationEngineApproved(address saviour) {
require(liquidationEngine.safeSaviours(saviour) == 1, "SafeSaviour/not-approved-in-liquidation-engine");
_;
}
// Checks whether someone controls a safe handler inside the GebSafeManager
modifier controlsSAFE(address owner, uint256 safeID) {
require(owner != address(0), "SafeSaviour/null-owner");
require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SafeSaviour/not-owning-safe");
_;
}
// --- Variables ---
LiquidationEngineLike_3 public liquidationEngine;
TaxCollectorLike public taxCollector;
OracleRelayerLike_2 public oracleRelayer;
GebSafeManagerLike public safeManager;
SAFEEngineLike_8 public safeEngine;
SAFESaviourRegistryLike public saviourRegistry;
// The amount of tokens the keeper gets in exchange for the gas spent to save a SAFE
uint256 public keeperPayout; // [wad]
// The minimum fiat value that the keeper must get in exchange for saving a SAFE
uint256 public minKeeperPayoutValue; // [wad]
/*
The proportion between the keeperPayout (if it's in collateral) and the amount of collateral or debt that's in a SAFE to be saved.
Alternatively, it can be the proportion between the fiat value of keeperPayout and the fiat value of the profit that a keeper
could make if a SAFE is liquidated right now. It ensures there's no incentive to intentionally put a SAFE underwater and then
save it just to make a profit that's greater than the one from participating in collateral auctions
*/
uint256 public payoutToSAFESize;
// --- Constants ---
uint256 public constant ONE = 1;
uint256 public constant HUNDRED = 100;
uint256 public constant THOUSAND = 1000;
uint256 public constant WAD_COMPLEMENT = 10**9;
uint256 public constant WAD = 10**18;
uint256 public constant RAY = 10**27;
uint256 public constant MAX_UINT = uint(-1);
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y) }
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Events ---
event SaveSAFE(address indexed keeper, bytes32 indexed collateralType, address indexed safeHandler, uint256 collateralAddedOrDebtRepaid);
// --- Functions to Implement ---
function saveSAFE(address,bytes32,address) virtual external returns (bool,uint256,uint256);
function getKeeperPayoutValue() virtual public returns (uint256);
function keeperPayoutExceedsMinValue() virtual public returns (bool);
function canSave(bytes32,address) virtual external returns (bool);
function tokenAmountUsedToSave(bytes32,address) virtual public returns (uint256);
}
////// src/interfaces/SaviourCRatioSetterLike.sol
/* pragma solidity 0.6.7; */
/* import "./OracleRelayerLike.sol"; */
/* import "./GebSafeManagerLike.sol"; */
/* import "../utils/ReentrancyGuard.sol"; */
abstract contract SaviourCRatioSetterLike is ReentrancyGuard {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "SaviourCRatioSetter/account-not-authorized");
_;
}
// Checks whether someone controls a safe handler inside the GebSafeManager
modifier controlsSAFE(address owner, uint256 safeID) {
require(owner != address(0), "SaviourCRatioSetter/null-owner");
require(either(owner == safeManager.ownsSAFE(safeID), safeManager.safeCan(safeManager.ownsSAFE(safeID), safeID, owner) == 1), "SaviourCRatioSetter/not-owning-safe");
_;
}
// --- Variables ---
OracleRelayerLike_2 public oracleRelayer;
GebSafeManagerLike public safeManager;
// Default desired cratio for each individual collateral type
mapping(bytes32 => uint256) public defaultDesiredCollateralizationRatios;
// Minimum bound for the desired cratio for each collateral type
mapping(bytes32 => uint256) public minDesiredCollateralizationRatios;
// Desired CRatios for each SAFE after they're saved
mapping(bytes32 => mapping(address => uint256)) public desiredCollateralizationRatios;
// --- Constants ---
uint256 public constant MAX_CRATIO = 1000;
uint256 public constant CRATIO_SCALE_DOWN = 10**25;
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y) }
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 indexed parameter, address data);
event SetDefaultCRatio(bytes32 indexed collateralType, uint256 cRatio);
event SetMinDesiredCollateralizationRatio(
bytes32 indexed collateralType,
uint256 cRatio
);
event SetDesiredCollateralizationRatio(
address indexed caller,
bytes32 indexed collateralType,
uint256 safeID,
address indexed safeHandler,
uint256 cRatio
);
// --- Functions ---
function setDefaultCRatio(bytes32, uint256) virtual external;
function setMinDesiredCollateralizationRatio(bytes32 collateralType, uint256 cRatio) virtual external;
function setDesiredCollateralizationRatio(bytes32 collateralType, uint256 safeID, uint256 cRatio) virtual external;
}
////// src/interfaces/UniswapLiquidityManagerLike.sol
/* pragma solidity 0.6.7; */
abstract contract UniswapLiquidityManagerLike {
function getToken0FromLiquidity(uint256) virtual public view returns (uint256);
function getToken1FromLiquidity(uint256) virtual public view returns (uint256);
function getLiquidityFromToken0(uint256) virtual public view returns (uint256);
function getLiquidityFromToken1(uint256) virtual public view returns (uint256);
function removeLiquidity(
uint256 liquidity,
uint128 amount0Min,
uint128 amount1Min,
address to
) public virtual returns (uint256, uint256);
}
////// src/math/SafeMath.sol
// SPDX-License-Identifier: MIT
/* pragma solidity >=0.6.0 <0.8.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.
*/
contract SafeMath_2 {
/**
* @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;
}
}
////// src/saviours/NativeUnderlyingUniswapV2SafeSaviour.sol
// Copyright (C) 2021 Reflexer Labs, INC
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity 0.6.7; */
/* import "../interfaces/UniswapLiquidityManagerLike.sol"; */
/* import "../interfaces/SaviourCRatioSetterLike.sol"; */
/* import "../interfaces/SafeSaviourLike.sol"; */
/* import "../math/SafeMath.sol"; */
contract NativeUnderlyingUniswapV2SafeSaviour is SafeMath_2, SafeSaviourLike {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "NativeUnderlyingUniswapV2SafeSaviour/account-not-authorized");
_;
}
mapping (address => uint256) public allowedUsers;
/**
* @notice Allow a user to deposit assets
* @param usr User to whitelist
*/
function allowUser(address usr) external isAuthorized {
allowedUsers[usr] = 1;
emit AllowUser(usr);
}
/**
* @notice Disallow a user from depositing assets
* @param usr User to disallow
*/
function disallowUser(address usr) external isAuthorized {
allowedUsers[usr] = 0;
emit DisallowUser(usr);
}
/**
* @notice Checks whether an address is an allowed user
**/
modifier isAllowed {
require(
either(restrictUsage == 0, both(restrictUsage == 1, allowedUsers[msg.sender] == 1)),
"NativeUnderlyingUniswapV2SafeSaviour/account-not-allowed"
);
_;
}
// --- Structs ---
struct Reserves {
uint256 systemCoins;
uint256 collateralCoins;
}
// --- Variables ---
// Flag that tells whether usage of the contract is restricted to allowed users
uint256 public restrictUsage;
// Whether the system coin is token0 in the Uniswap pool or not
bool public isSystemCoinToken0;
// Amount of LP tokens currently protecting each position
mapping(address => uint256) public lpTokenCover;
// Amount of system coin/collateral tokens that Safe owners can get back
mapping(address => Reserves) public underlyingReserves;
// Liquidity manager contract for Uniswap v2/v3
UniswapLiquidityManagerLike public liquidityManager;
// The ERC20 system coin
ERC20Like public systemCoin;
// The system coin join contract
CoinJoinLike public coinJoin;
// The collateral join contract for adding collateral in the system
CollateralJoinLike public collateralJoin;
// The LP token
ERC20Like public lpToken;
// The collateral token
ERC20Like public collateralToken;
// Oracle providing the system coin price feed
PriceFeedLike public systemCoinOrcl;
// Contract that defines desired CRatios for each Safe after it is saved
SaviourCRatioSetterLike public cRatioSetter;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event AllowUser(address usr);
event DisallowUser(address usr);
event ModifyParameters(bytes32 indexed parameter, uint256 val);
event ModifyParameters(bytes32 indexed parameter, address data);
event Deposit(
address indexed caller,
address indexed safeHandler,
uint256 lpTokenAmount
);
event Withdraw(
address indexed caller,
address indexed safeHandler,
address dst,
uint256 lpTokenAmount
);
event GetReserves(
address indexed caller,
address indexed safeHandler,
uint256 systemCoinAmount,
uint256 collateralAmount,
address dst
);
constructor(
bool isSystemCoinToken0_,
address coinJoin_,
address collateralJoin_,
address cRatioSetter_,
address systemCoinOrcl_,
address liquidationEngine_,
address taxCollector_,
address oracleRelayer_,
address safeManager_,
address saviourRegistry_,
address liquidityManager_,
address lpToken_,
uint256 minKeeperPayoutValue_
) public {
require(coinJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-coin-join");
require(collateralJoin_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-collateral-join");
require(cRatioSetter_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-cratio-setter");
require(systemCoinOrcl_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-system-coin-oracle");
require(oracleRelayer_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-oracle-relayer");
require(liquidationEngine_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liquidation-engine");
require(taxCollector_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-tax-collector");
require(safeManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-manager");
require(saviourRegistry_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-saviour-registry");
require(liquidityManager_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-liq-manager");
require(lpToken_ != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-lp-token");
require(minKeeperPayoutValue_ > 0, "NativeUnderlyingUniswapV2SafeSaviour/invalid-min-payout-value");
authorizedAccounts[msg.sender] = 1;
isSystemCoinToken0 = isSystemCoinToken0_;
minKeeperPayoutValue = minKeeperPayoutValue_;
coinJoin = CoinJoinLike(coinJoin_);
collateralJoin = CollateralJoinLike(collateralJoin_);
cRatioSetter = SaviourCRatioSetterLike(cRatioSetter_);
liquidationEngine = LiquidationEngineLike_3(liquidationEngine_);
taxCollector = TaxCollectorLike(taxCollector_);
oracleRelayer = OracleRelayerLike_2(oracleRelayer_);
systemCoinOrcl = PriceFeedLike(systemCoinOrcl_);
systemCoin = ERC20Like(coinJoin.systemCoin());
safeEngine = SAFEEngineLike_8(coinJoin.safeEngine());
safeManager = GebSafeManagerLike(safeManager_);
saviourRegistry = SAFESaviourRegistryLike(saviourRegistry_);
liquidityManager = UniswapLiquidityManagerLike(liquidityManager_);
lpToken = ERC20Like(lpToken_);
collateralToken = ERC20Like(collateralJoin.collateral());
systemCoinOrcl.getResultWithValidity();
oracleRelayer.redemptionPrice();
require(collateralJoin.contractEnabled() == 1, "NativeUnderlyingUniswapV2SafeSaviour/join-disabled");
require(address(collateralToken) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-col-token");
require(address(safeEngine) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-safe-engine");
require(address(systemCoin) != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-sys-coin");
emit AddAuthorization(msg.sender);
emit ModifyParameters("minKeeperPayoutValue", minKeeperPayoutValue);
emit ModifyParameters("oracleRelayer", oracleRelayer_);
emit ModifyParameters("taxCollector", taxCollector_);
emit ModifyParameters("systemCoinOrcl", systemCoinOrcl_);
emit ModifyParameters("liquidationEngine", liquidationEngine_);
emit ModifyParameters("liquidityManager", liquidityManager_);
}
// --- Administration ---
/**
* @notice Modify an uint256 param
* @param parameter The name of the parameter
* @param val New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized {
if (parameter == "minKeeperPayoutValue") {
require(val > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-min-payout");
minKeeperPayoutValue = val;
}
else if (parameter == "restrictUsage") {
require(val <= 1, "NativeUnderlyingUniswapV2SafeSaviour/invalid-restriction");
restrictUsage = val;
}
else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param");
emit ModifyParameters(parameter, val);
}
/**
* @notice Modify an address param
* @param parameter The name of the parameter
* @param data New address for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-data");
if (parameter == "systemCoinOrcl") {
systemCoinOrcl = PriceFeedLike(data);
systemCoinOrcl.getResultWithValidity();
}
else if (parameter == "oracleRelayer") {
oracleRelayer = OracleRelayerLike_2(data);
oracleRelayer.redemptionPrice();
}
else if (parameter == "liquidityManager") {
liquidityManager = UniswapLiquidityManagerLike(data);
}
else if (parameter == "liquidationEngine") {
liquidationEngine = LiquidationEngineLike_3(data);
}
else if (parameter == "taxCollector") {
taxCollector = TaxCollectorLike(data);
}
else revert("NativeUnderlyingUniswapV2SafeSaviour/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Transferring Reserves ---
/*
* @notify Get back system coins or collateral tokens that were withdrawn from Uniswap and not used to save a specific SAFE
* @param safeID The ID of the safe that was previously saved and has leftover funds that can be withdrawn
* @param dst The address that will receive
*/
function getReserves(uint256 safeID, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant {
address safeHandler = safeManager.safes(safeID);
(uint256 systemCoins, uint256 collateralCoins) =
(underlyingReserves[safeHandler].systemCoins, underlyingReserves[safeHandler].collateralCoins);
require(either(systemCoins > 0, collateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/no-reserves");
delete(underlyingReserves[safeManager.safes(safeID)]);
if (systemCoins > 0) {
systemCoin.transfer(dst, systemCoins);
}
if (collateralCoins > 0) {
collateralToken.transfer(dst, collateralCoins);
}
emit GetReserves(msg.sender, safeHandler, systemCoins, collateralCoins, dst);
}
// --- Adding/Withdrawing Cover ---
/*
* @notice Deposit lpToken in the contract in order to provide cover for a specific SAFE managed by the SAFE Manager
* @param safeID The ID of the SAFE to protect. This ID should be registered inside GebSafeManager
* @param lpTokenAmount The amount of collateralToken to deposit
*/
function deposit(uint256 safeID, uint256 lpTokenAmount) external isAllowed() liquidationEngineApproved(address(this)) nonReentrant {
require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount");
// Check that the SAFE exists inside GebSafeManager
address safeHandler = safeManager.safes(safeID);
require(safeHandler != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-handler");
// Check that the SAFE has debt
(, uint256 safeDebt) =
SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler);
require(safeDebt > 0, "NativeUnderlyingUniswapV2SafeSaviour/safe-does-not-have-debt");
// Update the lpToken balance used to cover the SAFE and transfer tokens to this contract
lpTokenCover[safeHandler] = add(lpTokenCover[safeHandler], lpTokenAmount);
require(lpToken.transferFrom(msg.sender, address(this), lpTokenAmount), "NativeUnderlyingUniswapV2SafeSaviour/could-not-transfer-lp");
emit Deposit(msg.sender, safeHandler, lpTokenAmount);
}
/*
* @notice Withdraw lpToken from the contract and provide less cover for a SAFE
* @dev Only an address that controls the SAFE inside the SAFE Manager can call this
* @param safeID The ID of the SAFE to remove cover from. This ID should be registered inside the SAFE Manager
* @param lpTokenAmount The amount of lpToken to withdraw
* @param dst The address that will receive the LP tokens
*/
function withdraw(uint256 safeID, uint256 lpTokenAmount, address dst) external controlsSAFE(msg.sender, safeID) nonReentrant {
require(lpTokenAmount > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-lp-amount");
// Fetch the handler from the SAFE manager
address safeHandler = safeManager.safes(safeID);
require(lpTokenCover[safeHandler] >= lpTokenAmount, "NativeUnderlyingUniswapV2SafeSaviour/not-enough-to-withdraw");
// Withdraw cover and transfer collateralToken to the caller
lpTokenCover[safeHandler] = sub(lpTokenCover[safeHandler], lpTokenAmount);
lpToken.transfer(dst, lpTokenAmount);
emit Withdraw(msg.sender, safeHandler, dst, lpTokenAmount);
}
// --- Saving Logic ---
/*
* @notice Saves a SAFE by withdrawing liquidity and repaying debt and/or adding more collateral
* @dev Only the LiquidationEngine can call this
* @param keeper The keeper that called LiquidationEngine.liquidateSAFE and that should be rewarded for spending gas to save a SAFE
* @param collateralType The collateral type backing the SAFE that's being liquidated
* @param safeHandler The handler of the SAFE that's being liquidated
* @return Whether the SAFE has been saved, the amount of LP tokens that were used to withdraw liquidity as well as the amount of
* system coins sent to the keeper as their payment (this implementation always returns 0)
*/
function saveSAFE(address keeper, bytes32 collateralType, address safeHandler) override external returns (bool, uint256, uint256) {
require(address(liquidationEngine) == msg.sender, "NativeUnderlyingUniswapV2SafeSaviour/caller-not-liquidation-engine");
require(keeper != address(0), "NativeUnderlyingUniswapV2SafeSaviour/null-keeper-address");
if (both(both(collateralType == "", safeHandler == address(0)), keeper == address(liquidationEngine))) {
return (true, uint(-1), uint(-1));
}
// Check that this is handling the correct collateral
require(collateralType == collateralJoin.collateralType(), "NativeUnderlyingUniswapV2SafeSaviour/invalid-collateral-type");
// Check that the SAFE has a non null amount of LP tokens covering it
require(lpTokenCover[safeHandler] > 0, "NativeUnderlyingUniswapV2SafeSaviour/null-cover");
// Tax the collateral
taxCollector.taxSingle(collateralType);
// Get the amount of tokens used to top up the SAFE
(uint256 safeDebtRepaid, uint256 safeCollateralAdded) =
getTokensForSaving(safeHandler, oracleRelayer.redemptionPrice());
// There must be tokens used to save the SAVE
require(either(safeDebtRepaid > 0, safeCollateralAdded > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-save-safe");
// Get the amounts of tokens sent to the keeper as payment
(uint256 keeperSysCoins, uint256 keeperCollateralCoins) =
getKeeperPayoutTokens(safeHandler, oracleRelayer.redemptionPrice(), safeDebtRepaid, safeCollateralAdded);
// There must be tokens that go to the keeper
require(either(keeperSysCoins > 0, keeperCollateralCoins > 0), "NativeUnderlyingUniswapV2SafeSaviour/cannot-pay-keeper");
// Store cover amount in local var
uint256 totalCover = lpTokenCover[safeHandler];
delete(lpTokenCover[safeHandler]);
// Mark the SAFE in the registry as just having been saved
saviourRegistry.markSave(collateralType, safeHandler);
// Withdraw all liquidity
uint256 sysCoinBalance = systemCoin.balanceOf(address(this));
uint256 collateralCoinBalance = collateralToken.balanceOf(address(this));
lpToken.approve(address(liquidityManager), totalCover);
liquidityManager.removeLiquidity(totalCover, 0, 0, address(this));
// Checks after removing liquidity
require(
either(systemCoin.balanceOf(address(this)) > sysCoinBalance, collateralToken.balanceOf(address(this)) > collateralCoinBalance),
"NativeUnderlyingUniswapV2SafeSaviour/faulty-remove-liquidity"
);
// Compute remaining balances of tokens that will go into reserves
sysCoinBalance = sub(sub(systemCoin.balanceOf(address(this)), sysCoinBalance), add(safeDebtRepaid, keeperSysCoins));
collateralCoinBalance = sub(
sub(collateralToken.balanceOf(address(this)), collateralCoinBalance), add(safeCollateralAdded, keeperCollateralCoins)
);
// Update reserves
if (sysCoinBalance > 0) {
underlyingReserves[safeHandler].systemCoins = add(
underlyingReserves[safeHandler].systemCoins, sysCoinBalance
);
}
if (collateralCoinBalance > 0) {
underlyingReserves[safeHandler].collateralCoins = add(
underlyingReserves[safeHandler].collateralCoins, collateralCoinBalance
);
}
// Save the SAFE
if (safeDebtRepaid > 0) {
// Approve the coin join contract to take system coins and repay debt
systemCoin.approve(address(coinJoin), safeDebtRepaid);
// Calculate the non adjusted system coin amount
uint256 nonAdjustedSystemCoinsToRepay = div(mul(safeDebtRepaid, RAY), getAccumulatedRate(collateralType));
// Join system coins in the system and repay the SAFE's debt
coinJoin.join(address(this), safeDebtRepaid);
safeEngine.modifySAFECollateralization(
collateralType,
safeHandler,
address(0),
address(this),
int256(0),
-int256(nonAdjustedSystemCoinsToRepay)
);
}
if (safeCollateralAdded > 0) {
// Approve collateralToken to the collateral join contract
collateralToken.approve(address(collateralJoin), safeCollateralAdded);
// Join collateralToken in the system and add it in the saved SAFE
collateralJoin.join(address(this), safeCollateralAdded);
safeEngine.modifySAFECollateralization(
collateralType,
safeHandler,
address(this),
address(0),
int256(safeCollateralAdded),
int256(0)
);
}
// Pay keeper
if (keeperSysCoins > 0) {
systemCoin.transfer(keeper, keeperSysCoins);
}
if (keeperCollateralCoins > 0) {
collateralToken.transfer(keeper, keeperCollateralCoins);
}
// Emit an event
emit SaveSAFE(keeper, collateralType, safeHandler, totalCover);
return (true, totalCover, 0);
}
// --- Getters ---
/*
* @notify Must be implemented according to the interface although it always returns 0
*/
function getKeeperPayoutValue() override public returns (uint256) {
return 0;
}
/*
* @notify Must be implemented according to the interface although it always returns false
*/
function keeperPayoutExceedsMinValue() override public returns (bool) {
return false;
}
/*
* @notice Determine whether a SAFE can be saved with the current amount of lpTokenCover deposited as cover for it
* @param safeHandler The handler of the SAFE which the function takes into account
* @return Whether the SAFE can be saved or not
*/
function canSave(bytes32, address safeHandler) override external returns (bool) {
// Fetch the redemption price first
uint256 redemptionPrice = oracleRelayer.redemptionPrice();
// Fetch the amount of tokens used to save the SAFE
(uint256 safeDebtRepaid, uint256 safeCollateralAdded) =
getTokensForSaving(safeHandler, redemptionPrice);
// Fetch the amount of tokens sent to the keeper
(uint256 keeperSysCoins, uint256 keeperCollateralCoins) =
getKeeperPayoutTokens(safeHandler, redemptionPrice, safeDebtRepaid, safeCollateralAdded);
// If there are some tokens used to save the SAFE and some tokens used to repay the keeper, return true
if (both(
either(safeDebtRepaid > 0, safeCollateralAdded > 0),
either(keeperSysCoins > 0, keeperCollateralCoins > 0)
)) {
return true;
}
return false;
}
/*
* @notice Return the total amount of LP tokens covering a specific SAFE
* @param collateralType The SAFE collateral type (ignored in this implementation)
* @param safeHandler The handler of the SAFE which the function takes into account
* @return The total LP token cover for a specific SAFE
*/
function tokenAmountUsedToSave(bytes32, address safeHandler) override public returns (uint256) {
return lpTokenCover[safeHandler];
}
/*
* @notify Fetch the collateral's price
*/
function getCollateralPrice() public view returns (uint256) {
(address ethFSM,,) = oracleRelayer.collateralTypes(collateralJoin.collateralType());
if (ethFSM == address(0)) return 0;
(uint256 priceFeedValue, bool hasValidValue) = PriceFeedLike(ethFSM).getResultWithValidity();
if (!hasValidValue) return 0;
return priceFeedValue;
}
/*
* @notify Fetch the system coin's market price
*/
function getSystemCoinMarketPrice() public view returns (uint256) {
(uint256 priceFeedValue, bool hasValidValue) = systemCoinOrcl.getResultWithValidity();
if (!hasValidValue) return 0;
return priceFeedValue;
}
/*
* @notify Get the target collateralization ratio that a SAFE should have after it's saved
* @param safeHandler The handler/address of the SAFE whose target collateralization ratio is retrieved
*/
function getTargetCRatio(address safeHandler) public view returns (uint256) {
bytes32 collateralType = collateralJoin.collateralType();
uint256 defaultCRatio = cRatioSetter.defaultDesiredCollateralizationRatios(collateralType);
uint256 targetCRatio = (cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler) == 0) ?
defaultCRatio : cRatioSetter.desiredCollateralizationRatios(collateralType, safeHandler);
return targetCRatio;
}
/*
* @notify Return the amount of system coins and collateral tokens retrieved from the LP position covering a specific SAFE
* @param safeHandler The handler/address of the targeted SAFE
*/
function getLPUnderlying(address safeHandler) public view returns (uint256, uint256) {
uint256 coverAmount = lpTokenCover[safeHandler];
if (coverAmount == 0) return (0, 0);
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = (isSystemCoinToken0) ?
(liquidityManager.getToken0FromLiquidity(coverAmount), liquidityManager.getToken1FromLiquidity(coverAmount)) :
(liquidityManager.getToken1FromLiquidity(coverAmount), liquidityManager.getToken0FromLiquidity(coverAmount));
return (sysCoinsFromLP, collateralFromLP);
}
/*
* @notice Return the amount of system coins and/or collateral tokens used to save a SAFE
* @param safeHandler The handler/address of the targeted SAFE
* @param redemptionPrice The system coin redemption price used in calculations
*/
function getTokensForSaving(address safeHandler, uint256 redemptionPrice)
public view returns (uint256, uint256) {
if (either(lpTokenCover[safeHandler] == 0, redemptionPrice == 0)) {
return (0, 0);
}
// Get the default CRatio for the SAFE
(uint256 depositedCollateralToken, uint256 safeDebt) =
SAFEEngineLike_8(collateralJoin.safeEngine()).safes(collateralJoin.collateralType(), safeHandler);
uint256 targetCRatio = getTargetCRatio(safeHandler);
if (either(safeDebt == 0, targetCRatio == 0)) {
return (0, 0);
}
// Get the collateral market price
uint256 collateralPrice = getCollateralPrice();
if (collateralPrice == 0) {
return (0, 0);
}
// Calculate how much debt would need to be repaid
uint256 debtToRepay = mul(
mul(HUNDRED, mul(depositedCollateralToken, collateralPrice) / WAD) / targetCRatio, RAY
) / redemptionPrice;
if (either(debtToRepay >= safeDebt, debtBelowFloor(collateralJoin.collateralType(), debtToRepay))) {
return (0, 0);
}
safeDebt = mul(safeDebt, getAccumulatedRate(collateralJoin.collateralType())) / RAY;
debtToRepay = sub(safeDebt, debtToRepay);
// Calculate underlying amounts received from LP withdrawal
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler);
// Determine total debt to repay; return if the SAFE can be saved solely by repaying debt, continue calculations otherwise
if (sysCoinsFromLP >= debtToRepay) {
return (debtToRepay, 0);
} else {
// Calculate the amount of collateral that would need to be added to the SAFE
uint256 scaledDownDebtValue = mul(add(mul(redemptionPrice, sub(safeDebt, sysCoinsFromLP)) / RAY, ONE), targetCRatio) / HUNDRED;
uint256 collateralTokenNeeded = div(mul(scaledDownDebtValue, WAD), collateralPrice);
collateralTokenNeeded = (depositedCollateralToken < collateralTokenNeeded) ?
sub(collateralTokenNeeded, depositedCollateralToken) : MAX_UINT;
// See if there's enough collateral to add to the SAFE in order to save it
if (collateralTokenNeeded <= collateralFromLP) {
return (sysCoinsFromLP, collateralTokenNeeded);
} else {
return (0, 0);
}
}
}
/*
* @notice Return the amount of system coins and/or collateral tokens used to pay a keeper
* @param safeHandler The handler/address of the targeted SAFE
* @param redemptionPrice The system coin redemption price used in calculations
* @param safeDebtRepaid The amount of system coins that are already used to save the targeted SAFE
* @param safeCollateralAdded The amount of collateral tokens that are already used to save the targeted SAFE
*/
function getKeeperPayoutTokens(address safeHandler, uint256 redemptionPrice, uint256 safeDebtRepaid, uint256 safeCollateralAdded)
public view returns (uint256, uint256) {
// Get the system coin and collateral market prices
uint256 collateralPrice = getCollateralPrice();
uint256 sysCoinMarketPrice = getSystemCoinMarketPrice();
if (either(collateralPrice == 0, sysCoinMarketPrice == 0)) {
return (0, 0);
}
// Calculate underlying amounts received from LP withdrawal
(uint256 sysCoinsFromLP, uint256 collateralFromLP) = getLPUnderlying(safeHandler);
// Check if the keeper can get system coins and if yes, compute how many
uint256 keeperSysCoins;
if (sysCoinsFromLP > safeDebtRepaid) {
uint256 remainingSystemCoins = sub(sysCoinsFromLP, safeDebtRepaid);
uint256 payoutInSystemCoins = div(mul(minKeeperPayoutValue, WAD), sysCoinMarketPrice);
if (payoutInSystemCoins <= remainingSystemCoins) {
return (payoutInSystemCoins, 0);
} else {
keeperSysCoins = remainingSystemCoins;
}
}
// Calculate how much collateral the keeper will get
if (collateralFromLP <= safeCollateralAdded) return (0, 0);
uint256 remainingCollateral = sub(collateralFromLP, safeCollateralAdded);
uint256 remainingKeeperPayoutValue = sub(minKeeperPayoutValue, mul(keeperSysCoins, sysCoinMarketPrice) / WAD);
uint256 collateralTokenNeeded = div(mul(remainingKeeperPayoutValue, WAD), collateralPrice);
// If there are enough collateral tokens retreived from LP in order to pay the keeper, return the token amounts
if (collateralTokenNeeded <= remainingCollateral) {
return (keeperSysCoins, collateralTokenNeeded);
} else {
// Otherwise, return zeroes
return (0, 0);
}
}
/*
* @notify Returns whether a target debt amount is below the debt floor of a specific collateral type
* @param collateralType The collateral type whose floor we compare against
* @param targetDebtAmount The target debt amount for a SAFE that has collateralType collateral in it
*/
function debtBelowFloor(bytes32 collateralType, uint256 targetDebtAmount) public view returns (bool) {
(, , , , uint256 debtFloor, ) = safeEngine.collateralTypes(collateralType);
return (mul(targetDebtAmount, RAY) < debtFloor);
}
/*
* @notify Get the accumulated interest rate for a specific collateral type
* @param The collateral type for which to retrieve the rate
*/
function getAccumulatedRate(bytes32 collateralType)
public view returns (uint256 accumulatedRate) {
(, accumulatedRate, , , , ) = safeEngine.collateralTypes(collateralType);
}
}
|
Allow a user to deposit assets usr User to whitelist/
|
function allowUser(address usr) external isAuthorized {
allowedUsers[usr] = 1;
emit AllowUser(usr);
}
| 8,026
|
pragma solidity ^0.4.24;
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract PCKevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularKey is PCKevents {}
contract PlayCoinKey is modularKey {
using SafeMath for *;
using NameFilter for string;
using PCKKeysCalcLong for uint256;
otherPCK private otherPCK_;
PlayCoinGodInterface constant private PCGod = PlayCoinGodInterface(0x6f93Be8fD47EBb62F54ebd149B58658bf9BaCF4f);
ProForwarderInterface constant private Pro_Inc = ProForwarderInterface(0x97354A7281693b7C93f6348Ba4eC38B9DDd76D6e);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x47D1c777f1853cac97E6b81226B1F5108FBD7B81);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "PlayCoin Key";
string constant public symbol = "PCK";
uint256 private rndExtra_ = 15 minutes; // length of the very first ICO
uint256 private rndGap_ = 15 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 12 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 6 hours; // max length a round timer can be
uint256 constant private rndMin_ = 10 minutes;
uint256 public rndReduceThreshold_ = 10e18; // 10ETH,reduce
bool public closed_ = false;
// admin is publish contract
address private admin = msg.sender;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => PCKdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => PCKdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => PCKdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => PCKdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => PCKdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (PCK, PCP) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = PCKdatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = PCKdatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = PCKdatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = PCKdatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (PCK, PCP)
potSplit_[0] = PCKdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = PCKdatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = PCKdatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = PCKdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isRoundActivated() {
require(round_[rID_].ended == false, "the round is finished");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
require(msg.sender == tx.origin, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
modifier onlyAdmins() {
require(msg.sender == admin, "onlyAdmins failed - msg.sender is not an admin");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
function kill () onlyAdmins() public {
require(round_[rID_].ended == true && closed_ == true, "the round is active or not close");
selfdestruct(admin);
}
function getRoundStatus() isActivated() public view returns(uint256, bool){
return (rID_, round_[rID_].ended);
}
function setThreshold(uint256 _threshold) onlyAdmins() public returns(uint256) {
rndReduceThreshold_ = _threshold;
return rndReduceThreshold_;
}
function setEnforce(bool _closed) onlyAdmins() public returns(bool) {
closed_ = _closed;
if( !closed_ && round_[rID_].ended == true && activated_ == true ){
nextRound();
}
return closed_;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
PCKdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit PCKevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit PCKevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit PCKevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_) private {
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (!closed_ && _now > (round_[_rID].strt + rndGap_) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if ( (closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
if( !closed_ ){
nextRound();
}
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PCKevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, PCKdatasets.EventReturns memory _eventData_) private {
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (!closed_ && _now > ( round_[_rID].strt + rndGap_ ) && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if ( ( closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
if( !closed_ ) {
nextRound();
}
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PCKevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID, _eth);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000) {
airDropTracker_++;
if (airdrop() == true) {
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function nextRound() private {
rID_++;
round_[rID_].strt = now;
round_[rID_].end = now.add(rndInit_).add(rndGap_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to PCGod
if (_p3d > 0)
PCGod.deposit.value(_p3d)();
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.PCPAmount = _p3d;
_eventData_.newPot = _res;
// start next round
//rID_++;
_rID++;
round_[_rID].ended = false;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID, uint256 _eth)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
uint256 _newEndTime;
if (_newTime < (rndMax_).add(_now))
_newEndTime = _newTime;
else
_newEndTime = rndMax_.add(_now);
// biger to threshold, reduce
if ( _eth >= rndReduceThreshold_ ) {
_newEndTime = (_newEndTime).sub( (((_keys) / (1000000000000000000))).mul(rndInc_).add( (((_keys) / (2000000000000000000) ).mul(rndInc_)) ) );
// last add 10 minutes
if( _newEndTime < _now + rndMin_ )
_newEndTime = _now + rndMin_ ;
}
round_[_rID].end = _newEndTime;
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop() private view returns(bool) {
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D short
uint256 _long = _eth / 100;
otherPCK_.potSwap.value(_long)();
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit PCKevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to PCGod contract
PCGod.deposit.value(_p3d)();
// set up event data
_eventData_.PCPAmount = _p3d.add(_eventData_.PCPAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit PCKevents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit PCKevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate() public {
// only team just can activate
require(
msg.sender == admin,
"only team just can activate"
);
// make sure that its been linked.
require(address(otherPCK_) != address(0), "must link to other PCK first");
// can only be ran once
require(activated_ == false, "PCK already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherPCK(address _otherPCK) public {
// only team just can activate
require(
msg.sender == admin,
"only team just can activate"
);
// make sure that it HASNT yet been linked.
require(address(otherPCK_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherPCK_ = otherPCK(_otherPCK);
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library PCKdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 PCPAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library PCKKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface otherPCK {
function potSwap() external payable;
}
interface PCKExtSettingInterface {
function getFastGap() external view returns(uint256);
function getLongGap() external view returns(uint256);
function getFastExtra() external view returns(uint256);
function getLongExtra() external view returns(uint256);
}
interface PlayCoinGodInterface {
function deposit() external payable;
}
interface ProForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
============================================================================== _ |_ |. _ |` _ __|_. _ _ _ . |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)====|=========================================================================
|
function kill () onlyAdmins() public {
require(round_[rID_].ended == true && closed_ == true, "the round is active or not close");
selfdestruct(admin);
}
| 1,254,072
|
/**
*Submitted for verification at Etherscan.io on 2022-04-05
*/
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File @openzeppelin/contracts/access/[email protected]
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (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/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (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/introspection/[email protected]
// OpenZeppelin Contracts v4.4.1 (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/[email protected]
// OpenZeppelin Contracts v4.4.1 (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/access/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/utils/structs/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, 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 `from` to `to` 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 from,
address to,
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);
}
// File contracts/Interfaces/DataInterface.sol
pragma solidity 0.8.11;
interface DataInterface is IAccessControlEnumerable{
/* solhint-disable */
function ADMIN_ROLE() external pure returns(bytes32);
function MODERATOR_ROLE() external pure returns(bytes32);
function SALECONTRACT_ROLE() external pure returns(bytes32);
/* solhint-enable */
// *******************************************
// ************* MANAGER REGION **************
// *******************************************
function manuallyWhitelistParticipant(address participant_) external;
function manuallyBlacklistParticipant(address participant_) external;
function manuallyCreditParticipant(address participant_, address tokenInvested_, uint tokenAmount_) external;
function setSignersAddress(address signersAddress_) external returns (bool);
function setTokenConversion(uint tokenConversion_) external returns (bool);
// *****************************************************
// ************* SALECONTRACT_ROLE REGION **************
// *****************************************************
function whitelistParticipant(address participant_, bytes memory signature_) external;
function creditParticipation(address participant_, address tokenInvested_, uint tokenAmount_) external;
// *************************************************
// ************* DEFAULT_ADMIN REGION **************
// *************************************************
function setRoleAdmin(bytes32 role, bytes32 adminRole) external returns (bool);
function salvageTokensFromContract(address tokenAddress, address to, uint amount) external returns (bool);
function killContract() external returns (bool);
// ********************************************
// ************* INTERNAL REGION **************
// ********************************************
// **************************************************
// ************* PUBLIC GETTERS REGION **************
// **************************************************
function getParticipantCount() external view returns (uint);
function getCombinedContributions() external view returns (uint);
function getIsParticipantWhitelisted(address participant_) external view returns (bool);
function getParticipantContributions(address participant_) external view returns (uint);
function getParticipantList(uint startIndex_, uint endIndex_) external view returns (address[] memory, uint[] memory);
function getSignersAddress() external view returns (address);
function getMessageHash(address contributor_, bool allowed_) external pure returns (bytes32);
function getTokenConversion() external view returns (uint);
// ******************************************
// ************* EVENTS REGION **************
// ******************************************
event ContributionMade(address indexed contractAddress, address indexed participant_, address tokenInvested_, uint baseAmount_, uint tokensIssued_);
event ParticipantWhitelisted(address participant_);
event ParticipantBlacklisted(address participant_);
event SignersAddressChanged(address oldValue, address newValue);
event TokenConversionChanged(uint oldValue, uint newValue);
event AdminRoleSet(bytes32 role, bytes32 adminRole);
event TokensSalvaged(address tokenAddress, address reciever, uint amount);
event ContractKilled();
}
// File contracts/DataContract.sol
pragma solidity 0.8.11;
//import "hardhat/console.sol";
/// @title Authtrail presale data contract
/// @author Authtrail llc
/// @dev Data contract serves as collection of all the data needed for sucessfull presale
/// @custom:experimental This is an experimental contract.
contract DataContract is AccessControlEnumerable, DataInterface {
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant MODERATOR_ROLE = keccak256("MODERATOR_ROLE");
bytes32 public constant SALECONTRACT_ROLE = keccak256("SALECONTRACT_ROLE");
uint private _participantCount;
uint private _combinedContributions;
address[] private _participantList;
mapping(address => bool) private _isParticipantWhitelisted;
mapping(address => uint) private _participantContributions;
address private _signersAddress;
uint private _tokenConversion = 5;
constructor(address defaultAdminAddress_, address adminAddress_, address moderatorAddress_, address signersAddress_) {
_setupRole(DEFAULT_ADMIN_ROLE, defaultAdminAddress_);
_setupRole(ADMIN_ROLE, adminAddress_);
_setupRole(MODERATOR_ROLE, moderatorAddress_);
_setRoleAdmin(MODERATOR_ROLE, ADMIN_ROLE);
_setRoleAdmin(SALECONTRACT_ROLE, ADMIN_ROLE);
_setupRole(ADMIN_ROLE, msg.sender);
_signersAddress = signersAddress_;
}
// *******************************************
// ************* MODERATOR REGION ************
// *******************************************
/// @notice Adds participant to whitelist manually
/// @dev This method should be used if someone has participated in crowdsale on different conditions
/// @param participant_ Participants address
function manuallyWhitelistParticipant(address participant_) public onlyRole(MODERATOR_ROLE) override {
require(!_isParticipantWhitelisted[participant_], "Participant is already whitelisted!");
_isParticipantWhitelisted[participant_] = true;
_participantList.push(participant_);
_participantCount += 1;
emit ParticipantWhitelisted(participant_);
}
/// @notice Removes participant from whitelist manually
/// @dev This method should be used if participant must be removed from whitelist
/// @param participant_ Participants address
function manuallyBlacklistParticipant(address participant_) public onlyRole(MODERATOR_ROLE) override {
require(_isParticipantWhitelisted[participant_], "Participant is not whitelisted!");
_isParticipantWhitelisted[participant_] = false;
emit ParticipantBlacklisted(participant_);
}
/// @notice Credits participant whithouth him going through presale
/// @dev This method should be used if someone has participated in crowdsale on different conditions
/// @param participant_ Participants address
/// @param tokenAmount_ Amount of tokens participant contributed
function manuallyCreditParticipant(address participant_, address tokenInvested_, uint tokenAmount_) public onlyRole(MODERATOR_ROLE) override {
require(_isParticipantWhitelisted[participant_], "Participant is not whitelisted!");
_participantContributions[participant_] += tokenAmount_;
_combinedContributions += tokenAmount_;
emit ContributionMade(msg.sender, participant_, tokenInvested_, tokenAmount_, tokenAmount_ * _tokenConversion);
}
/// @notice Sets new signer that handles whitelisting on the server
/// @dev This method should only be used in ongoing presale if something goes wrong
/// @param signersAddress_ New address of the signing account on our backend
/// @return default return True after everything is processed
function setSignersAddress(address signersAddress_) public onlyRole(MODERATOR_ROLE) override returns (bool) {
address oldValue = _signersAddress;
require(oldValue != signersAddress_, "Value is already set!");
_signersAddress = signersAddress_;
emit SignersAddressChanged(oldValue, signersAddress_);
return true;
}
/// @notice Sets new amount of our tokens that participant will be awarded for 1 stablecoin
/// @dev This method should only be used in ongoing presale if something goes wrong
/// @param tokenConversion_ New conversion between our token and stable coin contributed
/// @return default return True after everything is processed
function setTokenConversion(uint tokenConversion_) public onlyRole(MODERATOR_ROLE) override returns (bool) {
uint oldValue = _tokenConversion;
require(oldValue != tokenConversion_, "Value is already set!");
_tokenConversion = tokenConversion_;
emit TokenConversionChanged(oldValue, tokenConversion_);
return true;
}
// *****************************************************
// ************* SALECONTRACT_ROLE REGION **************
// *****************************************************
/// @notice Whitelist the participant if signature is done by our signer
/// @dev This method is internal method and should be used by presale contract
/// @param participant_ Address of the participant
/// @param signature_ Signed message of our backend that participant can be whitelisted
function whitelistParticipant(address participant_, bytes memory signature_) public onlyRole(SALECONTRACT_ROLE) override {
require(!_isParticipantWhitelisted[participant_], "Participant is already whitelisted!");
require(_verify(_signersAddress, participant_, signature_), "Wrong signature!");
_isParticipantWhitelisted[participant_] = true;
_participantList.push(participant_);
_participantCount += 1;
emit ParticipantWhitelisted(participant_);
}
/// @notice Adds the amount that this participant has contributed
/// @dev This method is internal method and should be used by presale contract
/// @param participant_ Address of the participant
/// @param tokenAmount_ Amount of Stablecoins participant has contributed
function creditParticipation(address participant_, address tokenInvested_, uint tokenAmount_) public onlyRole(SALECONTRACT_ROLE) override {
_participantContributions[participant_] += tokenAmount_;
_combinedContributions += tokenAmount_;
emit ContributionMade(msg.sender, participant_, tokenInvested_, tokenAmount_, tokenAmount_ * _tokenConversion);
}
// *************************************************
// ************* DEFAULT_ADMIN REGION **************
// *************************************************
/// @notice Sets new role admin to the role defined
/// @dev This method should only be used if some of priviliged keys are compromised, can only be done by defaultAdmin
/// @param role_ Role that we want to change
/// @param adminRole_ Role that will become new admin of the changed role
/// @return default return True after everything is processed
function setRoleAdmin(bytes32 role_, bytes32 adminRole_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool) {
_setRoleAdmin(role_, adminRole_);
emit AdminRoleSet(role_, adminRole_);
return true;
}
/// @notice Transfer tokens from the contract to desiered address
/// @dev This method should be used if users accedentaly sends tokens to our contract address
/// @param tokenAddress_ Token address of the token that we want to salvage
/// @param to_ Destination where salvaged tokens will be sent
/// @param amount_ Amount of tokens we want to salvage
/// @return default return True after everything is processed
function salvageTokensFromContract(address tokenAddress_, address to_, uint amount_) public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){
IERC20(tokenAddress_).transfer(to_, amount_);
emit TokensSalvaged(tokenAddress_, to_, amount_);
return true;
}
/// @notice Destroys the contract
/// @dev This method should NEVER be used if you don't know the implications!!!!!!!!
/// @return default return True after everything is processed
function killContract() public onlyRole(DEFAULT_ADMIN_ROLE) override returns (bool){
emit ContractKilled();
selfdestruct(payable(msg.sender));
return true;
}
// ********************************************
// ************* INTERNAL REGION **************
// ********************************************
function _verify(address signer_, address sender_, bytes memory signature_) internal pure returns(bool) {
bytes32 messageHash = getMessageHash(sender_, true);
bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature_) == signer_;
}
function _getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) {
/*
Signature is produced by signing a keccak256 hash with the following format:
"\x19Ethereum Signed Message\n" + len(msg) + msg
*/
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash));
}
function recoverSigner(bytes32 ethSignedMessageHash_, bytes memory signature_) internal pure returns (address) {
(bytes32 r,
bytes32 s,
uint8 v) = _splitSignature(signature_);
return ecrecover(ethSignedMessageHash_, v, r, s);
}
function _splitSignature(bytes memory sig_) internal pure returns (bytes32 r, bytes32 s, uint8 v) {
require(sig_.length == 65, "invalid signature length");
assembly {
/*
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(sig_, 32))
// second 32 bytes
s := mload(add(sig_, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig_, 96)))
}
// implicitly return (r, s, v)
}
// **************************************************
// ************* PUBLIC GETTERS REGION **************
// **************************************************
/// @notice Get number of unique participants
function getParticipantCount() public view override returns (uint) {
return _participantCount;
}
/// @notice Get all the contributions made
function getCombinedContributions() public view override returns (uint) {
return _combinedContributions;
}
/// @notice Get if participants address is whitelisted
function getIsParticipantWhitelisted(address participant_) public view override returns (bool) {
return _isParticipantWhitelisted[participant_];
}
/// @notice Get all contributions for one participant
function getParticipantContributions(address participant_) public view override returns (uint) {
return _participantContributions[participant_];
}
/// @notice Get list of all unique participants and their combined contributions
function getParticipantList(uint startIndex_, uint endIndex_) public view override returns (address[] memory, uint[] memory) {
uint endIndex = endIndex_;
if (endIndex_ > _participantCount) {
endIndex = _participantCount;
}
address[] memory participantAddressArray = new address[](endIndex - startIndex_);
uint[] memory participantContributionArray = new uint[](endIndex - startIndex_);
for (uint i=0; i<endIndex - startIndex_; i++) {
participantAddressArray[i] = _participantList[i + startIndex_];
participantContributionArray[i] = getParticipantContributions(participantAddressArray[i]);
}
return (participantAddressArray, participantContributionArray);
}
/// @notice Get public key of our backend signer
function getSignersAddress() public view override returns (address) {
return _signersAddress;
}
/// @notice Keccak message to use for proof
function getMessageHash(address contributor_, bool allowed_) public pure override returns (bytes32) {
return keccak256(abi.encodePacked(contributor_, allowed_));
}
/// @notice Amount of our tokens user will get for 1 stablecoin contributed
function getTokenConversion() public view override returns (uint) {
return _tokenConversion;
}
}
|
Get if participants address is whitelisted
|
function getIsParticipantWhitelisted(address participant_) public view override returns (bool) {
return _isParticipantWhitelisted[participant_];
}
| 8,004,944
|
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_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 {
_transferOwnership(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");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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 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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} 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 {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* 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 {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-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 virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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 virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
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 {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + 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 {IERC20-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 virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This 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 virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(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 virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This 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 virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens 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 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./libraries/ProofParser.sol";
import "./interfaces/ICrossChainBridge.sol";
import "./SimpleTokenProxy.sol";
import "./InternetBondProxy.sol";
contract BridgeRouter {
function peggedTokenAddress(address bridge, address fromToken) public pure returns (address) {
return SimpleTokenProxyUtils.simpleTokenProxyAddress(bridge, bytes32(bytes20(fromToken)));
}
function peggedBondAddress(address bridge, address fromToken) public pure returns (address) {
return InternetBondProxyUtils.internetBondProxyAddress(bridge, bytes32(bytes20(fromToken)));
}
function factoryPeggedToken(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge) public returns (IERC20Mintable) {
/* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */
address targetToken = SimpleTokenProxyUtils.deploySimpleTokenProxy(bridge, bytes32(bytes20(fromToken)), metaData);
require(targetToken == toToken, "bad chain");
/* to token is our new pegged token */
return IERC20Mintable(toToken);
}
function factoryPeggedBond(address fromToken, address toToken, ICrossChainBridge.Metadata memory metaData, address bridge, address feed) public returns (IERC20Mintable) {
/* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */
address targetToken = InternetBondProxyUtils.deployInternetBondProxy(bridge, bytes32(bytes20(fromToken)), metaData, feed);
require(targetToken == toToken, "bad chain");
/* to token is our new pegged token */
return IERC20Mintable(toToken);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./interfaces/IERC20.sol";
import "./interfaces/IInternetBondRatioFeed.sol";
import "./SimpleToken.sol";
import "./libraries/Utils.sol";
contract InternetBond is SimpleToken, IERC20InternetBond {
IInternetBondRatioFeed public ratioFeed;
bool internal _rebasing;
function ratio() public view override returns (uint256) {
return ratioFeed.getRatioFor(_originAddress);
}
function isRebasing() public view override returns (bool) {
return _rebasing;
}
function totalSupply() public view override returns (uint256) {
return _sharesToBonds(super.totalSupply());
}
function balanceOf(address account) public view override returns (uint256) {
return _sharesToBonds(super.balanceOf(account));
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
uint256 shares = _bondsToShares(amount);
_transfer(_msgSender(), recipient, shares, false);
emit Transfer(_msgSender(), recipient, _sharesToBonds(shares));
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _sharesToBonds(super.allowance(owner, spender));
}
function approve(address spender, uint256 amount) public override returns (bool) {
uint256 shares = _bondsToShares(amount);
_approve(_msgSender(), spender, shares, false);
emit Approval(_msgSender(), spender, allowance(_msgSender(), spender));
return true;
}
function increaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 shares = _bondsToShares(amount);
_increaseAllowance(_msgSender(), spender, shares, false);
emit Approval(_msgSender(), spender, allowance(_msgSender(), spender));
return true;
}
function decreaseAllowance(address spender, uint256 amount) public override returns (bool) {
uint256 shares = _bondsToShares(amount);
_decreaseAllowance(_msgSender(), spender, shares, false);
emit Approval(_msgSender(), spender, allowance(_msgSender(), spender));
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
uint256 shares = _bondsToShares(amount);
_transfer(sender, recipient, shares, false);
emit Transfer(sender, recipient, _sharesToBonds(shares));
_decreaseAllowance(sender, _msgSender(), shares, false);
emit Approval(sender, _msgSender(), allowance(sender, _msgSender()));
return true;
}
// NB: mint accepts amount in shares
function mint(address account, uint256 shares) public onlyOwner override {
require(account != address(0));
_totalSupply += shares;
_balances[account] += shares;
emit Transfer(address(0), account, _sharesToBonds(shares));
}
// NB: burn accepts amount in shares
function burn(address account, uint256 shares) public onlyOwner override {
require(account != address(0));
_balances[account] -= shares;
_totalSupply -= shares;
emit Transfer(account, address(0), _sharesToBonds(shares));
}
function _sharesToBonds(uint256 amount) internal view returns (uint256) {
if (_rebasing) {
uint256 currentRatio = ratio();
require(currentRatio > 0, "ratio not available");
return Utils.multiplyAndDivideCeil(amount, 10 ** decimals(), currentRatio);
} else {
return amount;
}
}
function _bondsToShares(uint256 amount) internal view returns (uint256) {
if (_rebasing) {
uint256 currentRatio = ratio();
require(currentRatio > 0, "ratio not available");
return Utils.multiplyAndDivideFloor(amount, currentRatio, 10 ** decimals());
} else {
return amount;
}
}
function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress, address ratioFeedAddress, bool rebasing) external emptyOwner {
super.initAndObtainOwnership(symbol, name, originChain, originAddress);
require(ratioFeedAddress != address(0x0), "no ratio feed");
ratioFeed = IInternetBondRatioFeed(ratioFeedAddress);
_rebasing = rebasing;
}
}
contract InternetBondFactory {
address private _template;
constructor() {
_template = InternetBondFactoryUtils.deployInternetBondTemplate(this);
}
function getImplementation() public view returns (address) {
return _template;
}
}
library InternetBondFactoryUtils {
bytes32 constant internal INTERNET_BOND_TEMPLATE_SALT = keccak256("InternetBondTemplateV1");
bytes constant internal INTERNET_BOND_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b506110c0806100206000396000f3fe608060405234801561001057600080fd5b506004361061012c5760003560e01c806371ca337d116100ad5780639dc29fac116100715780639dc29fac1461026b578063a457c2d71461027e578063a9059cbb14610291578063dd62ed3e146102a4578063df1f29ee146102b757600080fd5b806371ca337d1461020a5780638da5cb5b146102125780638e29ebb51461023d57806394bfed881461025057806395d89b411461026357600080fd5b8063313ce567116100f4578063313ce567146101b057806339509351146101bf57806340c10f19146101d25780635dfba115146101e557806370a08231146101f757600080fd5b806306fdde0314610131578063095ea7b31461014f57806318160ddd1461017257806323b872dd14610188578063265535671461019b575b600080fd5b6101396102da565b6040516101469190610e14565b60405180910390f35b61016261015d366004610d2a565b6102ec565b6040519015158152602001610146565b61017a610348565b604051908152602001610146565b610162610196366004610cee565b61035b565b6101ae6101a9366004610d93565b610400565b005b60405160128152602001610146565b6101626101cd366004610d2a565b61049e565b6101ae6101e0366004610d2a565b6104b9565b600854600160a01b900460ff16610162565b61017a610205366004610ca0565b610560565b61017a610582565b600254610225906001600160a01b031681565b6040516001600160a01b039091168152602001610146565b600854610225906001600160a01b031681565b6101ae61025e366004610d54565b610606565b610139610657565b6101ae610279366004610d2a565b610664565b61016261028c366004610d2a565b6106f9565b61016261029f366004610d2a565b610714565b61017a6102b2366004610cbb565b610752565b600654600754604080519283526001600160a01b03909116602083015201610146565b60606102e760015461078a565b905090565b6000806102f883610860565b905061030733858360006108e6565b6001600160a01b0384163360008051602061106b83398151915261032b8288610752565b60405190815260200160405180910390a360019150505b92915050565b60006102e761035660055490565b61097c565b60008061036783610860565b905061037685858360006109f9565b836001600160a01b0316856001600160a01b031660008051602061104b8339815191526103a28461097c565b60405190815260200160405180910390a36103c08533836000610ab2565b336001600160a01b03861660008051602061106b8339815191526103e48884610752565b60405190815260200160405180910390a3506001949350505050565b6002546001600160a01b03161561041657600080fd5b61042286868686610606565b6001600160a01b03821661046d5760405162461bcd60e51b815260206004820152600d60248201526c1b9bc81c985d1a5bc819995959609a1b60448201526064015b60405180910390fd5b60088054911515600160a01b026001600160a81b03199092166001600160a01b039093169290921717905550505050565b6000806104aa83610860565b90506103073385836000610b5f565b6002546001600160a01b031633146104d057600080fd5b6001600160a01b0382166104e357600080fd5b80600560008282546104f59190610e69565b90915550506001600160a01b03821660009081526003602052604081208054839290610522908490610e69565b90915550506001600160a01b038216600060008051602061104b83398151915261054b8461097c565b60405190815260200160405180910390a35050565b6001600160a01b0381166000908152600360205260408120546103429061097c565b60085460075460405163a1f1d48d60e01b81526001600160a01b039182166004820152600092919091169063a1f1d48d9060240160206040518083038186803b1580156105ce57600080fd5b505afa1580156105e2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102e79190610dfb565b6002546001600160a01b03161561061c57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102e760005461078a565b6002546001600160a01b0316331461067b57600080fd5b6001600160a01b03821661068e57600080fd5b6001600160a01b038216600090815260036020526040812080548392906106b6908490610fc7565b9250508190555080600560008282546106cf9190610fc7565b90915550600090506001600160a01b03831660008051602061104b83398151915261054b8461097c565b60008061070583610860565b90506103073385836000610ab2565b60008061072083610860565b905061072f33858360006109f9565b6001600160a01b0384163360008051602061104b83398151915261032b8461097c565b6001600160a01b0380831660009081526004602090815260408083209385168352929052908120546107839061097c565b9392505050565b6060816107a557505060408051600081526020810190915290565b600060105b60ff8116156107fc57836107be8284610e81565b60ff16602081106107d1576107d161101e565b1a60f81b6001600160f81b031916156107f1576107ee8183610e81565b91505b60011c607f166107aa565b50600061080a826001610e81565b60ff1667ffffffffffffffff81111561082557610825611034565b6040519080825280601f01601f19166020018201604052801561084f576020820181803683370190505b506020810194909452509192915050565b600854600090600160a01b900460ff16156108dd57600061087f610582565b9050600081116108c75760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b61078383826108d86012600a610efd565b610bbc565b5090565b919050565b6001600160a01b0384166108f957600080fd5b6001600160a01b03831661090c57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561097657826001600160a01b0316846001600160a01b031660008051602061106b8339815191528460405161096d91815260200190565b60405180910390a35b50505050565b600854600090600160a01b900460ff16156108dd57600061099b610582565b9050600081116109e35760405162461bcd60e51b8152602060048201526013602482015272726174696f206e6f7420617661696c61626c6560681b6044820152606401610464565b610783836109f36012600a610efd565b83610c01565b6001600160a01b038416610a0c57600080fd5b6001600160a01b038316610a1f57600080fd5b6001600160a01b03841660009081526003602052604081208054849290610a47908490610fc7565b90915550506001600160a01b03831660009081526003602052604081208054849290610a74908490610e69565b9091555050801561097657826001600160a01b0316846001600160a01b031660008051602061104b8339815191528460405161096d91815260200190565b6001600160a01b038416610ac557600080fd5b6001600160a01b038316610ad857600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610fc7565b90915550508015610976576001600160a01b0384811660008181526004602090815260408083209488168084529482529182902054915191825260008051602061106b833981519152910161096d565b6001600160a01b038416610b7257600080fd5b6001600160a01b038316610b8557600080fd5b6001600160a01b03808516600090815260046020908152604080832093871683529290529081208054849290610b0f908490610e69565b6000610bf9610bd4610bce8487610ea6565b85610c3e565b8385610be08289610fde565b610bea9190610fa8565b610bf49190610ea6565b610c71565b949350505050565b6000610bf9610c13610bce8487610ea6565b83610c1f600182610fc7565b86610c2a878a610fde565b610c349190610fa8565b610bea9190610e69565b600082610c4d57506000610342565b82820282848281610c6057610c60611008565b041461078357600019915050610342565b60008282018381101561078357600019915050610342565b80356001600160a01b03811681146108e157600080fd5b600060208284031215610cb257600080fd5b61078382610c89565b60008060408385031215610cce57600080fd5b610cd783610c89565b9150610ce560208401610c89565b90509250929050565b600080600060608486031215610d0357600080fd5b610d0c84610c89565b9250610d1a60208501610c89565b9150604084013590509250925092565b60008060408385031215610d3d57600080fd5b610d4683610c89565b946020939093013593505050565b60008060008060808587031215610d6a57600080fd5b843593506020850135925060408501359150610d8860608601610c89565b905092959194509250565b60008060008060008060c08789031215610dac57600080fd5b863595506020870135945060408701359350610dca60608801610c89565b9250610dd860808801610c89565b915060a08701358015158114610ded57600080fd5b809150509295509295509295565b600060208284031215610e0d57600080fd5b5051919050565b600060208083528351808285015260005b81811015610e4157858101830151858201604001528201610e25565b81811115610e53576000604083870101525b50601f01601f1916929092016040019392505050565b60008219821115610e7c57610e7c610ff2565b500190565b600060ff821660ff84168060ff03821115610e9e57610e9e610ff2565b019392505050565b600082610eb557610eb5611008565b500490565b600181815b80851115610ef5578160001904821115610edb57610edb610ff2565b80851615610ee857918102915b93841c9390800290610ebf565b509250929050565b600061078360ff841683600082610f1657506001610342565b81610f2357506000610342565b8160018114610f395760028114610f4357610f5f565b6001915050610342565b60ff841115610f5457610f54610ff2565b50506001821b610342565b5060208310610133831016604e8410600b8410161715610f82575081810a610342565b610f8c8383610eba565b8060001904821115610fa057610fa0610ff2565b029392505050565b6000816000190483118215151615610fc257610fc2610ff2565b500290565b600082821015610fd957610fd9610ff2565b500390565b600082610fed57610fed611008565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfeddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a26469706673582212202704c0c85a7ffefb8570f6c29df5c6522044694561363ba9c4f84b992471d3fb64736f6c63430008060033";
bytes32 constant internal INTERNET_BOND_TEMPLATE_HASH = keccak256(INTERNET_BOND_TEMPLATE_BYTECODE);
function deployInternetBondTemplate(InternetBondFactory templateFactory) internal returns (address) {
/* we can use any deterministic salt here, since we don't care about it */
bytes32 salt = INTERNET_BOND_TEMPLATE_SALT;
/* concat bytecode with constructor */
bytes memory bytecode = INTERNET_BOND_TEMPLATE_BYTECODE;
/* deploy contract and store result in result variable */
address result;
assembly {
result := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(result != address(0x00), "deploy failed");
/* check that generated contract address is correct */
require(result == internetBondTemplateAddress(templateFactory), "address mismatched");
return result;
}
function internetBondTemplateAddress(InternetBondFactory templateFactory) internal pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), INTERNET_BOND_TEMPLATE_SALT, INTERNET_BOND_TEMPLATE_HASH));
return address(bytes20(hash << 96));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./interfaces/ICrossChainBridge.sol";
contract InternetBondProxy {
bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1);
fallback() external {
address bridge;
bytes32 slot = BEACON_SLOT;
assembly {
bridge := sload(slot)
}
address impl = ICrossChainBridge(bridge).getBondImplementation();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
function setBeacon(address newBeacon) external {
address beacon;
bytes32 slot = BEACON_SLOT;
assembly {
beacon := sload(slot)
}
require(beacon == address(0x00));
assembly {
sstore(slot, newBeacon)
}
}
}
library InternetBondProxyUtils {
bytes constant internal INTERNET_BOND_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b0316631626425c6040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220d283edebb1e56b63c1cf809c7a7219bbf056c367c289dabb51fdba5f71cdf44c64736f6c63430008060033";
bytes32 constant internal INTERNET_BOND_PROXY_HASH = keccak256(INTERNET_BOND_PROXY_BYTECODE);
bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address,address,bool)"));
bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)"));
function deployInternetBondProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData, address ratioFeed) internal returns (address) {
/* lets concat bytecode with constructor parameters */
bytes memory bytecode = INTERNET_BOND_PROXY_BYTECODE;
/* deploy new contract and store contract address in result variable */
address result;
assembly {
result := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(result != address(0x00), "deploy failed");
/* setup impl */
(bool success, bytes memory returnValue) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge)));
require(success, string(abi.encodePacked("setBeacon failed: ", returnValue)));
/* setup meta data */
bytes memory inputData = new bytes(0xc4);
bool isRebasing = metaData.bondMetadata[1] == bytes1(0x01);
bytes4 selector = SET_META_DATA_SIG;
assembly {
mstore(add(inputData, 0x20), selector)
mstore(add(inputData, 0x24), mload(metaData))
mstore(add(inputData, 0x44), mload(add(metaData, 0x20)))
mstore(add(inputData, 0x64), mload(add(metaData, 0x40)))
mstore(add(inputData, 0x84), mload(add(metaData, 0x60)))
mstore(add(inputData, 0xa4), ratioFeed)
mstore(add(inputData, 0xc4), isRebasing)
}
(success, returnValue) = result.call(inputData);
require(success, string(abi.encodePacked("set metadata failed: ", returnValue)));
/* return generated contract address */
return result;
}
function internetBondProxyAddress(address deployer, bytes32 salt) internal pure returns (address) {
bytes32 bytecodeHash = keccak256(INTERNET_BOND_PROXY_BYTECODE);
bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash));
return address(bytes20(hash << 96));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./interfaces/IInternetBondRatioFeed.sol";
contract InternetBondRatioFeed is OwnableUpgradeable, IInternetBondRatioFeed {
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
mapping(address => bool) _isOperator;
mapping(address => uint256) private _ratios;
function initialize(address operator) public initializer {
__Ownable_init();
_isOperator[operator] = true;
}
function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) public override onlyOperator {
require(addresses.length == ratios.length, "corrupted ratio data");
for (uint256 i = 0; i < addresses.length; i++) {
_ratios[addresses[i]] = ratios[i];
}
}
function getRatioFor(address token) public view override returns (uint256) {
return _ratios[token];
}
function addOperator(address operator) public onlyOwner {
require(operator != address(0x0), "operator must be non-zero");
require(!_isOperator[operator], "already operator");
_isOperator[operator] = true;
emit OperatorAdded(operator);
}
function removeOperator(address operator) public onlyOwner {
require(_isOperator[operator], "not an operator");
delete _isOperator[operator];
emit OperatorRemoved(operator);
}
modifier onlyOperator() {
require(msg.sender == owner() || _isOperator[msg.sender], "Operator: not allowed");
_;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./interfaces/IERC20.sol";
contract SimpleToken is Context, IERC20, IERC20Mintable, IERC20Pegged {
// pre-defined state
bytes32 internal _symbol; // 0
bytes32 internal _name; // 1
address public owner; // 2
// internal state
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _totalSupply;
uint256 internal _originChain;
address internal _originAddress;
function name() public view returns (string memory) {
return bytes32ToString(_name);
}
function symbol() public view returns (string memory) {
return bytes32ToString(_symbol);
}
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
if (_bytes32 == 0) {
return new string(0);
}
uint8 cntNonZero = 0;
for (uint8 i = 16; i > 0; i >>= 1) {
if (_bytes32[cntNonZero + i] != 0) cntNonZero += i;
}
string memory result = new string(cntNonZero + 1);
assembly {
mstore(add(result, 0x20), _bytes32)
}
return result;
}
function decimals() public pure returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount, true);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount, true);
return true;
}
function increaseAllowance(address spender, uint256 amount) public virtual returns (bool) {
_increaseAllowance(_msgSender(), spender, amount, true);
return true;
}
function decreaseAllowance(address spender, uint256 amount) public virtual returns (bool) {
_decreaseAllowance(_msgSender(), spender, amount, true);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount, true);
_decreaseAllowance(sender, _msgSender(), amount, true);
return true;
}
function _increaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal {
require(owner != address(0));
require(spender != address(0));
_allowances[owner][spender] += amount;
if (emitEvent) {
emit Approval(owner, spender, _allowances[owner][spender]);
}
}
function _decreaseAllowance(address owner, address spender, uint256 amount, bool emitEvent) internal {
require(owner != address(0));
require(spender != address(0));
_allowances[owner][spender] -= amount;
if (emitEvent) {
emit Approval(owner, spender, _allowances[owner][spender]);
}
}
function _approve(address owner, address spender, uint256 amount, bool emitEvent) internal {
require(owner != address(0));
require(spender != address(0));
_allowances[owner][spender] = amount;
if (emitEvent) {
emit Approval(owner, spender, amount);
}
}
function _transfer(address sender, address recipient, uint256 amount, bool emitEvent) internal {
require(sender != address(0));
require(recipient != address(0));
_balances[sender] -= amount;
_balances[recipient] += amount;
if (emitEvent) {
emit Transfer(sender, recipient, amount);
}
}
function mint(address account, uint256 amount) public onlyOwner virtual override {
require(account != address(0));
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function burn(address account, uint256 amount) public onlyOwner virtual override {
require(account != address(0));
_balances[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
modifier emptyOwner() {
require(owner == address(0x00));
_;
}
function initAndObtainOwnership(bytes32 symbol, bytes32 name, uint256 originChain, address originAddress) public emptyOwner {
owner = msg.sender;
_symbol = symbol;
_name = name;
_originChain = originChain;
_originAddress = originAddress;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function getOrigin() public view override returns (uint256, address) {
return (_originChain, _originAddress);
}
}
contract SimpleTokenFactory {
address private _template;
constructor() {
_template = SimpleTokenFactoryUtils.deploySimpleTokenTemplate(this);
}
function getImplementation() public view returns (address) {
return _template;
}
}
library SimpleTokenFactoryUtils {
bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_SALT = keccak256("SimpleTokenTemplateV1");
bytes constant internal SIMPLE_TOKEN_TEMPLATE_BYTECODE = hex"608060405234801561001057600080fd5b50610a7f806100206000396000f3fe608060405234801561001057600080fd5b50600436106101005760003560e01c80638da5cb5b11610097578063a457c2d711610066578063a457c2d714610224578063a9059cbb14610237578063dd62ed3e1461024a578063df1f29ee1461028357600080fd5b80638da5cb5b146101cb57806394bfed88146101f657806395d89b41146102095780639dc29fac1461021157600080fd5b8063313ce567116100d3578063313ce5671461016b578063395093511461017a57806340c10f191461018d57806370a08231146101a257600080fd5b806306fdde0314610105578063095ea7b31461012357806318160ddd1461014657806323b872dd14610158575b600080fd5b61010d6102a6565b60405161011a919061095e565b60405180910390f35b6101366101313660046108f5565b6102b8565b604051901515815260200161011a565b6005545b60405190815260200161011a565b6101366101663660046108b9565b6102d0565b6040516012815260200161011a565b6101366101883660046108f5565b6102f6565b6101a061019b3660046108f5565b610305565b005b61014a6101b0366004610864565b6001600160a01b031660009081526003602052604090205490565b6002546101de906001600160a01b031681565b6040516001600160a01b03909116815260200161011a565b6101a061020436600461091f565b6103b9565b61010d61040a565b6101a061021f3660046108f5565b610417565b6101366102323660046108f5565b6104c5565b6101366102453660046108f5565b6104d4565b61014a610258366004610886565b6001600160a01b03918216600090815260046020908152604080832093909416825291909152205490565b600654600754604080519283526001600160a01b0390911660208301520161011a565b60606102b36001546104e3565b905090565b60006102c733848460016105b9565b50600192915050565b60006102df8484846001610661565b6102ec843384600161072c565b5060019392505050565b60006102c733848460016107eb565b6002546001600160a01b0316331461031c57600080fd5b6001600160a01b03821661032f57600080fd5b806005600082825461034191906109b3565b90915550506001600160a01b0382166000908152600360205260408120805483929061036e9084906109b3565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020015b60405180910390a35050565b6002546001600160a01b0316156103cf57600080fd5b60028054336001600160a01b031991821617909155600094909455600192909255600655600780549092166001600160a01b03909116179055565b60606102b36000546104e3565b6002546001600160a01b0316331461042e57600080fd5b6001600160a01b03821661044157600080fd5b6001600160a01b038216600090815260036020526040812080548392906104699084906109f0565b92505081905550806005600082825461048291906109f0565b90915550506040518181526000906001600160a01b038416907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906020016103ad565b60006102c7338484600161072c565b60006102c73384846001610661565b6060816104fe57505060408051600081526020810190915290565b600060105b60ff811615610555578361051782846109cb565b60ff166020811061052a5761052a610a1d565b1a60f81b6001600160f81b0319161561054a5761054781836109cb565b91505b60011c607f16610503565b5060006105638260016109cb565b60ff1667ffffffffffffffff81111561057e5761057e610a33565b6040519080825280601f01601f1916602001820160405280156105a8576020820181803683370190505b506020810194909452509192915050565b6001600160a01b0384166105cc57600080fd5b6001600160a01b0383166105df57600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905220829055801561065b57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161065291815260200190565b60405180910390a35b50505050565b6001600160a01b03841661067457600080fd5b6001600160a01b03831661068757600080fd5b6001600160a01b038416600090815260036020526040812080548492906106af9084906109f0565b90915550506001600160a01b038316600090815260036020526040812080548492906106dc9084906109b3565b9091555050801561065b57826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8460405161065291815260200190565b6001600160a01b03841661073f57600080fd5b6001600160a01b03831661075257600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109f0565b9091555050801561065b576001600160a01b038481166000818152600460209081526040808320948816808452948252918290205491519182527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259101610652565b6001600160a01b0384166107fe57600080fd5b6001600160a01b03831661081157600080fd5b6001600160a01b038085166000908152600460209081526040808320938716835292905290812080548492906107899084906109b3565b80356001600160a01b038116811461085f57600080fd5b919050565b60006020828403121561087657600080fd5b61087f82610848565b9392505050565b6000806040838503121561089957600080fd5b6108a283610848565b91506108b060208401610848565b90509250929050565b6000806000606084860312156108ce57600080fd5b6108d784610848565b92506108e560208501610848565b9150604084013590509250925092565b6000806040838503121561090857600080fd5b61091183610848565b946020939093013593505050565b6000806000806080858703121561093557600080fd5b84359350602085013592506040850135915061095360608601610848565b905092959194509250565b600060208083528351808285015260005b8181101561098b5785810183015185820160400152820161096f565b8181111561099d576000604083870101525b50601f01601f1916929092016040019392505050565b600082198211156109c6576109c6610a07565b500190565b600060ff821660ff84168060ff038211156109e8576109e8610a07565b019392505050565b600082821015610a0257610a02610a07565b500390565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052604160045260246000fdfea2646970667358221220fe9609dd4d099f8ee61d515b2ebf66a53d24e78cf669be48b69b627acefde71564736f6c63430008060033";
bytes32 constant internal SIMPLE_TOKEN_TEMPLATE_HASH = keccak256(SIMPLE_TOKEN_TEMPLATE_BYTECODE);
bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("obtainOwnership(bytes32,bytes32)"));
function deploySimpleTokenTemplate(SimpleTokenFactory templateFactory) internal returns (address) {
/* we can use any deterministic salt here, since we don't care about it */
bytes32 salt = SIMPLE_TOKEN_TEMPLATE_SALT;
/* concat bytecode with constructor */
bytes memory bytecode = SIMPLE_TOKEN_TEMPLATE_BYTECODE;
/* deploy contract and store result in result variable */
address result;
assembly {
result := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(result != address(0x00), "deploy failed");
/* check that generated contract address is correct */
require(result == simpleTokenTemplateAddress(templateFactory), "address mismatched");
return result;
}
function simpleTokenTemplateAddress(SimpleTokenFactory templateFactory) internal pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(templateFactory), SIMPLE_TOKEN_TEMPLATE_SALT, SIMPLE_TOKEN_TEMPLATE_HASH));
return address(bytes20(hash << 96));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./interfaces/ICrossChainBridge.sol";
contract SimpleTokenProxy {
bytes32 private constant BEACON_SLOT = bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1);
fallback() external {
address bridge;
bytes32 slot = BEACON_SLOT;
assembly {
bridge := sload(slot)
}
address impl = ICrossChainBridge(bridge).getTokenImplementation();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
function setBeacon(address newBeacon) external {
address beacon;
bytes32 slot = BEACON_SLOT;
assembly {
beacon := sload(slot)
}
require(beacon == address(0x00));
assembly {
sstore(slot, newBeacon)
}
}
}
library SimpleTokenProxyUtils {
bytes constant internal SIMPLE_TOKEN_PROXY_BYTECODE = hex"608060405234801561001057600080fd5b50610215806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c8063d42afb56146100fd575b60008061005960017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b60001b9050805491506000826001600160a01b031663709bc7f36040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561009f57600080fd5b505af11580156100b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906100d79190610185565b90503660008037600080366000845af43d6000803e8080156100f8573d6000f35b3d6000fd5b61011061010b366004610161565b610112565b005b60008061014060017fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d516101a2565b8054925090506001600160a01b0382161561015a57600080fd5b9190915550565b60006020828403121561017357600080fd5b813561017e816101c7565b9392505050565b60006020828403121561019757600080fd5b815161017e816101c7565b6000828210156101c257634e487b7160e01b600052601160045260246000fd5b500390565b6001600160a01b03811681146101dc57600080fd5b5056fea2646970667358221220e6ae4b3dc2474e43ff609e19eb520ce54b6f38170a43a6f96541360be5efc2b464736f6c63430008060033";
bytes32 constant internal SIMPLE_TOKEN_PROXY_HASH = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE);
bytes4 constant internal SET_META_DATA_SIG = bytes4(keccak256("initAndObtainOwnership(bytes32,bytes32,uint256,address)"));
bytes4 constant internal SET_BEACON_SIG = bytes4(keccak256("setBeacon(address)"));
function deploySimpleTokenProxy(address bridge, bytes32 salt, ICrossChainBridge.Metadata memory metaData) internal returns (address) {
/* lets concat bytecode with constructor parameters */
bytes memory bytecode = SIMPLE_TOKEN_PROXY_BYTECODE;
/* deploy new contract and store contract address in result variable */
address result;
assembly {
result := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(result != address(0x00), "deploy failed");
/* setup impl */
(bool success,) = result.call(abi.encodePacked(SET_BEACON_SIG, abi.encode(bridge)));
require(success, "setBeacon failed");
/* setup meta data */
(success,) = result.call(abi.encodePacked(SET_META_DATA_SIG, abi.encode(metaData)));
require(success, "set metadata failed");
/* return generated contract address */
return result;
}
function simpleTokenProxyAddress(address deployer, bytes32 salt) internal pure returns (address) {
bytes32 bytecodeHash = keccak256(SIMPLE_TOKEN_PROXY_BYTECODE);
bytes32 hash = keccak256(abi.encodePacked(uint8(0xff), address(deployer), salt, bytecodeHash));
return address(bytes20(hash << 96));
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "../interfaces/IERC20.sol";
interface ICrossChainBridge {
event ContractAllowed(address contractAddress, uint256 toChain);
event ContractDisallowed(address contractAddress, uint256 toChain);
event ConsensusChanged(address consensusAddress);
event TokenImplementationChanged(address consensusAddress);
event BondImplementationChanged(address consensusAddress);
struct Metadata {
bytes32 symbol;
bytes32 name;
uint256 originChain;
address originAddress;
bytes32 bondMetadata; // encoded metadata version, bond type
}
event DepositLocked(
uint256 chainId,
address indexed fromAddress,
address indexed toAddress,
address fromToken,
address toToken,
uint256 totalAmount,
Metadata metadata
);
event DepositBurned(
uint256 chainId,
address indexed fromAddress,
address indexed toAddress,
address fromToken,
address toToken,
uint256 totalAmount,
Metadata metadata,
address originToken
);
event WithdrawMinted(
bytes32 receiptHash,
address indexed fromAddress,
address indexed toAddress,
address fromToken,
address toToken,
uint256 totalAmount
);
event WithdrawUnlocked(
bytes32 receiptHash,
address indexed fromAddress,
address indexed toAddress,
address fromToken,
address toToken,
uint256 totalAmount
);
enum InternetBondType {
NOT_BOND,
REBASING_BOND,
NONREBASING_BOND
}
function isPeggedToken(address toToken) external returns (bool);
function deposit(uint256 toChain, address toAddress) payable external;
function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) external;
function withdraw(bytes calldata encodedProof, bytes calldata rawReceipt, bytes calldata receiptRootSignature) external;
function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external;
function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external;
function getTokenImplementation() external returns (address);
function getBondImplementation() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Mintable {
function mint(address account, uint256 amount) external;
function burn(address account, uint256 amount) external;
}
interface IERC20Pegged {
function getOrigin() external view returns (uint256, address);
}
interface IERC20Extra {
function name() external returns (string memory);
function decimals() external returns (uint8);
function symbol() external returns (string memory);
}
interface IERC20InternetBond {
function ratio() external view returns (uint256);
function isRebasing() external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
interface IInternetBondRatioFeed {
function updateRatioBatch(address[] calldata addresses, uint256[] calldata ratios) external;
function getRatioFor(address) external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.6;
library CallDataRLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
function beginIteration(uint256 listOffset) internal pure returns (uint256 iter) {
return listOffset + _payloadOffset(listOffset);
}
function next(uint256 iter) internal pure returns (uint256 nextIter) {
return iter + itemLength(iter);
}
function payloadLen(uint256 ptr, uint256 len) internal pure returns (uint256) {
return len - _payloadOffset(ptr);
}
function toAddress(uint256 ptr) internal pure returns (address) {
return address(uint160(toUint(ptr, 21)));
}
function toUint(uint256 ptr, uint256 len) internal pure returns (uint256) {
require(len > 0 && len <= 33);
uint256 offset = _payloadOffset(ptr);
uint256 numLen = len - offset;
uint256 result;
assembly {
result := calldataload(add(ptr, offset))
// cut off redundant bytes
result := shr(mul(8, sub(32, numLen)), result)
}
return result;
}
function toUintStrict(uint256 ptr) internal pure returns (uint256) {
// one byte prefix
uint256 result;
assembly {
result := calldataload(add(ptr, 1))
}
return result;
}
function rawDataPtr(uint256 ptr) internal pure returns (uint256) {
return ptr + _payloadOffset(ptr);
}
// @return entire rlp item byte length
function itemLength(uint callDataPtr) internal pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, calldataload(callDataPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
callDataPtr := add(callDataPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr))
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
callDataPtr := add(callDataPtr, 1)
let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr))
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 callDataPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, calldataload(callDataPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START)
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./CallDataRLPReader.sol";
import "./Utils.sol";
import "../interfaces/ICrossChainBridge.sol";
library EthereumVerifier {
bytes32 constant TOPIC_PEG_IN_LOCKED = keccak256("DepositLocked(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32))");
bytes32 constant TOPIC_PEG_IN_BURNED = keccak256("DepositBurned(uint256,address,address,address,address,uint256,(bytes32,bytes32,uint256,address,bytes32),address)");
enum PegInType {
None,
Lock,
Burn
}
struct State {
bytes32 receiptHash;
address contractAddress;
uint256 chainId;
address fromAddress;
address payable toAddress;
address fromToken;
address toToken;
uint256 totalAmount;
// metadata fields (we can't use Metadata struct here because of Solidity struct memory layout)
bytes32 symbol;
bytes32 name;
uint256 originChain;
address originAddress;
bytes32 bondMetadata;
address originToken;
}
function getMetadata(State memory state) internal pure returns (ICrossChainBridge.Metadata memory) {
ICrossChainBridge.Metadata memory metadata;
assembly {
metadata := add(state, 0x100)
}
return metadata;
}
function parseTransactionReceipt(uint256 receiptOffset) internal view returns (State memory, PegInType pegInType) {
State memory state;
/* parse peg-in data from logs */
uint256 iter = CallDataRLPReader.beginIteration(receiptOffset + 0x20);
{
/* postStateOrStatus - we must ensure that tx is not reverted */
uint256 statusOffset = iter;
iter = CallDataRLPReader.next(iter);
require(CallDataRLPReader.payloadLen(statusOffset, iter - statusOffset) == 1, "tx is reverted");
}
/* skip cumulativeGasUsed */
iter = CallDataRLPReader.next(iter);
/* logs - we need to find our logs */
uint256 logs = iter;
iter = CallDataRLPReader.next(iter);
uint256 logsIter = CallDataRLPReader.beginIteration(logs);
for (; logsIter < iter;) {
uint256 log = logsIter;
logsIter = CallDataRLPReader.next(logsIter);
/* make sure there is only one peg-in event in logs */
PegInType logType = _decodeReceiptLogs(state, log);
if (logType != PegInType.None) {
require(pegInType == PegInType.None, "multiple logs");
pegInType = logType;
}
}
/* don't allow to process if peg-in type is unknown */
require(pegInType != PegInType.None, "missing logs");
return (state, pegInType);
}
function _decodeReceiptLogs(
State memory state,
uint256 log
) internal view returns (PegInType pegInType) {
uint256 logIter = CallDataRLPReader.beginIteration(log);
address contractAddress;
{
/* parse smart contract address */
uint256 addressOffset = logIter;
logIter = CallDataRLPReader.next(logIter);
contractAddress = CallDataRLPReader.toAddress(addressOffset);
}
/* topics */
bytes32 mainTopic;
address fromAddress;
address toAddress;
{
uint256 topicsIter = logIter;
logIter = CallDataRLPReader.next(logIter);
// Must be 3 topics RLP encoded: event signature, fromAddress, toAddress
// Each topic RLP encoded is 33 bytes (0xa0[32 bytes data])
// Total payload: 99 bytes. Since it's list with total size bigger than 55 bytes we need 2 bytes prefix (0xf863)
// So total size of RLP encoded topics array must be 101
if (CallDataRLPReader.itemLength(topicsIter) != 101) {
return PegInType.None;
}
topicsIter = CallDataRLPReader.beginIteration(topicsIter);
mainTopic = bytes32(CallDataRLPReader.toUintStrict(topicsIter));
topicsIter = CallDataRLPReader.next(topicsIter);
fromAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter))));
topicsIter = CallDataRLPReader.next(topicsIter);
toAddress = address(bytes20(uint160(CallDataRLPReader.toUintStrict(topicsIter))));
topicsIter = CallDataRLPReader.next(topicsIter);
require(topicsIter == logIter); // safety check that iteration is finished
}
uint256 ptr = CallDataRLPReader.rawDataPtr(logIter);
logIter = CallDataRLPReader.next(logIter);
uint256 len = logIter - ptr;
{
// parse logs based on topic type and check that event data has correct length
uint256 expectedLen;
if (mainTopic == TOPIC_PEG_IN_LOCKED) {
expectedLen = 0x120;
pegInType = PegInType.Lock;
} else if (mainTopic == TOPIC_PEG_IN_BURNED) {
expectedLen = 0x140;
pegInType = PegInType.Burn;
} else {
return PegInType.None;
}
if (len != expectedLen) {
return PegInType.None;
}
}
{
// read chain id separately and verify that contract that emitted event is relevant
uint256 chainId;
assembly {
chainId := calldataload(ptr)
}
if (chainId != Utils.currentChain()) return PegInType.None;
// All checks are passed after this point, no errors allowed and we can modify state
state.chainId = chainId;
ptr += 0x20;
len -= 0x20;
}
{
uint256 structOffset;
assembly {
// skip 5 fields: receiptHash, contractAddress, chainId, fromAddress, toAddress
structOffset := add(state, 0xa0)
calldatacopy(structOffset, ptr, len)
}
}
state.contractAddress = contractAddress;
state.fromAddress = fromAddress;
state.toAddress = payable(toAddress);
return pegInType;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "./CallDataRLPReader.sol";
import "./Utils.sol";
library ProofParser {
// Proof is message format signed by the protocol. It contains somewhat redundant information, so only part
// of the proof could be passed into the contract and other part can be inferred from transaction receipt
struct Proof {
uint256 chainId;
uint256 status;
bytes32 transactionHash;
uint256 blockNumber;
bytes32 blockHash;
uint256 transactionIndex;
bytes32 receiptHash;
uint256 transferAmount;
}
function parseProof(uint256 proofOffset) internal pure returns (Proof memory) {
Proof memory proof;
uint256 dataOffset = proofOffset + 0x20;
assembly {
calldatacopy(proof, dataOffset, 0x20) // 1 field (chainId)
dataOffset := add(dataOffset, 0x20)
calldatacopy(add(proof, 0x40), dataOffset, 0x80) // 4 fields * 0x20 = 0x80
dataOffset := add(dataOffset, 0x80)
calldatacopy(add(proof, 0xe0), dataOffset, 0x20) // transferAmount
}
return proof;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
import "../SimpleToken.sol";
library Utils {
function currentChain() internal view returns (uint256) {
uint256 chain;
assembly {
chain := chainid()
}
return chain;
}
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function saturatingMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
if (a == 0) return 0;
uint256 c = a * b;
if (c / a != b) return type(uint256).max;
return c;
}
}
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return type(uint256).max;
return c;
}
}
// Preconditions:
// 1. a may be arbitrary (up to 2 ** 256 - 1)
// 2. b * c < 2 ** 256
// Returned value: min(floor((a * b) / c), 2 ** 256 - 1)
function multiplyAndDivideFloor(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return saturatingAdd(
saturatingMultiply(a / c, b),
((a % c) * b) / c // can't fail because of assumption 2.
);
}
// Preconditions:
// 1. a may be arbitrary (up to 2 ** 256 - 1)
// 2. b * c < 2 ** 256
// Returned value: min(ceil((a * b) / c), 2 ** 256 - 1)
function multiplyAndDivideCeil(uint256 a, uint256 b, uint256 c) internal pure returns (uint256) {
return saturatingAdd(
saturatingMultiply(a / c, b),
((a % c) * b + (c - 1)) / c // can't fail because of assumption 2.
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.6;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "../interfaces/ICrossChainBridge.sol";
import "../interfaces/IERC20.sol";
import "../libraries/EthereumVerifier.sol";
import "../libraries/ProofParser.sol";
import "../libraries/Utils.sol";
import "../SimpleToken.sol";
import "../InternetBond.sol";
import "../InternetBondRatioFeed.sol";
import "../BridgeRouter.sol";
contract CrossChainBridge_R1 is PausableUpgradeable, ReentrancyGuardUpgradeable, OwnableUpgradeable, ICrossChainBridge {
mapping(uint256 => address) private _bridgeAddressByChainId;
address private _consensusAddress;
mapping(bytes32 => bool) private _usedProofs;
address private _tokenImplementation;
mapping(address => address) private _peggedTokenOrigin;
Metadata _nativeTokenMetadata;
address private _bondImplementation;
IInternetBondRatioFeed private _internetBondRatioFeed;
BridgeRouter private _bridgeRouter;
function initialize(
address consensusAddress,
SimpleTokenFactory tokenFactory,
InternetBondFactory bondFactory,
string memory nativeTokenSymbol,
string memory nativeTokenName,
InternetBondRatioFeed bondFeed,
BridgeRouter router
) public initializer {
__Pausable_init();
__ReentrancyGuard_init();
__Ownable_init();
__CrossChainBridge_init(consensusAddress, tokenFactory, bondFactory, nativeTokenSymbol, nativeTokenName, bondFeed, router);
}
function getTokenImplementation() public view override returns (address) {
return _tokenImplementation;
}
function setTokenFactory(SimpleTokenFactory factory) public onlyOwner {
_tokenImplementation = factory.getImplementation();
require(_tokenImplementation != address(0x0));
emit TokenImplementationChanged(_tokenImplementation);
}
function getBondImplementation() public view override returns (address) {
return _bondImplementation;
}
function setBondFactory(InternetBondFactory factory) public onlyOwner {
_bondImplementation = factory.getImplementation();
require(_bondImplementation != address(0x0));
emit BondImplementationChanged(_tokenImplementation);
}
function getNativeAddress() public view returns (address) {
return _nativeTokenMetadata.originAddress;
}
function getOrigin(address token) internal view returns (uint256, address) {
if (token == _nativeTokenMetadata.originAddress) {
return (0, address(0x0));
}
try IERC20Pegged(token).getOrigin() returns (uint256 chain, address origin) {
return (chain, origin);
} catch {}
return (0, address(0x0));
}
function __CrossChainBridge_init(
address consensusAddress,
SimpleTokenFactory tokenFactory,
InternetBondFactory bondFactory,
string memory nativeTokenSymbol,
string memory nativeTokenName,
InternetBondRatioFeed bondFeed,
BridgeRouter router
) internal {
_consensusAddress = consensusAddress;
_tokenImplementation = tokenFactory.getImplementation();
_bondImplementation = bondFactory.getImplementation();
_nativeTokenMetadata = Metadata(
Utils.stringToBytes32(nativeTokenSymbol),
Utils.stringToBytes32(nativeTokenName),
Utils.currentChain(),
// generate unique address that will not collide with any contract address
address(bytes20(keccak256(abi.encodePacked("CrossChainBridge:", nativeTokenSymbol)))),
0x0
);
_internetBondRatioFeed = bondFeed;
_bridgeRouter = router;
}
// HELPER FUNCTIONS
function isPeggedToken(address toToken) public view override returns (bool) {
return _peggedTokenOrigin[toToken] != address(0x00);
}
function getRatio(address token) public view returns (uint256) {
return _internetBondRatioFeed.getRatioFor(token);
}
function getBondType(address token) public view returns (InternetBondType) {
try IERC20InternetBond(token).isRebasing() returns (bool isRebasing) {
if (isRebasing) return InternetBondType.REBASING_BOND;
else return InternetBondType.NONREBASING_BOND;
} catch {
}
return InternetBondType.NOT_BOND;
}
function getNativeRatio(address token) public view returns (uint256) {
try IERC20InternetBond(token).ratio() returns (uint256 ratio) {
return ratio;
} catch {
}
return 0;
}
function createBondMetadata(uint8 version, InternetBondType bondType) internal pure returns (bytes32) {
bytes32 result = 0x0;
result |= bytes32(bytes1(version));
result |= bytes32(bytes1(uint8(bondType))) >> 8;
return result;
}
// DEPOSIT FUNCTIONS
function deposit(uint256 toChain, address toAddress) public payable nonReentrant whenNotPaused override {
_depositNative(toChain, toAddress, msg.value);
}
function deposit(address fromToken, uint256 toChain, address toAddress, uint256 amount) public nonReentrant whenNotPaused override {
(uint256 chain, address origin) = getOrigin(fromToken);
if (chain != 0) {
/* if we have pegged contract then its pegged token */
_depositPegged(fromToken, toChain, toAddress, amount, chain, origin);
} else {
/* otherwise its erc20 token, since we can't detect is it erc20 token it can only return insufficient balance in case of any errors */
_depositErc20(fromToken, toChain, toAddress, amount);
}
}
function _depositNative(uint256 toChain, address toAddress, uint256 totalAmount) internal {
/* sender is our from address because he is locking funds */
address fromAddress = address(msg.sender);
/* lets determine target bridge contract */
address toBridge = _bridgeAddressByChainId[toChain];
require(toBridge != address(0x00), "bad chain");
/* we need to calculate peg token contract address with meta data */
address toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), _nativeTokenMetadata.originAddress);
/* emit event with all these params */
emit DepositLocked(
toChain,
fromAddress, // who send these funds
toAddress, // who can claim these funds in "toChain" network
_nativeTokenMetadata.originAddress, // this is our current native token (e.g. ETH, MATIC, BNB, etc)
toToken, // this is an address of our target pegged token
totalAmount, // how much funds was locked in this contract
_nativeTokenMetadata // meta information about
);
}
function _depositPegged(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount, uint256 chain, address origin) internal {
/* sender is our from address because he is locking funds */
address fromAddress = address(msg.sender);
/* check allowance and transfer tokens */
require(IERC20Upgradeable(fromToken).balanceOf(fromAddress) >= totalAmount, "insufficient balance");
InternetBondType bondType = getBondType(fromToken);
uint256 amt;
if (bondType == InternetBondType.REBASING_BOND) {
amt = _peggedAmountToShares(totalAmount, getRatio(origin));
} else {
amt = totalAmount;
}
address toToken;
if (bondType == InternetBondType.NOT_BOND) {
toToken = _peggedDestinationErc20Token(fromToken, origin, toChain, chain);
} else {
toToken = _peggedDestinationErc20Bond(fromToken, origin, toChain, chain);
}
IERC20Mintable(fromToken).burn(fromAddress, amt);
Metadata memory metaData = Metadata(
Utils.stringToBytes32(IERC20Extra(fromToken).symbol()),
Utils.stringToBytes32(IERC20Extra(fromToken).name()),
chain,
origin,
createBondMetadata(0, bondType)
);
/* emit event with all these params */
emit DepositBurned(
toChain,
fromAddress, // who send these funds
toAddress, // who can claim these funds in "toChain" network
fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else)
toToken, // this is an address of our target pegged token
amt, // how much funds was locked in this contract
metaData,
origin
);
}
function _peggedAmountToShares(uint256 amount, uint256 ratio) internal pure returns (uint256) {
require(ratio > 0, "zero ratio");
return Utils.multiplyAndDivideFloor(amount, ratio, 1e18);
}
function _nativeAmountToShares(uint256 amount, uint256 ratio, uint8 decimals) internal pure returns (uint256) {
require(ratio > 0, "zero ratio");
return Utils.multiplyAndDivideFloor(amount, ratio, 10 ** decimals);
}
function _depositErc20(address fromToken, uint256 toChain, address toAddress, uint256 totalAmount) internal {
/* sender is our from address because he is locking funds */
address fromAddress = address(msg.sender);
InternetBondType bondType = getBondType(fromToken);
/* check allowance and transfer tokens */
{
uint256 balanceBefore = IERC20(fromToken).balanceOf(address(this));
uint256 allowance = IERC20(fromToken).allowance(fromAddress, address(this));
require(totalAmount <= allowance, "insufficient allowance");
require(IERC20(fromToken).transferFrom(fromAddress, address(this), totalAmount), "can't transfer");
uint256 balanceAfter = IERC20(fromToken).balanceOf(address(this));
if (bondType != InternetBondType.REBASING_BOND) {
// Assert that enough coins were transferred to bridge
require(balanceAfter >= balanceBefore + totalAmount, "incorrect behaviour");
} else {
// For rebasing internet bonds we can't assert that exactly totalAmount will be transferred
require(balanceAfter >= balanceBefore, "incorrect behaviour");
}
}
/* lets determine target bridge contract */
address toBridge = _bridgeAddressByChainId[toChain];
require(toBridge != address(0x00), "bad chain");
/* lets pack ERC20 token meta data and scale amount to 18 decimals */
uint256 chain = Utils.currentChain();
uint256 amt;
if (bondType != InternetBondType.REBASING_BOND) {
amt = _amountErc20Token(fromToken, totalAmount);
} else {
amt = _amountErc20Bond(fromToken, totalAmount, getNativeRatio(fromToken));
}
address toToken;
if (bondType == InternetBondType.NOT_BOND) {
toToken = _bridgeRouter.peggedTokenAddress(address(toBridge), fromToken);
} else {
toToken = _bridgeRouter.peggedBondAddress(address(toBridge), fromToken);
}
Metadata memory metaData = Metadata(
Utils.stringToBytes32(IERC20Extra(fromToken).symbol()),
Utils.stringToBytes32(IERC20Extra(fromToken).name()),
chain,
fromToken,
createBondMetadata(0, bondType)
);
/* emit event with all these params */
emit DepositLocked(
toChain,
fromAddress, // who send these funds
toAddress, // who can claim these funds in "toChain" network
fromToken, // this is our current native token (can be ETH, CLV, DOT, BNB or something else)
toToken, // this is an address of our target pegged token
amt, // how much funds was locked in this contract
metaData // meta information about
);
}
function _peggedDestinationErc20Token(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) {
/* lets determine target bridge contract */
address toBridge = _bridgeAddressByChainId[toChain];
require(toBridge != address(0x00), "bad chain");
require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported");
if (toChain == originChain) {
return _peggedTokenOrigin[fromToken];
} else {
return _bridgeRouter.peggedTokenAddress(address(toBridge), origin);
}
}
function _peggedDestinationErc20Bond(address fromToken, address origin, uint256 toChain, uint originChain) internal view returns (address) {
/* lets determine target bridge contract */
address toBridge = _bridgeAddressByChainId[toChain];
require(toBridge != address(0x00), "bad chain");
require(_peggedTokenOrigin[fromToken] == origin, "non-pegged contract not supported");
if (toChain == originChain) {
return _peggedTokenOrigin[fromToken];
} else {
return _bridgeRouter.peggedBondAddress(address(toBridge), origin);
}
}
function _amountErc20Token(address fromToken, uint256 totalAmount) internal returns (uint256) {
/* lets pack ERC20 token meta data and scale amount to 18 decimals */
require(IERC20Extra(fromToken).decimals() <= 18, "decimals overflow");
totalAmount *= (10 ** (18 - IERC20Extra(fromToken).decimals()));
return totalAmount;
}
function _amountErc20Bond(address fromToken, uint256 totalAmount, uint256 nativeRatio) internal returns (uint256) {
/* lets pack ERC20 token meta data and scale amount to 18 decimals */
uint8 decimals = IERC20Extra(fromToken).decimals();
require(decimals <= 18, "decimals overflow");
uint256 totalShares = _nativeAmountToShares(totalAmount, nativeRatio, decimals);
totalShares *= (10 ** (18 - decimals));
return totalShares;
}
function _currentChainNativeMetaData() internal view returns (Metadata memory) {
return _nativeTokenMetadata;
}
// WITHDRAWAL FUNCTIONS
function withdraw(
bytes calldata /* encodedProof */,
bytes calldata rawReceipt,
bytes memory proofSignature
) external nonReentrant whenNotPaused override {
uint256 proofOffset;
uint256 receiptOffset;
assembly {
proofOffset := add(0x4, calldataload(4))
receiptOffset := add(0x4, calldataload(36))
}
/* we must parse and verify that tx and receipt matches */
(EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType) = EthereumVerifier.parseTransactionReceipt(receiptOffset);
require(state.chainId == Utils.currentChain(), "receipt points to another chain");
ProofParser.Proof memory proof = ProofParser.parseProof(proofOffset);
require(_bridgeAddressByChainId[proof.chainId] == state.contractAddress, "crosschain event from not allowed contract");
state.receiptHash = keccak256(rawReceipt);
proof.status = 0x01; // execution must be successful
proof.receiptHash = state.receiptHash; // ensure that rawReceipt is preimage of receiptHash
bytes32 hash;
assembly {
hash := keccak256(proof, 0x100)
}
// we can trust receipt only if proof is signed by consensus
require(ECDSAUpgradeable.recover(hash, proofSignature) == _consensusAddress, "bad signature");
// withdraw funds to recipient
_withdraw(state, pegInType, hash);
}
function _withdraw(EthereumVerifier.State memory state, EthereumVerifier.PegInType pegInType, bytes32 proofHash) internal {
/* make sure these proofs wasn't used before */
require(!_usedProofs[proofHash], "proof already used");
_usedProofs[proofHash] = true;
if (state.toToken == _nativeTokenMetadata.originAddress) {
_withdrawNative(state);
} else if (pegInType == EthereumVerifier.PegInType.Lock) {
_withdrawPegged(state, state.fromToken);
} else if (state.toToken != state.originToken) {
// origin token is not deployed by our bridge so collision is not possible
_withdrawPegged(state, state.originToken);
} else {
_withdrawErc20(state);
}
}
function _withdrawNative(EthereumVerifier.State memory state) internal {
state.toAddress.transfer(state.totalAmount);
emit WithdrawUnlocked(
state.receiptHash,
state.fromAddress,
state.toAddress,
state.fromToken,
state.toToken,
state.totalAmount
);
}
function _withdrawPegged(EthereumVerifier.State memory state, address origin) internal {
/* create pegged token if it doesn't exist */
Metadata memory metadata = EthereumVerifier.getMetadata(state);
InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1]));
if (bondType == InternetBondType.NOT_BOND) {
_factoryPeggedToken(state.toToken, metadata);
} else {
_factoryPeggedBond(state.toToken, metadata);
}
/* mint tokens (NB: mint for bonds accepts amount in shares) */
IERC20Mintable(state.toToken).mint(state.toAddress, state.totalAmount);
/* emit peg-out event (its just informative event) */
emit WithdrawMinted(
state.receiptHash,
state.fromAddress,
state.toAddress,
state.fromToken,
state.toToken,
state.totalAmount
);
}
function _withdrawErc20(EthereumVerifier.State memory state) internal {
Metadata memory metadata = EthereumVerifier.getMetadata(state);
InternetBondType bondType = InternetBondType(uint8(metadata.bondMetadata[1]));
/* we need to rescale this amount */
uint8 decimals = IERC20Extra(state.toToken).decimals();
require(decimals <= 18, "decimals overflow");
uint256 scaledAmount = state.totalAmount / (10 ** (18 - decimals));
if (bondType == InternetBondType.REBASING_BOND) {
scaledAmount = Utils.multiplyAndDivideCeil(scaledAmount, 10 ** decimals, getNativeRatio(state.toToken));
}
/* transfer tokens and make sure behaviour is correct (just in case) */
uint256 balanceBefore = IERC20(state.toToken).balanceOf(state.toAddress);
require(IERC20Upgradeable(state.toToken).transfer(state.toAddress, scaledAmount), "can't transfer");
uint256 balanceAfter = IERC20(state.toToken).balanceOf(state.toAddress);
require(balanceBefore <= balanceAfter, "incorrect behaviour");
/* emit peg-out event (its just informative event) */
emit WithdrawUnlocked(
state.receiptHash,
state.fromAddress,
state.toAddress,
state.fromToken,
state.toToken,
state.totalAmount
);
}
// OWNER MAINTENANCE FUNCTIONS (owner functions will be reduced in future releases)
function factoryPeggedToken(uint256 fromChain, Metadata calldata metaData) external onlyOwner override {
// make sure this chain is supported
require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract");
// calc target token
address toToken = _bridgeRouter.peggedTokenAddress(address(this), metaData.originAddress);
require(_peggedTokenOrigin[toToken] == address(0x00), "already exists");
// deploy new token (its just a warmup operation)
_factoryPeggedToken(toToken, metaData);
}
function _factoryPeggedToken(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) {
address fromToken = metaData.originAddress;
/* if pegged token exist we can just return its address */
if (_peggedTokenOrigin[toToken] != address(0x00)) {
return IERC20Mintable(toToken);
}
/* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */
(bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall(
abi.encodeWithSignature("factoryPeggedToken(address,address,(bytes32,bytes32,uint256,address,bytes32),address)", fromToken, toToken, metaData, address(this))
);
if (!success) {
// preserving error message
uint256 returnLength = returnValue.length;
assembly {
revert(add(returnValue, 0x20), returnLength)
}
}
/* now we can mark this token as pegged */
_peggedTokenOrigin[toToken] = fromToken;
/* to token is our new pegged token */
return IERC20Mintable(toToken);
}
function factoryPeggedBond(uint256 fromChain, Metadata calldata metaData) external onlyOwner override {
// make sure this chain is supported
require(_bridgeAddressByChainId[fromChain] != address(0x00), "bad contract");
// calc target token
address toToken = _bridgeRouter.peggedBondAddress(address(this), metaData.originAddress);
require(_peggedTokenOrigin[toToken] == address(0x00), "already exists");
// deploy new token (its just a warmup operation)
_factoryPeggedBond(toToken, metaData);
}
function _factoryPeggedBond(address toToken, Metadata memory metaData) internal returns (IERC20Mintable) {
address fromToken = metaData.originAddress;
if (_peggedTokenOrigin[toToken] != address(0x00)) {
return IERC20Mintable(toToken);
}
/* we must use delegate call because we need to deploy new contract from bridge contract to have valid address */
(bool success, bytes memory returnValue) = address(_bridgeRouter).delegatecall(
abi.encodeWithSignature("factoryPeggedBond(address,address,(bytes32,bytes32,uint256,address,bytes32),address,address)", fromToken, toToken, metaData, address(this), address(_internetBondRatioFeed))
);
if (!success) {
// preserving error message
uint256 returnLength = returnValue.length;
assembly {
revert(add(returnValue, 0x20), returnLength)
}
}
/* now we can mark this token as pegged */
_peggedTokenOrigin[toToken] = fromToken;
/* to token is our new pegged token */
return IERC20Mintable(toToken);
}
function addAllowedContract(address allowedContract, uint256 toChain) public onlyOwner {
require(_bridgeAddressByChainId[toChain] == address(0x00), "already allowed");
require(toChain > 0, "chain id must be positive");
_bridgeAddressByChainId[toChain] = allowedContract;
emit ContractAllowed(allowedContract, toChain);
}
function removeAllowedContract(uint256 toChain) public onlyOwner {
require(_bridgeAddressByChainId[toChain] != address(0x00), "already disallowed");
require(toChain > 0, "chain id must be positive");
address wasContract = _bridgeAddressByChainId[toChain];
delete _bridgeAddressByChainId[toChain];
emit ContractDisallowed(wasContract, toChain);
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function changeConsensus(address consensus) public onlyOwner {
require(consensus != address(0x0), "zero address disallowed");
_consensusAddress = consensus;
emit ConsensusChanged(_consensusAddress);
}
function changeRouter(address router) public onlyOwner {
require(router != address(0x0), "zero address disallowed");
_bridgeRouter = BridgeRouter(router);
// We don't have special event for router change since it's very special technical contract
// In future changing router will be disallowed
}
}
|
return entire rlp item byte length
|
function itemLength(uint callDataPtr) internal pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, calldataload(callDataPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr))
itemLen := add(dataLen, add(byteLen, 1))
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
callDataPtr := add(callDataPtr, 1)
let dataLen := shr(mul(8, sub(32, byteLen)), calldataload(callDataPtr))
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
| 7,027,129
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.